Dev tools
API Rate Limiting: How to Handle 429 Errors
API rate limiting explained: why you get 429 Too Many Requests, how to retry with backoff, rate limit algorithms, AI API limits and designing your own.
API rate limiting is how an API controls how many requests a client can make in a given time, such as 100 requests per minute. When you go over the limit, the server responds with HTTP 429 Too Many Requests, often with a Retry-After header telling you how long to wait. The right way to handle it is to slow down: wait for the time in Retry-After if it's there, otherwise retry with exponential backoff and random jitter, cap the number of retries, and reduce how many requests you send in the first place.
This guide explains why APIs rate limit, how to handle 429 errors correctly with example code, the common rate limiting algorithms, how AI APIs like Claude and OpenAI limit usage, rate limiting vs throttling, and how to design rate limits for your own API.
What Is API Rate Limiting?
API rate limiting caps the number of requests (and sometimes the amount of data or compute) a client can use in a period of time. Limits are usually tied to an API key, user, account or IP address, and can apply per second, per minute, per day or per month.
APIs rate limit to:
- Protect the service from overload, whether accidental (a bug in a loop) or deliberate (abuse, scraping, denial of service).
- Share capacity fairly between customers.
- Control costs, especially for expensive operations like AI model calls.
- Enforce pricing tiers, where higher plans get higher limits.
What 429 Too Many Requests Means
HTTP status code 429 means "Too Many Requests": the client has sent too many requests in a given amount of time. It's defined in RFC 6585. A well-behaved API returns it with:
- a `Retry-After` header, giving the number of seconds to wait (or a date and time),
- a response body explaining which limit was hit,
- often rate limit headers showing your limit, how many requests remain and when the window resets.
A 429 is a signal to slow down, not a failure to work around. Retrying immediately and aggressively usually makes things worse, because every retry counts against the limit too.
Rate limit exceeded vs other errors
- 429: you're sending too many requests; wait and slow down.
- 503 Service Unavailable: the server is overloaded or down; often also comes with
Retry-After. - 403 Forbidden: you're not allowed at all; retrying won't help.
- Quota or spend cap reached: some APIs return 429 when a monthly budget or quota is used up. Retrying won't help until the quota resets or you raise it.
How to Handle 429 Errors
- Respect `Retry-After`. If the header is present, wait at least that long before retrying.
- Otherwise, use exponential backoff. Wait 1 second, then 2, then 4, then 8, and so on, up to a maximum.
- Add jitter. Randomize each wait a little so many clients don't retry at exactly the same moment and cause another spike.
- Cap retries. After a set number of attempts, fail clearly and log the problem instead of retrying forever.
- Retry only safe requests. Retrying a request that creates a payment or sends an email can duplicate it unless the API supports idempotency keys.
- Slow down the whole client, not just one request: if one call hit the limit, others in flight will too.
Example: retry with backoff in Python
This example uses the requests library. It honours Retry-After when present and otherwise backs off exponentially with jitter:
import random
import time
import requests
def get_with_retries(url, max_retries=5, base_delay=1.0, max_delay=60.0):
for attempt in range(max_retries + 1):
response = requests.get(url, timeout=30)
if response.status_code != 429:
response.raise_for_status()
return response
if attempt == max_retries:
response.raise_for_status()
retry_after = response.headers.get("Retry-After")
if retry_after and retry_after.isdigit():
delay = float(retry_after)
else:
delay = min(max_delay, base_delay * (2 ** attempt))
delay = random.uniform(0, delay) # "full jitter"
time.sleep(delay)Many official SDKs already do this. OpenAI's Python SDK, for example, automatically retries certain errors, including 429s, twice by default with a short exponential backoff, and lets you change the number of retries. Check your SDK's documentation before adding your own retry layer, so you don't end up retrying twice as much as you intended.
How to Avoid Hitting Rate Limits
Retries handle the symptom; these reduce the cause:
- Cache responses that don't change often, instead of fetching them repeatedly.
- Batch requests where the API supports it, such as fetching 100 records in one call instead of 100 calls.
- Use webhooks instead of polling. Let the API notify you of changes rather than asking every few seconds. Our guide to webhook vs API explains the difference.
- Throttle on your side. A client-side limiter that stays just under the API's limit prevents most 429s.
- Limit concurrency. Many limits are hit by too many requests in parallel, not by the total. A queue with a fixed number of workers helps.
- Spread work over time. Schedule large jobs to run gradually, not in one burst.
- Read the rate limit headers and slow down before you reach zero remaining.
- Watch for bugs. A surprising number of 429s come from code that calls an API in a loop or on every page render.
API Rate Limiting Algorithms
| Algorithm | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Fixed window | Count requests per fixed period, such as per minute | Simple | Allows bursts at window edges (end of one minute plus start of the next) |
| Sliding window log | Track timestamps of each request in the last N seconds | Accurate | Uses more memory |
| Sliding window counter | Blend counts of the current and previous window | Good accuracy, low memory | Approximate |
| Token bucket | Tokens refill at a steady rate; each request spends one; bursts allowed up to bucket size | Allows short bursts, smooth over time | Slightly more complex |
| Leaky bucket | Requests queue and leave at a constant rate | Very smooth output | Adds delay; queue can fill |
The token bucket is the most common for public APIs because it allows short bursts while enforcing an average rate. Anthropic, for example, says its API uses the token bucket algorithm, so capacity is continuously replenished up to your maximum rather than reset at fixed intervals.
Rate Limits on AI APIs
AI model APIs usually limit more than requests:
- Requests per minute (RPM).
- Input tokens per minute and output tokens per minute, because long prompts and answers cost far more than short ones.
- Spend limits per month, tied to your account tier.
Anthropic's API, for example, measures limits in requests per minute, input tokens per minute and output tokens per minute for each model class. When you exceed one, it returns a 429 explaining which limit was hit, and when the response includes retry-after, you should wait that many seconds. Anthropic also describes "ramp limits": a sudden sharp increase in usage can trigger 429s even under your normal limits, so ramp traffic up gradually. And if your account reaches its monthly spend cap, requests return 429 without a retry-after header, and retrying won't help until access resumes.
Practical tips for AI APIs:
- Count tokens, not just requests, when planning throughput.
- Use batch APIs for large offline jobs; they often have separate, higher limits and lower prices.
- Use prompt caching for repeated long prompts where supported.
- Route through a gateway that can spread load across providers and keys and apply your own limits. Our guide to the LLM gateway covers how that works.
- Pick smaller models for simple tasks, which saves both rate limit and money. Our guide on how to reduce LLM costs lists more ways.
Rate Limiting vs Throttling
Rate limiting vs throttling are often used to mean the same thing, but there's a useful distinction:
- Rate limiting rejects requests over the limit, typically with a 429.
- Throttling slows requests down, for example by queueing them or delaying responses, instead of rejecting them.
Some providers use "throttling" for both. What matters for your client is the behaviour: if you get 429s, back off; if responses simply get slower, check whether the API is queueing you.
How to Design Rate Limits for Your Own API
If you run an API, good rate limiting protects you and helps your users:
- Choose the key: per API key or user for authenticated APIs; per IP address for anonymous traffic.
- Choose the algorithm: token bucket is a sensible default.
- Set limits from real usage: look at normal traffic, then set limits comfortably above it for each plan.
- Return clear 429 responses with
Retry-Afterand a message saying which limit was hit. - Expose rate limit headers so clients can slow down before hitting the limit. An IETF draft standardizes
RateLimitheaders; many APIs use their ownX-RateLimit-*names. - Store counters in a fast shared store such as Redis, so all your servers enforce the same limits.
- Apply limits at the edge too, with an API gateway, reverse proxy or CDN, to block abuse before it reaches your application.
- Separate expensive endpoints with stricter limits.
- Document your limits and how to request higher ones.
Common Mistakes
- Retrying immediately in a tight loop, which multiplies the problem.
- Ignoring `Retry-After`.
- No retry limit, so a stuck job runs forever.
- Retrying non-idempotent requests, creating duplicate orders or messages.
- Treating a quota or spend cap like a temporary limit.
- Two retry layers stacked, such as an SDK and your own wrapper, multiplying attempts.
- No monitoring, so you don't notice you're constantly near the limit.
Rate Limiting in Gateways and Frameworks
You rarely need to write a rate limiter from scratch. Common options:
- API gateways such as those offered by cloud providers and open-source gateways can enforce per-key or per-IP limits before traffic reaches your code.
- Reverse proxies: nginx's
limit_req_zoneandlimit_reqdirectives implement request rate limiting with burst control. - Application libraries: for example express-rate-limit for Node.js Express apps, Bucket4j for Java and Spring Boot applications, and django-ratelimit for Django.
- CDNs and web application firewalls can rate limit abusive traffic at the edge, before it costs you compute.
For a single server, an in-memory limiter is fine. Once you run several instances, store counters in a shared store such as Redis, or rely on the gateway, so that limits apply across all instances rather than per server.
Testing Your Retry Logic
Retry code is rarely exercised until production traffic spikes. A few ways to test it safely:
- Use a mock server that returns 429 with and without
Retry-Afterfor a set number of calls, and check that your client waits and eventually succeeds or gives up. - Check total retry time, not just the count, so a user-facing request doesn't hang for minutes.
- Log every 429 with the endpoint and the limit that was hit, so you can see which limits you approach most often.
- Load test gradually against a sandbox or staging environment, never against a provider's production API without permission.
Rate Limits in a Worked Example
Imagine a sync job that copies 50,000 records from a CRM whose API allows 100 requests per minute and returns 100 records per request:
- Naive approach: request records one at a time as fast as possible. That's 50,000 requests; the job hits the limit within the first minute and spends most of its time in retries.
- Batched approach: request 100 records per call. That's 500 requests, which at 100 per minute takes about five minutes, with no 429s if a client-side limiter keeps the pace just under the limit.
- Incremental approach: after the first full sync, request only records changed since the last run, or subscribe to the API's change webhooks. A daily sync might then need a handful of requests.
The same principle applies to almost every integration: the biggest wins come from asking for less, not from retrying more cleverly.
FAQ
What does 429 Too Many Requests mean?
It means you've sent too many requests to an API in a given time and hit its rate limit. Wait before retrying, ideally for the time given in the Retry-After header, and reduce how often you send requests.
How do I fix a "rate limit exceeded" error?
Wait for the time given in Retry-After if provided, otherwise retry with exponential backoff and jitter, cap your retries, and reduce request volume with caching, batching, webhooks or client-side throttling. If you regularly need more, ask the provider for a higher limit or upgrade your plan.
What is exponential backoff?
It's a retry strategy where the wait time doubles after each failed attempt, such as 1, 2, 4 and 8 seconds, usually with random jitter added so that many clients don't retry at the same moment.
What is the difference between rate limiting and throttling?
Rate limiting rejects requests above a limit, usually with HTTP 429. Throttling slows requests down, for example by queueing them. Many providers use the terms interchangeably.
Why do AI APIs have token limits as well as request limits?
Because the cost of an AI request depends on how much text it processes. A single request with a long prompt can use as much capacity as many short ones, so providers limit input and output tokens per minute as well as requests.