Handling AI Rate Limits

Recover from AI rate limits by respecting Retry-After and retrying with exponential backoff and jitter.

TL;DR

  1. Detect a 429 status and read the Retry-After header.
  2. Retry with exponential backoff plus random jitter.
  3. Cap retries and limit concurrency to avoid a storm.

Detect the Limit

    Check the Status

    A 429 means you are being rate limited.

    if (res.status === 429) await backoff();
    Read Retry-After

    The header says how long to wait.

    const ra = res.headers.get('Retry-After');
    Parse Seconds

    Convert the header to milliseconds.

    const ms = Number(ra) * 1000;

Back Off and Retry

    Exponential Delay

    Double the wait after each attempt.

    const delay = base * 2 ** attempt;
    Add Jitter

    Randomize so clients do not sync up.

    const wait = delay + Math.random() * 250;
    Cap Attempts

    Give up after a few tries.

    if (attempt >= 5)
      throw new Error('rate limited');

Limit Concurrency

    Max In Flight

    Only allow a few requests at once.

    if (active >= 3) await queue.next();
    Queue Extras

    Hold the rest until a slot frees.

    queue.push(task);
    Per-User Cap

    Enforce a limit on the server too.

    // server: N requests per user / minute

Tell the User

    Show a Wait

    Let them know a retry is coming.

    setStatus('Busy, retrying...');
    Disable Send

    Block new requests while retrying.

    <button disabled={retrying}>Send</button>
    Final Error

    Surface a clear message if it gives up.

    setError('Too many requests, try later');

Tips

  1. Honor the Retry-After header when present; it tells you exactly how long to wait, which beats guessing with backoff alone.
  2. Add random jitter to each backoff delay so many clients do not retry in sync and hammer the API at the same instant.

Warnings

  1. Do not retry forever; cap attempts and surface a clear error, or a rate-limited user waits behind endless silent retries.
  2. Retrying a non-idempotent action can double an effect; only auto-retry safe reads, not writes with side effects.

In Practice

FAQ