Node.js theorytheory 0/50 · 0%
Web3 integration · medium

32. Rate limiting and retries

Being a good citizen against RPC providers and external APIs.

Public and even paid RPC providers rate-limit requests. A robust client backs off and retries transient failures (timeouts, 429s, 5xx) with increasing delay, instead of hammering the endpoint or failing on the first blip.

js
async function withRetry(fn, { attempts = 5, baseDelay = 200 } = {}) {
  for (let i = 0; i < attempts; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === attempts - 1) throw err;
      const delay = baseDelay * 2 ** i; // exponential backoff
      await new Promise((r) => setTimeout(r, delay));
    }
  }
}

const block = await withRetry(() => rpcCall(url, "eth_blockNumber"));

Exponential backoff (doubling the delay each retry) spreads out retries so a temporary outage doesn't turn into a thundering herd of simultaneous retries the instant service resumes.

Check your understanding

  1. 1. What is exponential backoff?

  2. 2. What HTTP status commonly indicates rate limiting?

  3. 3. Why is retrying without backoff risky during an outage?