Skip to content

Commit 487f324

Browse files
committed
fix(gauges): survive Blockscout rate limiting on mainnet
Mainnet Blockscout 429s well below our fan-out, so any uncached gauge returned 500. Adds a process-wide paced request queue with 429-aware retries and a stale-while-revalidate cache in front of gauge logs, and returns a retryable 503 instead of an opaque 500.
1 parent 0daf126 commit 487f324

7 files changed

Lines changed: 754 additions & 23 deletions
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import type { Hex } from 'viem'
2+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3+
4+
import { buildGaugeEventsResponse } from './fetch-gauge-events'
5+
6+
vi.mock('@/lib/constants', () => ({
7+
BLOCKSCOUT_URL: 'https://blockscout.test',
8+
EVENTS_FROM_BLOCK: 6958707,
9+
}))
10+
11+
vi.mock('@/lib/logger', () => ({
12+
logger: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
13+
}))
14+
15+
const TOPIC: Hex = '0x72421f1eeaa316f3b67618996c0df193d45328d3645bb1866b6beb11a0c8230e'
16+
const ROUTE = '/api/gauges/backer-rewards-claimed'
17+
18+
const GAUGE_A = '0xa7671bd525f529b60bf9f6c28fbe5d64f2cd0d73'
19+
const GAUGE_B = '0x0e6ee0c15a701a9d8b8449615a2a1ee017aa22e5'
20+
21+
const request = (query: string) => new Request(`https://app.test${ROUTE}?${query}`)
22+
23+
const emptyLogsResponse = () =>
24+
new Response(JSON.stringify({ status: '0', message: 'No logs found', result: [] }), { status: 200 })
25+
26+
const rateLimitedResponse = () =>
27+
new Response(
28+
JSON.stringify({ status: '0', message: 'Too many requests. Increase limits now', result: null }),
29+
{ status: 429, headers: { 'x-ratelimit-limit': '10', 'x-ratelimit-remaining': '0' } },
30+
)
31+
32+
describe('buildGaugeEventsResponse', () => {
33+
const originalFetch = global.fetch
34+
35+
beforeEach(() => {
36+
vi.restoreAllMocks()
37+
})
38+
39+
afterEach(() => {
40+
global.fetch = originalFetch
41+
})
42+
43+
it('rejects a missing gauges param', async () => {
44+
const response = await buildGaugeEventsResponse(request('') as Request, TOPIC, ROUTE)
45+
expect(response.status).toBe(400)
46+
})
47+
48+
it('returns a log map keyed by gauge when every gauge resolves', async () => {
49+
global.fetch = vi.fn().mockImplementation(async () => emptyLogsResponse())
50+
51+
const response = await buildGaugeEventsResponse(
52+
request(`gauges=${GAUGE_A},${GAUGE_B}`),
53+
TOPIC,
54+
ROUTE,
55+
)
56+
57+
expect(response.status).toBe(200)
58+
await expect(response.json()).resolves.toEqual({ [GAUGE_A]: [], [GAUGE_B]: [] })
59+
})
60+
61+
it('answers 503 with Retry-After and the failing gauges instead of an opaque 500', async () => {
62+
global.fetch = vi.fn().mockImplementation(async (input: string | URL) => {
63+
return String(input).includes(GAUGE_B) ? rateLimitedResponse() : emptyLogsResponse()
64+
})
65+
66+
const response = await buildGaugeEventsResponse(
67+
request(`gauges=${GAUGE_A},${GAUGE_B}`),
68+
TOPIC,
69+
ROUTE,
70+
)
71+
72+
expect(response.status).toBe(503)
73+
expect(response.headers.get('Retry-After')).toBe('5')
74+
75+
const body = await response.json()
76+
expect(body.failedGauges).toEqual([GAUGE_B])
77+
// Never surface a partial map: the client reads missing gauges as "nothing claimed".
78+
expect(body).not.toHaveProperty(GAUGE_A)
79+
})
80+
})

‎src/app/api/gauges/_lib/fetch-gauge-events.ts‎

Lines changed: 103 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import { NextResponse } from 'next/server'
22
import { type Address, type Hex, isAddress, type RpcLog } from 'viem'
33

4-
import { fetchLogsByTopic } from '@/lib/blockscout/fetch-logs-by-topic'
4+
import { fetchLogsByTopic, type RpcLogWithTimestamp } from '@/lib/blockscout/fetch-logs-by-topic'
5+
import { StaleWhileRevalidateCache } from '@/lib/blockscout/stale-while-revalidate-cache'
56
import { EVENTS_FROM_BLOCK } from '@/lib/constants'
67
import { logger } from '@/lib/logger'
78

