Handle RPC rate limit headers and Retry-After in Node.js
Build a Node.js JSON-RPC client that inspects rate limit headers, waits after HTTP 429 responses, and stops after a bounded number of retries.
To handle RPC rate limits, inspect each HTTP response, retry HTTP 429 responses after the server's Retry-After delay when present, and cap retries. The example below sends a read-only JSON-RPC request and logs rate limit headers without assuming a provider uses a particular header format.
Prepare a read-only RPC request
Use Node.js 18 or later and an HTTP RPC endpoint you are authorized to access. Set RPC_URL to that endpoint before running the script; do not commit URLs containing API keys.
The example calls eth_blockNumber, so use an Ethereum-compatible JSON-RPC endpoint. This is an RPC access task: it sends a request to a node endpoint, not an indexing or historical querying task.
- Check your provider's documentation for its rate limit policy and headers; header names and reset formats can differ.
- Keep retries bounded. Repeating requests indefinitely can prolong overload and hide an invalid configuration.
Inspect headers and retry HTTP 429 responses
Save this script as rpc-retry.mjs, set RPC_URL in your environment, and run node rpc-retry.mjs. It accepts Retry-After as either seconds or an HTTP date; without a usable value it uses exponential backoff. A 60-second maximum wait keeps the example bounded: if the server asks for longer, the script stops rather than retrying early.
const url = process.env.RPC_URL;
if (!url) {
console.error('Set RPC_URL to an authorized Ethereum-compatible HTTP endpoint.');
process.exit(1);
}
const maxAttempts = 4;
const maxWaitMs = 60_000;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function retryAfterMs(value) {
if (!value) return null;
const trimmed = value.trim();
if (/^\d+$/.test(trimmed)) return Number(trimmed) * 1000;
const date = Date.parse(trimmed);
return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
}
async function main() {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
let response;
try {
response = await fetch(url, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_blockNumber', params: [] }),
signal: AbortSignal.timeout(10_000)
});
} catch (error) {
throw new Error(`Request failed or timed out: ${error.message}`);
}
console.error(`HTTP ${response.status}, attempt ${attempt}/${maxAttempts}`);
for (const [name, value] of response.headers) {
if (name === 'retry-after' || name.includes('ratelimit') || name.includes('rate-limit')) {
console.error(`${name}: ${value}`);
}
}
if (response.status === 429) {
await response.body?.cancel();
if (attempt === maxAttempts) throw new Error('Rate limit persisted; retry budget exhausted.');
const delay = retryAfterMs(response.headers.get('retry-after')) ?? (1000 * 2 ** (attempt - 1));
if (delay > maxWaitMs) throw new Error('Retry-After exceeds the maximum allowed wait.');
console.error(`Waiting ${delay} ms before retrying.`);
await sleep(delay);
continue;
}
if (!response.ok) {
await response.body?.cancel();
throw new Error(`RPC HTTP request failed with status ${response.status}.`);
}
let payload;
try {
payload = await response.json();
} catch {
throw new Error('RPC response was not valid JSON.');
}
if (payload.error) throw new Error(`JSON-RPC error: ${JSON.stringify(payload.error)}`);
if (payload.id !== 1 || typeof payload.result !== 'string') {
throw new Error('Unexpected JSON-RPC response.');
}
console.log(`Block number (hex): ${payload.result}`);
return;
}
}
main().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});On success, expect HTTP status information on stderr and a hexadecimal block number on stdout. Rate limit headers appear only if the endpoint returns headers matching the script's filters.
On HTTP 429, the script logs the attempt and waits before retrying. Network errors, timeouts, other HTTP failures, malformed JSON, JSON-RPC errors, and an exhausted retry budget produce an error and a nonzero exit code.
Adapt the policy to your application
Read the provider's documentation before interpreting remaining-quota or reset headers. The script logs them for inspection but does not assume their units or use them to schedule requests.
For concurrent workers, coordinate request rates across processes and consider jitter in fallback delays to avoid synchronized retries. Apply automatic retries carefully to state-changing RPC methods: a timeout does not prove the server failed to process a request.
If you need to understand your own usage, record response status, header values, attempt counts, and elapsed time without logging credentials. Measure against your actual endpoint and workload rather than assuming a universal limit.
Choose RPC access or indexed queries
RPC is suitable for direct node requests such as the current block number. If your application needs to filter and query application-specific historical data, consider an indexing and querying workflow separately; retrying RPC requests does not create an indexed dataset.
Next, explore OnFinality Learn for more RPC guidance, or use RPC Assistant as another starting point for RPC questions.