Skip to content

Commit d3413bb

Browse files
AnnaR-progclaude
andauthored
fix(holdoff): count a 429 burst as one strike (MAG-4386) (#536)
Part 1 of MAG-4370. RecordRateLimit added a strike for every 429, including the ones that land while the url is already held off. A vendor's per-second quota answers a burst with one 429 per request in flight, so seven 429s inside one second took a 30 s hold-off to the 30-minute cap: 31 min with jitter on main, and QuickNode's 28 real 429s in about 2 s gave 31-35 min in the 2026-10-15 real-node run. A strike is now a hold-off that ended in another 429. A 429 inside a standing hold-off adds no strike and leaves the hold-off where it was, and RecordRateLimit returns what is left of it. That return is what ChainTracker.noteFetchOutcome stores as its own wait and hands to the start retry; every other caller only logs it. A Retry-After longer than what is left extends the hold-off to the ask, still without a strike. The provider-name escalation is checked on every 429, as before. The recorded counter and the duration histogram now count hold-offs applied, so a burst counts once. x-ratelimit-reset and RateLimit-Reset are deliberately not read. Retry-After floors the hold-off under the 30 s first strike, so QuickNode's x-ratelimit-reset: 1 would change nothing. The header's unit differs by vendor (delta-seconds, epoch seconds, milliseconds), and under the floor rule a misread can only lengthen a hold-off. The relay path never sees the header anyway: the reply-header filter (MAG-3104) keeps only Retry-After and Date before httpStatusRelayError types the 429. Tests: TestBurstWithinOneHoldoffIsOneStrike, TestLongerRetryAfterInsideTheWindowExtendsWithoutAStrike and TestMetrics_BurstRecordsOneHoldoff fail on main. Seven existing tests recorded back-to-back 429s on a fixed clock as consecutive strikes. They now let each hold-off run out first, or assert the one-strike floor: TestConsecutiveStrikesDoubleUpToCap, TestRetryAfterIsTheFloor, TestAnswerClearsStrikesAndHoldoff, TestStrikeMemoryAgesOut, TestNoteFetchOutcome_NoAnswerKeepsTheHoldoff, TestNoteFetchOutcome_OwnRateLimitDoesNotHoldTheProviderForRelays and TestReplayFailingRelay_RecoveredClearsHoldoff. Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent e7c6e4c commit d3413bb

7 files changed

Lines changed: 150 additions & 26 deletions

File tree

‎docs/METRICS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ signal that an upstream is refusing us for load.
385385

386386
| Metric | Type | Labels | Description |
387387
| --- | --- | --- | --- |
388-
| `smartrouter_rate_limit_holdoffs_total` | Counter | `provider`, `event` | Registry events. `event` is the closed set `recorded` (a 429 held an endpoint off), `escalated` (the hold-off widened to the whole provider name — counted once on the transition, not per refresh), `cleared` (an answer dropped a standing penalty — not counted when there was nothing to clear). |
388+
| `smartrouter_rate_limit_holdoffs_total` | Counter | `provider`, `event` | Registry events. `event` is the closed set `recorded` (a 429 held an endpoint off — a new hold-off, or a Retry-After that extended one; a 429 inside a standing hold-off changes nothing and is not counted, so a burst counts once), `escalated` (the hold-off widened to the whole provider name — counted once on the transition, not per refresh), `cleared` (an answer dropped a standing penalty — not counted when there was nothing to clear). |
389389
| `smartrouter_rate_limit_holdoff_seconds` | Histogram | `provider` | Applied hold-off duration per `recorded` event, in **seconds** (buckets `15, 30, 60, 120, 300, 600, 1800, 3600` — not the shared millisecond latency buckets). Shows upstream `Retry-After` magnitudes against the exponential default. |
390390

391391
`provider` is the configured provider name on the relay / probe / re-verify paths. The

‎docs/RATE-LIMIT-HOLDOFF.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,20 @@ another registry, and tests use `NewRegistry` or the jitter-free `NewRegistryWit
1919
consecutive strike, capped at 30m before jitter. Jitter extends each hold-off by up to
2020
+20% and never shortens it, so a fleet held off by one vendor-wide limit does not return
2121
in a synchronized burst.
22+
- **One strike per hold-off.** A strike is a hold-off that ended in another 429, not a
23+
429. A 429 that arrives while the URL is still held off adds no strike and leaves the
24+
hold-off where it is — `RecordRateLimit` returns what is left of it — unless its
25+
Retry-After asks for longer, which extends the hold-off to the ask, still without a
26+
strike. A vendor's per-second quota answers a burst with one 429 per request already in
27+
flight; counted one strike each, seven 429s inside one second took a 30s hold-off to
28+
the 30m cap (MAG-4386: QuickNode, 28 real 429s in about 2s, 31-35 min). The
29+
provider-name escalation is still checked on every 429.
30+
- **Only Retry-After is read.** Vendor quota headers are not: QuickNode answers a 429 with
31+
`x-ratelimit-reset: 1` and no Retry-After. Under the floor rule a window shorter than
32+
the 30s first hold-off changes nothing; the header's unit differs by vendor
33+
(delta-seconds, epoch seconds, milliseconds), and the floor rule means a misread can
34+
only lengthen a hold-off; and the relay path never sees it, because the reply-header
35+
filter (MAG-3104) keeps only Retry-After and Date before the 429 is typed.
2236
- **Any answer clears.** An upstream that answered a request — success or a genuine
2337
failure — is no longer refusing us for load: the URL's strikes and the provider
2438
escalation are dropped, and later failures reach their normal handling at the normal

‎protocol/chaintracker/rate_limit_holdoff_test.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,9 @@ func TestNoteFetchOutcome_NoAnswerKeepsTheHoldoff(t *testing.T) {
177177
cs.noteFetchOutcome(errors.New("dial tcp 10.0.0.1:443: connect: connection refused"))
178178
require.True(t, registry.HeldOff(holdoffTestURL, holdoffTestURL), "a fetch with no answer must not clear the hold-off")
179179

180-
// The strike survived: the next refusal escalates instead of starting over.
180+
// The strike survived: the next refusal escalates instead of starting over. It comes after the
181+
// hold-off ran out, as the floored poll's would; one inside it is no new strike (MAG-4386).
182+
now = now.Add(holdoff.InitialHoldoff + time.Second)
181183
require.Equal(t, 2*holdoff.InitialHoldoff, cs.noteFetchOutcome(common.RateLimited(errors.New("json-rpc error 429"), 0)))
182184

183185
cs.noteFetchOutcome(nil)
@@ -206,7 +208,9 @@ func TestNoteFetchOutcome_OwnRateLimitDoesNotHoldTheProviderForRelays(t *testing
206208
require.False(t, providerHeld, "a polled leg's 429 must not take the provider out of relay selection")
207209
require.False(t, registry.HeldOff(holdoffTestProvider, holdoffTestURL), "nothing lands under the relay path's key")
208210
require.True(t, registry.HeldOff(holdoffTestURL, holdoffTestURL), "the url itself is held, as the ws and gRPC paths key it")
209-
require.Greater(t, cs.computePollInterval(0, 0), holdoff.InitialHoldoff, "and the poll still waits its own hold-off out")
211+
got := cs.computePollInterval(0, 0)
212+
require.Greater(t, got, holdoff.InitialHoldoff-time.Second, "and the poll still waits its own hold-off out")
213+
require.LessOrEqual(t, got, holdoff.InitialHoldoff, "three refusals inside one hold-off are one strike (MAG-4386)")
210214
}
211215

212216
// Any answer from the url clears: a relay serving the url fine — recorded by the relay path under

‎protocol/holdoff/burst_test.go‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package holdoff
2+
3+
import (
4+
"testing"
5+
"time"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
// A vendor's per-second quota answers a burst with many 429s inside one window. Each used to add
11+
// a strike, so seven 429s in one second escalated a 30 s hold-off to the 30-minute cap
12+
// (MAG-4386, measured on QuickNode: 28 real 429s in ~2 s held the url off for 31-35 min). A 429
13+
// that lands while the url is already held off adds nothing: the burst is one strike, and the
14+
// hold-off still ends when the first one said.
15+
func TestBurstWithinOneHoldoffIsOneStrike(t *testing.T) {
16+
r, now := newTestRegistry(t0)
17+
18+
first := r.RecordRateLimit("vendor", "u", 0)
19+
require.Equal(t, InitialHoldoff, first)
20+
21+
for i := 1; i < 7; i++ {
22+
*now = t0.Add(time.Duration(i) * 100 * time.Millisecond)
23+
remaining := r.RecordRateLimit("vendor", "u", 0)
24+
require.Equal(t, t0.Add(InitialHoldoff).Sub(*now), remaining,
25+
"429 #%d inside the window reports what is left of the hold-off, not a new one", i+1)
26+
}
27+
require.Equal(t, t0.Add(InitialHoldoff), r.ReadyAt("vendor", "u"),
28+
"the burst did not move the end of the hold-off")
29+
30+
// The window passes; the next 429 is the second strike, not the eighth.
31+
*now = t0.Add(InitialHoldoff + time.Second)
32+
require.Equal(t, 2*InitialHoldoff, r.RecordRateLimit("vendor", "u", 0))
33+
}
34+
35+
// An upstream that asks for longer than what is left gets it, and that is still not a strike.
36+
func TestLongerRetryAfterInsideTheWindowExtendsWithoutAStrike(t *testing.T) {
37+
r, now := newTestRegistry(t0)
38+
r.RecordRateLimit("vendor", "u", 0) // strike 1: 30 s
39+
40+
*now = t0.Add(time.Second)
41+
require.Equal(t, 5*time.Minute, r.RecordRateLimit("vendor", "u", 5*time.Minute))
42+
require.Equal(t, t0.Add(time.Second+5*time.Minute), r.ReadyAt("vendor", "u"))
43+
44+
// A shorter ask inside the window never shortens it.
45+
*now = t0.Add(2 * time.Second)
46+
require.Equal(t, 5*time.Minute-time.Second, r.RecordRateLimit("vendor", "u", time.Second))
47+
require.Equal(t, t0.Add(time.Second+5*time.Minute), r.ReadyAt("vendor", "u"))
48+
49+
// Past it, the next 429 is the second strike: the extension did not count as one.
50+
*now = t0.Add(time.Second + 5*time.Minute + time.Second)
51+
require.Equal(t, 2*InitialHoldoff, r.RecordRateLimit("vendor", "u", 0))
52+
}
53+
54+
// A 429 that changes nothing is not a recorded hold-off: the burst shows once on the
55+
// recorded counter and once in the duration histogram, an extension shows as one more.
56+
func TestMetrics_BurstRecordsOneHoldoff(t *testing.T) {
57+
r, now := newTestRegistry(t0)
58+
base := eventCount(t, "vendorBurst", eventRecorded)
59+
60+
r.RecordRateLimit("vendorBurst", "u", 0)
61+
for i := 1; i < 7; i++ {
62+
*now = t0.Add(time.Duration(i) * 100 * time.Millisecond)
63+
r.RecordRateLimit("vendorBurst", "u", 0)
64+
}
65+
require.Equal(t, base+1, eventCount(t, "vendorBurst", eventRecorded))
66+
67+
r.RecordRateLimit("vendorBurst", "u", 10*time.Minute)
68+
require.Equal(t, base+2, eventCount(t, "vendorBurst", eventRecorded), "an extension is a hold-off applied")
69+
}

‎protocol/holdoff/holdoff.go‎

Lines changed: 46 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@
1616
// the point: a fleet held off by one vendor-wide limit must not return in a
1717
// synchronized burst.
1818
//
19+
// - One strike per hold-off. A 429 that arrives while the URL is still held off adds no
20+
// strike and does not move the hold-off, unless its Retry-After asks for longer than
21+
// what is left. A burst refused inside one quota window is one refusal, not one per
22+
// request that was in flight.
23+
//
1924
// - Any answer clears. An upstream that answered a request — even with a genuine
2025
// failure — is no longer refusing us for load, so the URL's strikes and the
2126
// provider escalation are dropped and later failures reach their normal handling
@@ -109,8 +114,15 @@ func NewRegistryWithClock(now func() time.Time) *Registry {
109114
}
110115

111116
// RecordRateLimit notes a 429 from url, owned by provider. retryAfter is what the
112-
// upstream asked for (0 when it said nothing) and floors the hold-off. Returns the
113-
// applied hold-off so callers can log what was decided.
117+
// upstream asked for (0 when it said nothing) and floors the hold-off. Returns how long
118+
// url is now held off, so callers can log what was decided and hand it on as a wait.
119+
//
120+
// A strike is a hold-off that ended in another 429, not a 429. One that lands while url is
121+
// still held off is the same refusal again: a vendor's per-second quota answers a burst with
122+
// a 429 per request already in flight, and counting each as a strike took one second of them
123+
// to the 30-minute cap (MAG-4386). It adds no strike and leaves the hold-off where it was —
124+
// the return is what is left of it — unless the upstream asked for longer than that, which
125+
// extends the hold-off to the ask, still without a strike.
114126
func (r *Registry) RecordRateLimit(provider, url string, retryAfter time.Duration) time.Duration {
115127
r.mu.Lock()
116128
defer r.mu.Unlock()
@@ -128,25 +140,29 @@ func (r *Registry) RecordRateLimit(provider, url string, retryAfter time.Duratio
128140
ps.urls[url] = e
129141
}
130142

131-
e.strikes++
132-
d := exponentialFor(e.strikes)
133-
if retryAfter > d {
134-
d = retryAfter
135-
}
136-
if d > maxUpstreamHoldoff {
137-
d = maxUpstreamHoldoff
138-
}
139-
d += time.Duration(r.randFloat() * JitterFactor * float64(d))
140-
if d > maxUpstreamHoldoff {
141-
d = maxUpstreamHoldoff
142-
}
143-
e.readyAt = now.Add(d)
144143
e.lastSeen = now
145-
metricRecorded(provider, d)
144+
if e.readyAt.After(now) {
145+
if retryAfter > e.readyAt.Sub(now) {
146+
if d := r.boundedWithJitterLocked(retryAfter); now.Add(d).After(e.readyAt) {
147+
e.readyAt = now.Add(d)
148+
metricRecorded(provider, d)
149+
}
150+
}
151+
} else {
152+
e.strikes++
153+
d := exponentialFor(e.strikes)
154+
if retryAfter > d {
155+
d = retryAfter
156+
}
157+
d = r.boundedWithJitterLocked(d)
158+
e.readyAt = now.Add(d)
159+
metricRecorded(provider, d)
160+
}
146161

147162
// Escalate when enough distinct URLs of this provider are held off at once. The
148163
// provider-wide hold-off ends when its longest-held member does — and any answered
149-
// request drops it sooner.
164+
// request drops it sooner. Checked on every 429, a repeat included, as before: which
165+
// URLs are held is the question, not whether this 429 added a strike.
150166
held := 0
151167
latest := time.Time{}
152168
for _, ue := range ps.urls {
@@ -163,6 +179,19 @@ func (r *Registry) RecordRateLimit(provider, url string, retryAfter time.Duratio
163179
}
164180
ps.escalatedUntil = latest
165181
}
182+
return e.readyAt.Sub(now)
183+
}
184+
185+
// boundedWithJitterLocked bounds a hold-off at maxUpstreamHoldoff and extends it by the
186+
// jitter, bounded again so the worst case stays within the parser's limit. Called under mu.
187+
func (r *Registry) boundedWithJitterLocked(d time.Duration) time.Duration {
188+
if d > maxUpstreamHoldoff {
189+
d = maxUpstreamHoldoff
190+
}
191+
d += time.Duration(r.randFloat() * JitterFactor * float64(d))
192+
if d > maxUpstreamHoldoff {
193+
d = maxUpstreamHoldoff
194+
}
166195
return d
167196
}
168197

‎protocol/holdoff/holdoff_test.go‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,27 +25,31 @@ func TestFirstStrikeUsesInitialHoldoff(t *testing.T) {
2525
require.Equal(t, t0.Add(InitialHoldoff), r.ReadyAt("vendor", "https://a.example/eth"))
2626
}
2727

28+
// A strike is a hold-off that ended in another 429, so each 429 here lands just after the
29+
// previous hold-off ran out (a 429 inside one is no strike: TestBurstWithinOneHoldoffIsOneStrike).
2830
func TestConsecutiveStrikesDoubleUpToCap(t *testing.T) {
29-
r, _ := newTestRegistry(t0)
31+
r, now := newTestRegistry(t0)
3032
want := []time.Duration{
3133
30 * time.Second, time.Minute, 2 * time.Minute, 4 * time.Minute,
3234
8 * time.Minute, 16 * time.Minute, 30 * time.Minute, 30 * time.Minute,
3335
}
3436
for i, w := range want {
3537
d := r.RecordRateLimit("vendor", "u", 0)
3638
require.Equal(t, w, d, "strike %d", i+1)
39+
*now = now.Add(d + time.Second)
3740
}
3841
}
3942

4043
func TestRetryAfterIsTheFloor(t *testing.T) {
41-
r, _ := newTestRegistry(t0)
44+
r, now := newTestRegistry(t0)
4245

4346
// Larger than the exponential: the vendor's ask wins.
4447
d := r.RecordRateLimit("vendor", "u", 10*time.Minute)
4548
require.Equal(t, 10*time.Minute, d)
4649

4750
// Smaller than the current exponential: the exponential wins (a vendor asking for
4851
// 1s on the second consecutive strike does not shrink the penalty).
52+
*now = t0.Add(10*time.Minute + time.Second)
4953
d = r.RecordRateLimit("vendor", "u", time.Second)
5054
require.Equal(t, time.Minute, d)
5155
}
@@ -66,9 +70,10 @@ func TestJitterOnlyExtends(t *testing.T) {
6670
}
6771

6872
func TestAnswerClearsStrikesAndHoldoff(t *testing.T) {
69-
r, _ := newTestRegistry(t0)
70-
r.RecordRateLimit("vendor", "u", 0)
73+
r, now := newTestRegistry(t0)
7174
r.RecordRateLimit("vendor", "u", 0)
75+
*now = t0.Add(InitialHoldoff + time.Second)
76+
r.RecordRateLimit("vendor", "u", 0) // second strike: held off until t0+31s+1m
7277
require.True(t, r.HeldOff("vendor", "u"))
7378

7479
r.RecordAnswer("vendor", "u")
@@ -127,10 +132,11 @@ func TestHoldoffExpires(t *testing.T) {
127132
func TestStrikeMemoryAgesOut(t *testing.T) {
128133
r, now := newTestRegistry(t0)
129134
r.RecordRateLimit("vendor", "u", 0)
135+
*now = t0.Add(InitialHoldoff + time.Second)
130136
r.RecordRateLimit("vendor", "u", 0) // 2 strikes, next would be 2m
131137

132138
// Past the retention window with no further 429s, the URL starts clean.
133-
*now = t0.Add(entryRetention + 2*time.Minute)
139+
*now = t0.Add(InitialHoldoff + time.Second + entryRetention + 2*time.Minute)
134140
d := r.RecordRateLimit("vendor", "u", 0)
135141
require.Equal(t, InitialHoldoff, d)
136142
}

‎protocol/rpcsmartrouter/relay_rate_limit_test.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,10 @@ func TestReplayFailingRelay_RecoveredClearsHoldoff(t *testing.T) {
9090
reg := holdoff.NewRegistryWithClock(func() time.Time { return now })
9191
relayHoldoff = reg
9292

93-
// Two strikes, then let the hold-off expire.
93+
// Two strikes, then let the hold-off expire. A strike is a hold-off that ended in another
94+
// 429, so the second comes after the first ran out (MAG-4386).
9495
reg.RecordRateLimit("provider1", "http://fake:8545", 0)
96+
now = now.Add(holdoff.InitialHoldoff + time.Second)
9597
reg.RecordRateLimit("provider1", "http://fake:8545", 0)
9698
now = now.Add(2 * time.Minute)
9799
require.False(t, reg.HeldOff("provider1", "http://fake:8545"))

0 commit comments

Comments
 (0)