Back to Blog
Backend•5 min read

Fix API 429 Errors With Safe Retry and Backoff

APIsRate LimitsReliability

In this guide

Handle API 429 Too Many Requests with Retry-After, bounded backoff, jitter, and shared request limits. Includes a read-only JavaScript example.

An API 429 Too Many Requests response means the service is limiting request volume for a defined scope. Reduce concurrency, honor a valid Retry-After value, and use bounded backoff with jitter. Retry only operations whose replay is safe, and stop when the retry or elapsed-time budget is exhausted.

Why do retries sometimes make an API outage worse?

Imagine a CRM synchronization where ten workers share one provider credential. Each worker immediately retries a rejected request. The retry traffic adds to the original burst and keeps the integration throttled. Slowing one screen does not solve the limit when other workers continue using the same account quota.

Record the provider, endpoint group, response status, documented limit scope, and request volume. Check whether the quota applies to an account, API key, IP address, or another identifier. Avoid assuming that a new worker has its own allowance. Also check scheduled jobs that all start at the same minute.

Step 1: inspect the response before choosing a delay

Read the provider's current limit documentation and response headers. Retry-After can represent a number of seconds or an HTTP date. If it is present and valid, it is a minimum waiting instruction for the retry policy. A delay beyond your interactive time budget should become scheduled work or a clear pending state.

Differentiate rate limiting from authentication, permission, and validation errors. Retrying a 401 with the same expired credential does not replenish a request allowance. Retrying invalid input wastes capacity. Keep the error classification visible in logs and user messages so operations can identify which remedy is relevant.

Step 2: use a bounded retry for read-only calls

This JavaScript example retries only a GET after 429, limits each fetch, and refuses a server delay longer than its short interactive budget. It intentionally does not retry arbitrary HTTP failures or network exceptions. A background importer should schedule a later attempt rather than holding a process open indefinitely.

js
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

function retryDelay(value) {
  if (!value) return null;
  if (/^\d+$/.test(value.trim())) return Number(value) * 1000;
  const timestamp = Date.parse(value);
  return Number.isFinite(timestamp) ? Math.max(0, timestamp - Date.now()) : null;
}

async function getWithBackoff(url) {
  for (let attempt = 0; attempt < 3; attempt++) {
    const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
    if (response.status !== 429) {
      if (!response.ok) throw new Error("HTTP " + response.status);
      return response.json();
    }
    const serverDelay = retryDelay(response.headers.get("Retry-After"));
    await response.body?.cancel();
    if (attempt === 2) break;
    if (serverDelay !== null && serverDelay > 10000) {
      throw new Error("Rate limited: schedule a later attempt");
    }
    const backoff = Math.min(1000 * 2 ** attempt, 8000);
    await sleep(Math.max(serverDelay ?? 0, backoff) + Math.random() * 250);
  }
  throw new Error("Rate limit retry budget exhausted");
}

Choose the allowed attempt count and timeout from the job's requirements. This example has a deliberately small budget and assumes an environment supporting AbortSignal.timeout. A production worker should also respond to shutdown or caller cancellation so abandoned tasks do not keep consuming request capacity.

Step 3: control concurrency across the actual limit scope

Backoff helps one caller. A shared queue or limiter may be needed when several workers share a provider account. Set concurrency deliberately, spread scheduled work, and avoid duplicate fetches for the same resource. Cache appropriate public or account-scoped reads with clear expiry and access boundaries.

A limiter stored only in one process does not coordinate a fleet of processes. Choose shared coordination when the provider's limit requires it, and define what happens when that coordinator is unavailable. Observe queue age as well as error counts: a perfectly throttled integration can still miss business deadlines if work arrives faster than it can be processed.

Step 4: protect writes from accidental replay

Do not reuse the GET example for creating invoices, taking payments, or sending messages. For writes, understand the provider's idempotency contract and persist a stable operation key across retries. A timeout can occur after a remote service has accepted a write, leaving the local caller uncertain about its outcome.

Reconcile uncertain operations through a provider lookup or documented recovery flow. Rotating a new idempotency key on every attempt defeats its purpose. Keep event receipt, business action, and downstream request identity connected so an operator can determine whether retry means 'try again' or 'create a second thing'.

Step 5: verify the failure policy with controlled responses

  1. Return 429 followed by success. Assert that the caller waits and completes within its attempt budget.
  2. Test numeric and date Retry-After headers, a missing header, and an invalid header.
  3. Return a very long Retry-After. Confirm that interactive work stops and background work is scheduled appropriately.
  4. Run multiple workers against a fake provider to verify shared concurrency behavior without consuming a real quota.
  5. For writes, simulate a lost response after acceptance and confirm one business action through the provider's supported idempotency flow.

Should the user keep pressing the retry button?

A clear pending or rate-limited state is better than encouraging repeated clicks while the same quota is exhausted. Keep one operation identity, explain when another attempt is available, and prevent the interface from launching concurrent copies of the same action. A manual retry still needs the same server-side replay protection as an automatic one.

For a long-running import, show accepted work and progress separately from completed work. The request may be safely queued while provider capacity is temporarily unavailable. That distinction lets users understand the delay without interpreting a successful queue receipt as proof that every record has already synchronized.

Track requests, throttled responses, retries, successful completions, and oldest queued work. For server-side limit design, read API rate limiting. For integrations that need recovery and operational visibility, explore backend engineering and share the provider limit and workload for a scoped review.

Official references and further reading

MDN: HTTP 429 Too Many Requests

HTTP Semantics: Retry-After

AWS Builders Library: timeouts, retries, and jitter

Share this article:

Keep Reading

Ready to implement these ideas?

Discuss Your Project