Back to Tutorials
LLM Application Development
Intermediate

Rate Limits and Retries: Back Off and Spread Out

Watch a token bucket refuse bursts under a per-minute limit, then race five retry strategies against the same API and see which one wastes thousands of calls.

9 minInteractive: drag, click and try things as you read


Every AI API limits how fast you can call it. Go over the limit and it answers 429 Too Many Requests instead of doing the work. Sooner or later every app that calls a model meets that answer, so production code has to retry. But how you retry decides whether your requests trickle through, pile up, or keep hammering a service that’s already struggling. Wait longer after each failure, add some randomness, stop after a few tries, and better still, don’t send what will be refused. Here you’ll watch a rate limit at work, then race five retry strategies against the same limit.

What a rate limit really is#

Providers limit how many requests you can make, and usually how many tokens you can send and receive, per minute. Anthropic’s API, for example, counts requests per minute, input tokens per minute and output tokens per minute for each model, and returns a 429 when you exceed any of them.

“Per minute” doesn’t mean a counter that resets on the minute. Many providers, Anthropic included, use a token bucket (nothing to do with the tokens a model reads). Picture a bucket that fills with permits at a steady rate, one a second for a limit of 60 a minute. Each request takes a permit out. If the bucket is empty, the request is refused. The bucket’s size decides how big a burst it can absorb, and Anthropic’s documentation warns that a limit of 60 a minute might be enforced as one request per second.

Predict first

Your limit is 60 requests a minute, enforced as one per second. You send three bursts of 15 requests, 20 seconds apart: 45 in the minute. How many get through?

Try it
A limit of 60 requests a minute as a token bucket that refills at one permit a second. The sending patterns are made up; the bucket arithmetic is exactly what runs here. Providers don’t publish their bucket sizes, so try all three.

Steady traffic, one request every 1.2 seconds, sails through whatever the bucket holds: it never asks for a permit faster than they arrive. Bursts are a different story. Three bursts of 15 all get through a bucket holding 60, 30 get through one holding 10, and 3 get through one holding 1. Sending 60 at once fares worse still: just 11 get through a bucket of 10, and 2 a bucket of 1. A per-minute limit is really a limit on how fast you go at any moment. Spreading requests out avoids most 429s before they happen.

Retrying without making it worse#

Some errors are worth retrying because the same request may well succeed a moment later: 429 (rate limited), 408 (timeout), 500-range server errors, and Anthropic’s 529 (overloaded). Others never will: a 400 means the request itself is wrong, a 401 means the key is wrong, and sending them again just fails again. Even a 429 can be permanent: Anthropic returns one without a retry-after header when an account reaches its monthly spend cap, and retrying won’t help until access resumes. So every retry loop needs a limit.

The interesting question is how long to wait. Try it on a common situation: a batch job fires 100 requests at once at an API that allows 10 a second.

Predict first

Each refused request immediately tries again, as fast as the network allows (every 0.1 seconds). How many calls does it take to get all 100 requests through?

Try it
Simulated: 100 requests sent within 50 milliseconds to an API that allows 10 a second (a token bucket holding 10). Backoff uses the numbers from Anthropic’s Python SDK: wait 0.5 seconds, then 1, 2, 4, and never more than 8. With jitter, “Run again” draws new random waits.

Retrying at once gets everything through in 9.0 seconds, as fast as the limit allows, but it takes 4,195 calls, about 41 refusals for every success. Waiting a fixed second cuts that to 550 calls with the same finish, but look at the chart: everyone refused together comes back together, in a wave every second.

Exponential backoff, doubling the wait after each failure, is the standard advice, yet on its own it’s the slowest of all here: 55.5 seconds, with 595 calls. Requests that fail together still wait exactly as long as each other, so they keep arriving in waves, now with longer and longer gaps in which the API sits idle. Add jitter, a random wait anywhere between zero and the backoff time, and the waves dissolve: about 460 calls and done in 11 to 15 seconds. In a 2015 AWS article comparing kinds of jitter, Marc Brooker called backoff without jitter “the clear loser”, and this “full jitter” was among the best.

The real winner doesn’t retry at all. Pacing, a small limiter in your own code that holds each request until the limit has room, makes exactly 100 calls, none refused, and finishes as fast as anything else. Jitter breaks up the crowd; pacing never forms one.

Retries in production#

  • Use what your SDK already does. Anthropic’s official SDKs retry connection errors, 408, 409, 429 and 5xx responses twice by default, with exponential backoff and a little jitter, honouring retry-after. Set max_retries to change how many times. Don’t wrap a second retry loop around it without thinking: retries at several layers multiply. Three layers that each try four times can turn one failure into 64 calls.
  • Cap attempts and total time. A request that has failed four or five times needs a different plan, not a sixth try. Retrying forever is how a brief outage turns into a retry storm: every client retrying at once can keep a struggling service down after the original problem is fixed.
  • Make retries safe. Retrying an LLM call costs tokens but does no harm. Retrying a call that charges a card or sends an email can do it twice, so give those calls an idempotency key, if the service supports one, so it can recognise a repeat.
  • Slow down before you’re told to. Responses carry headers showing how much of each limit is left; Anthropic’s include anthropic-ratelimit-requests-remaining. Cap how many calls you have in flight, and ramp up big jobs gradually.
  • Have a fallback. When retries run out: queue the work for later (Anthropic’s Message Batches API processes requests asynchronously at half the price), switch to another model, or tell the user plainly that it’s busy and try again later.

In code#

The SDK handles retries for Claude calls (anthropic.Anthropic(max_retries=4) raises the default of 2). For any other API, a retry loop with backoff, full jitter, a retry limit and retry-after looks like this. It runs as is, against a pretend API that refuses twice:

import random
import time

RETRYABLE = {408, 409, 429, 500, 502, 503, 504, 529}   # worth another try; 400, 401, 403, 404 are not

class APIError(Exception):
    def __init__(self, status, retry_after=None):
        self.status, self.retry_after = status, retry_after

def call_with_retries(fn, max_retries=4, base=0.5, cap=8.0):
    for attempt in range(max_retries + 1):
        try:
            return fn()
        except APIError as e:
            if e.status not in RETRYABLE or attempt == max_retries:
                raise                                              # not retryable, or out of tries
            wait = random.uniform(0, min(cap, base * 2 ** attempt))  # backoff with full jitter
            if e.retry_after:
                wait = max(wait, e.retry_after)                    # never sooner than the API asked
            print(f"try {attempt + 1}: {e.status}, waiting {wait:.2f} s")
            time.sleep(wait)

# a pretend API that refuses twice, then answers
replies = iter([APIError(429, retry_after=1), APIError(529), "hello"])
def flaky():
    r = next(replies)
    if isinstance(r, Exception):
        raise r
    return r

random.seed(4)
print(call_with_retries(flaky))
# try 1: 429, waiting 1.00 s
# try 2: 529, waiting 0.10 s
# hello

What to remember

  • A per-minute limit is usually a token bucket: bursts get refused even when the minute’s total is under the limit.
  • Retry only errors that can succeed later, with exponential backoff plus jitter, honouring retry-after, and stop after a few tries.
  • Better than retrying well is not needing to: pace requests to the limit, cap concurrency, and have a fallback when retries run out.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.