@@ -13,18 +14,64 @@ export const GAUGE_EVENTS_REVALIDATE_SECONDS = 25
1314
*/
1415
export const MAX_GAUGES_PER_REQUEST = 200
1516

17+
/**
18+
* How long a gauge's logs are served without touching Blockscout. Matches the client's own poll
19+
* interval (`AVERAGE_BLOCKTIME`), so a steady-state page costs at most one upstream call per gauge
20+
* per block instead of one per tab per block.
21+
*/
22+
const GAUGE_LOGS_FRESH_MS = 60_000
23+
24+
/**
25+
* How long logs may still be served while refreshing in the background — and, if Blockscout is
26+
* failing, instead of erroring. These events are append-only history; stale is far better than 500.
27+
*/
28+
const GAUGE_LOGS_STALE_MS = 15 * 60_000
29+
30+
/** ~200 gauges × 3 topics, with headroom. */
31+
const GAUGE_LOGS_MAX_ENTRIES = 750
32+
33+
/** Advertised to clients when every gauge failed, so retries are spaced instead of immediate. */
34+
const RETRY_AFTER_SECONDS = 5
35+
1636
export type GaugeEventsResponse = Record<Address, RpcLog[]>
1737

38+
/**
39+
* Process-wide cache of gauge logs, keyed by topic + gauge + block floor.
40+
*
41+
* This is the load-bearing part of the Blockscout rate-limit mitigation: pacing alone (see
42+
* `request-throttle.ts`) only spreads the same volume of requests over time, which would make cold
43+
* responses unacceptably slow. Not asking twice is what keeps us inside the budget.
44+
*/
45+
const gaugeLogsCache = new StaleWhileRevalidateCache<RpcLogWithTimestamp[]>({
46+
freshMs: GAUGE_LOGS_FRESH_MS,
47+
staleMs: GAUGE_LOGS_STALE_MS,
48+
maxEntries: GAUGE_LOGS_MAX_ENTRIES,
49+
})
50+
51+
/** Exposed for tests; production code should never need to drop the cache. */
52+
export function clearGaugeLogsCache(): void {
53+
gaugeLogsCache.clear()
54+
}
55+
56+
function cacheKey(topic0: Hex, gauge: Address, fromBlock: string): string {
57+
return `${topic0.toLowerCase()}|${gauge.toLowerCase()}|${fromBlock}`
58+
}
59+
1860
/**
1961
* Shared handler for `/api/gauges/<event>` route handlers.
2062
*
2163
* Query params:
2264
* - `gauges` (required): comma-separated gauge addresses.
2365
* - `fromBlock` (optional): decimal block number; defaults to `EVENTS_FROM_BLOCK`.
2466
*
25-
* Fetches Blockscout `getLogs` per gauge in parallel for the given `topic0`. Each underlying
26-
* `fetch` opts into Next.js Data Cache via `next.revalidate`, so concurrent requests within the
27-
* window share a single Blockscout round-trip.
67+
* Fetches Blockscout `getLogs` per gauge for the given `topic0`, behind a stale-while-revalidate
68+
* cache and a process-wide paced request queue. Gauges are resolved with `allSettled` so one
69+
* failure is reported precisely instead of collapsing the whole batch into an opaque error.
70+
*
71+
* @remarks
72+
* Responses stay all-or-nothing on purpose. The client does `eventsByGauge[gauge] ?? []`, so
73+
* omitting a failed gauge would silently render it as "no rewards claimed" — wrong numbers are
74+
* worse than a retryable error here.
2875
*/
2976
export async function buildGaugeEventsResponse(req: Request, topic0: Hex, route: string): Promise<Response> {
3077
const url = new URL(req.url)
@@ -52,26 +99,60 @@ export async function buildGaugeEventsResponse(req: Request, topic0: Hex, route:
5299
const fromBlock =
53100
fromBlockParam && /^\d+$/.test(fromBlockParam) ? fromBlockParam : EVENTS_FROM_BLOCK.toString()
54101

55-
try {
56-
const results = await Promise.all(
57-
gauges.map(gauge =>
58-
fetchLogsByTopic({
59-
address: gauge,
60-
topic0,
61-
fromBlock,
62-
fetchInit: { next: { revalidate: GAUGE_EVENTS_REVALIDATE_SECONDS } },
63-
}),
102+
const results = await Promise.allSettled(
103+
gauges.map(gauge =>
104+
gaugeLogsCache.getOrLoad(
105+
cacheKey(topic0, gauge, fromBlock),
106+
async () => {
107+
const { data } = await fetchLogsByTopic({
108+
address: gauge,
109+
topic0,
110+
fromBlock,
111+
fetchInit: { next: { revalidate: GAUGE_EVENTS_REVALIDATE_SECONDS } },
112+
})
113+
return data
114+
},
115+
err => logger.warn({ err, route, topic0, gauge }, 'Background refresh of gauge logs failed'),
64116
),
65-
)
117+
),
118+
)
66119

67-
const eventsByGauge: GaugeEventsResponse = {}
68-
gauges.forEach((gauge, i) => {
69-
eventsByGauge[gauge] = results[i].data
70-
})
120+
const eventsByGauge: GaugeEventsResponse = {}
121+
const failures: Array<{ gauge: Address; reason: unknown }> = []
71122

72-
return NextResponse.json(eventsByGauge)
73-
} catch (err) {
74-
logger.error({ err, route, topic0 }, 'Error fetching gauge events from Blockscout')
75-
return NextResponse.json({ error: 'Failed to fetch gauge events' }, { status: 500 })
123+
results.forEach((result, i) => {
124+
const gauge = gauges[i]
125+
if (result.status === 'fulfilled') {
126+
eventsByGauge[gauge] = result.value
127+
} else {
128+
failures.push({ gauge, reason: result.reason })
129+
}
130+
})
131+
132+
if (failures.length > 0) {
133+
logger.error(
134+
{
135+
route,
136+
topic0,
137+
fromBlock,
138+
failedCount: failures.length,
139+
totalCount: gauges.length,
140+
failures: failures.map(({ gauge, reason }) => ({
141+
gauge,
142+
err: reason instanceof Error ? reason.message : String(reason),
143+
})),
144+
},
145+
'Error fetching gauge events from Blockscout',
146+
)
147+
148+
return NextResponse.json(
149+
{
150+
error: 'Failed to fetch gauge events',
151+
failedGauges: failures.map(({ gauge }) => gauge),
152+
},
153+
{ status: 503, headers: { 'Retry-After': String(RETRY_AFTER_SECONDS) } },
154+
)
76155
}
156+
157+
return NextResponse.json(eventsByGauge)
77158
}

‎src/lib/blockscout/fetch-blockscout-get-logs-paginated.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import type { Address, Hex } from 'viem'
33
import { BLOCKSCOUT_URL } from '@/lib/constants'
44
import type { BackendEventByTopic0ResponseValue } from '@/shared/utils'
55

6+
import { throttledBlockscoutFetch } from './request-throttle'
7+
68
/**
79
* Max getLogs pages per call chain to cap explorer load (same as legacy `fetchLogsByTopic`).
810
* Beyond this, pagination stops and returned logs may be incomplete—monitor if that becomes likely.
@@ -106,6 +108,8 @@ function buildPageParams(query: BlockscoutGetLogsQuery, fromBlock: string): Reco
106108
* @returns Raw log rows as returned by Blockscout (includes `timeStamp` for server-side use).
107109
*
108110
* @remarks
111+
* - Every page goes through {@link throttledBlockscoutFetch}, so calls are paced process-wide and
112+
* retried on 429/5xx. Expect wall-clock time to grow with page count under contention.
109113
* - If pagination reaches {@link BLOCKSCOUT_GET_LOGS_MAX_PAGES}, fetching stops and the result set may be truncated.
110114
* - **Empty `getLogs` responses:** Blockscout sometimes returns `status: '0'` with `result` `null` or `[]` when no
111115
* logs match (e.g. message `No records found`). That is treated as a normal empty page—pagination ends and the
@@ -160,7 +164,8 @@ export async function fetchBlockscoutGetLogsPaginated({
160164
url.searchParams.append(key, value)
161165
}
162166

163-
const response = await fetch(url.toString(), {
167+
// Paced + retried: Blockscout rate-limits per IP and answers 429 well below our natural fan-out.
168+
const response = await throttledBlockscoutFetch(url.toString(), {
164169
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
165170
...fetchInit,
166171
})
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2+
3+
import {
4+
configureBlockscoutThrottle,
5+
resetBlockscoutThrottle,
6+
throttledBlockscoutFetch,
7+
} from './request-throttle'
8+
9+
const jsonResponse = (status: number, headers: Record<string, string> = {}) =>
10+
new Response(JSON.stringify({ status: status === 200 ? '1' : '0', result: [] }), {
11+
status,
12+
headers,
13+
})
14+
15+
describe('throttledBlockscoutFetch', () => {
16+
const originalFetch = global.fetch
17+
18+
beforeEach(() => {
19+
resetBlockscoutThrottle()
20+
})
21+
22+
afterEach(() => {
23+
global.fetch = originalFetch
24+
resetBlockscoutThrottle()
25+
})
26+
27+
it('returns a successful response without retrying', async () => {
28+
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(200))
29+
global.fetch = fetchMock
30+
31+
const response = await throttledBlockscoutFetch('https://blockscout.test/api')
32+
33+
expect(response.status).toBe(200)
34+
expect(fetchMock).toHaveBeenCalledTimes(1)
35+
})
36+
37+
it('retries on 429 and resolves once the rate limit clears', async () => {
38+
configureBlockscoutThrottle({ maxAttempts: 3, maxBackoffMs: 5, minIntervalMs: 0 })
39+
40+
const fetchMock = vi
41+
.fn()
42+
.mockResolvedValueOnce(jsonResponse(429, { 'x-ratelimit-limit': '10' }))
43+
.mockResolvedValueOnce(jsonResponse(429, { 'x-ratelimit-limit': '10' }))
44+
.mockResolvedValueOnce(jsonResponse(200))
45+
global.fetch = fetchMock
46+
47+
const response = await throttledBlockscoutFetch('https://blockscout.test/api')
48+
49+
expect(response.status).toBe(200)
50+
expect(fetchMock).toHaveBeenCalledTimes(3)
51+
})
52+
53+
it('returns the last response unread when retries are exhausted, leaving error handling to the caller', async () => {
54+
configureBlockscoutThrottle({ maxAttempts: 2, maxBackoffMs: 5, minIntervalMs: 0 })
55+
56+
// A fresh Response per attempt: reusing one object would leak `bodyUsed` across attempts.
57+
const fetchMock = vi.fn().mockImplementation(async () => jsonResponse(429))
58+
global.fetch = fetchMock
59+
60+
const response = await throttledBlockscoutFetch('https://blockscout.test/api')
61+
62+
expect(response.status).toBe(429)
63+
expect(response.bodyUsed).toBe(false)
64+
expect(fetchMock).toHaveBeenCalledTimes(2)
65+
})
66+
67+
it('does not retry non-retryable statuses', async () => {
68+
configureBlockscoutThrottle({ maxAttempts: 4, maxBackoffMs: 5, minIntervalMs: 0 })
69+
70+
const fetchMock = vi.fn().mockResolvedValue(jsonResponse(400))
71+
global.fetch = fetchMock
72+
73+
const response = await throttledBlockscoutFetch('https://blockscout.test/api')
74+
75+
expect(response.status).toBe(400)
76+
expect(fetchMock).toHaveBeenCalledTimes(1)
77+
})
78+
79+
it('propagates transport errors after exhausting attempts', async () => {
80+
configureBlockscoutThrottle({ maxAttempts: 2, maxBackoffMs: 5, minIntervalMs: 0 })
81+
82+
const fetchMock = vi.fn().mockRejectedValue(new Error('socket hang up'))
83+
global.fetch = fetchMock
84+
85+
await expect(throttledBlockscoutFetch('https://blockscout.test/api')).rejects.toThrow(
86+
'socket hang up',
87+
)
88+
expect(fetchMock).toHaveBeenCalledTimes(2)
89+
})
90+
91+
it('serializes concurrent calls and paces them by minIntervalMs', async () => {
92+
configureBlockscoutThrottle({ maxConcurrency: 1, minIntervalMs: 40, maxAttempts: 1 })
93+
94+
let inFlight = 0
95+
let maxInFlight = 0
96+
const startTimes: number[] = []
97+
98+
global.fetch = vi.fn().mockImplementation(async () => {
99+
startTimes.push(Date.now())
100+
inFlight += 1
101+
maxInFlight = Math.max(maxInFlight, inFlight)
102+
await new Promise(resolve => setTimeout(resolve, 5))
103+
inFlight -= 1
104+
return jsonResponse(200)
105+
})
106+
107+
await Promise.all(
108+
Array.from({ length: 3 }, () => throttledBlockscoutFetch('https://blockscout.test/api')),
109+
)
110+
111+
expect(maxInFlight).toBe(1)
112+
// Three requests at >=40ms spacing cannot finish faster than two intervals.
113+
expect(startTimes[2] - startTimes[0]).toBeGreaterThanOrEqual(70)
114+
})
115+
116+
it('clamps an absurd x-ratelimit-reset to maxBackoffMs', async () => {
117+
configureBlockscoutThrottle({ maxAttempts: 2, maxBackoffMs: 30, minIntervalMs: 0 })
118+
119+
// Mainnet Blockscout reports resets tens of minutes out; using it verbatim would hang the request.
120+
const fetchMock = vi
121+
.fn()
122+
.mockResolvedValueOnce(jsonResponse(429, { 'x-ratelimit-reset': '2893988' }))
123+
.mockResolvedValueOnce(jsonResponse(200))
124+
global.fetch = fetchMock
125+
126+
const startedAt = Date.now()
127+
const response = await throttledBlockscoutFetch('https://blockscout.test/api')
128+
129+
expect(response.status).toBe(200)
130+
expect(Date.now() - startedAt).toBeLessThan(1_000)
131+
})
132+
})

0 commit comments

Comments
 (0)