API Rate Limiting: How to Choose Limits & Handle 429s
In this article
API rate limiting controls how many requests a client can make within a given time window, and handling 429 Too Many Requests responses reliably requires a combination of sensible limit selection, client-side retry logic, and server-side design that respects the limits. This article explains how rate limiting works, how to choose appropriate limits for your API, and how to build clients that handle 429s gracefully.
What Is API Rate Limiting?
API rate limiting is a technique used to control the amount of incoming traffic to an API. It sets a maximum number of requests a client can make in a specific time period, such as 100 requests per minute. The goal is to protect the server from overload, ensure fair usage among all clients, and maintain service quality. Rate limiting is often implemented at the API gateway or application level, and it can apply to individual API keys, IP addresses, or user accounts.
When a client exceeds the limit, the server returns an HTTP status code 429 Too Many Requests, along with headers that indicate when the limit resets and how long the client should wait before retrying. The Retry-After header is particularly important, as it tells the client the number of seconds to wait before making another request.
How Rate Limiting Works
Rate limiting algorithms determine when a request is allowed or rejected. The most common algorithms are:
- Token Bucket: A bucket holds a fixed number of tokens. Each request consumes a token. Tokens are added at a steady rate (e.g., one per second). If the bucket is empty, the request is denied. This allows short bursts of traffic up to the bucket size.
- Leaky Bucket: Requests are processed at a constant rate. Incoming requests are queued. If the queue is full, new requests are rejected. This smooths out bursts but can introduce latency.
- Fixed Window: The time is divided into fixed windows (e.g., 1 minute). Each window has a maximum request count. Once the count is reached, requests are denied until the next window. This is simple but can allow double bursts at window boundaries.
- Sliding Window Log: Each request’s timestamp is stored. The count is calculated by looking at requests within the last N seconds. This is more accurate but uses more memory.
- Sliding Window Counter: A hybrid of fixed window and sliding log, using counters for the current and previous windows to approximate a sliding window.
Most APIs use a combination of these, often with a token bucket for bursts and a fixed window for long-term limits. The chosen algorithm affects how “fair” the limit feels to clients.
How to Choose the Right Rate Limits
Choosing rate limits is a balance between protecting your infrastructure and providing a good developer experience. There is no one-size-fits-all number; it depends on your API’s capacity, typical request cost, and user base. Here are the key factors:
- Server capacity: Measure how many requests your API can handle per second before latency spikes or errors increase. Use load testing to find the breaking point, then set limits at a fraction of that (e.g., 50-70%).
- Cost per request: Some endpoints are more expensive (e.g., complex database queries, external calls). You may want lower limits for those endpoints.
- User expectations: If your API is for internal use, limits can be higher. For public APIs, consider what a typical integration needs. For example, a weather API might allow 1,000 calls/day for free users, while a real-time chat API might allow 60 calls/minute.
- Burst vs. sustained: Allow short bursts (e.g., 10 requests per second) while enforcing a lower sustained rate (e.g., 1,000 requests per hour).
- Abuse prevention: If your API is prone to scraping or brute-force attacks, lower limits for unauthenticated requests.
A common approach is to start with generous limits and tighten them based on observed usage. Monitor your API’s performance and adjust limits as needed. You can also offer different tiers: free, pro, enterprise, each with higher limits.
Handling 429 Responses Reliably
When your client receives a 429, it means you’ve hit the limit. To handle this gracefully, follow these best practices:
- Read the
Retry-Afterheader: The server tells you how long to wait (in seconds) before retrying. If the header is absent, use a default backoff strategy. - Implement exponential backoff: Start with a small delay (e.g., 1 second), then double it after each consecutive 429 (e.g., 1s, 2s, 4s, 8s) up to a maximum (e.g., 60s). Add random jitter to avoid thundering herd problems.
- Queue requests: If you’re making many requests in parallel, queue them and process at a rate that respects the limit. For example, if your limit is 10 requests per second, use a rate limiter on the client side.
- Retry only idempotent requests: If a request changes state (e.g., POST that creates an order), retrying may cause duplicates. Use idempotency keys or avoid retrying non-safe methods.
- Log and monitor: Track 429 responses to understand when you’re hitting limits. This helps you adjust your client’s behavior or request higher limits if needed.
- Fallback for critical operations: If an API call is essential, have a fallback (e.g., cached data) so your application doesn’t fail completely.
- Rate limiting: Controls the rate of requests per time unit (e.g., 100 requests per minute). It prevents bursts.
- Throttling: A broader term that can include rate limiting, but also includes controlling bandwidth or CPU usage. In API context, it’s often synonymous with rate limiting.
- Quota: A limit on the total number of requests over a longer period, such as 10,000 requests per day. Quotas are often used for billing tiers.
- Caching: Reduce the number of requests by caching responses on the client or server side. This is especially effective for GET requests with static data.
- Batching: Allow clients to send multiple operations in a single request (e.g., GraphQL, or a custom batch endpoint). This reduces the number of requests.
- API keys and authentication: Requiring authentication helps identify abusive clients and apply different limits.
- Load shedding: If the server is overwhelmed, drop non-critical requests (return 503) instead of processing all.
- Webhooks: Instead of polling, let the server push data to clients, reducing the need for frequent requests.
Here’s a simple Python example using the requests library with exponential backoff:
import time
import requests
def call_api(url):
max_retries = 5
for attempt in range(max_retries):
response = requests.get(url)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', 2 ** attempt))
time.sleep(retry_after)
continue
return response
return response # give up after max retries
This code reads the Retry-After header, falls back to exponential backoff if missing, and retries up to 5 times.
Common Problems and Misconceptions
One common misconception is that a 429 always means you’ve exceeded your limit. It can also be returned for other reasons, such as a shared IP being rate-limited by another user, or the server being under maintenance. Always check the response body for details.
Another issue is that many developers ignore the Retry-After header and just retry immediately, causing a “retry storm” that worsens the problem. Always respect the server’s instructions.
Another problem is that rate limits are often not transparent. If your API doesn’t include headers like X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset, clients can’t proactively avoid hitting the limit. Always include these headers in your API responses.
Finally, be careful with time synchronization. If your client and server clocks are out of sync, the X-RateLimit-Reset timestamp may be off, causing you to wait longer than necessary or retry too early.
Rate Limiting vs. Throttling vs. Quotas
These terms are often used interchangeably but have distinct meanings:
For example, an API might have a rate limit of 10 requests per second, but also a daily quota of 50,000 requests. The rate limit prevents short-term overload, while the quota prevents long-term overuse.
Costs and Trade-offs of Rate Limiting
Rate limiting has costs for both API providers and consumers. For providers, implementing rate limiting requires additional infrastructure (e.g., Redis for distributed counters) and adds complexity. If limits are too strict, you risk frustrating developers and driving them to competitors. If too loose, you risk server overload and increased costs.
For consumers, rate limits can slow down development and require more complex client code. You may need to purchase higher tiers or implement caching to reduce API calls. However, rate limits also protect you from accidentally overwhelming the API and getting banned.
Alternatives and Complements
Rate limiting isn’t the only way to protect an API. Consider these alternatives:
These can be used in combination with rate limiting to provide a robust API.
Frequently Asked Questions
What does the 429 status code mean?
HTTP 429 Too Many Requests indicates that the client has sent too many requests in a given time period. The server includes a Retry-After header suggesting how long to wait before retrying.
How do I find out my rate limit?
Many APIs include response headers like X-RateLimit-Limit (the maximum), X-RateLimit-Remaining (how many left), and X-RateLimit-Reset (when the limit resets). Check your API’s documentation for specifics.
Should I retry a 429 response?
Yes, but only after respecting the Retry-After header or using exponential backoff. Avoid immediate retries, as they can worsen the situation. Also, only retry idempotent requests (GET, PUT, DELETE) to avoid side effects.
What is exponential backoff?
Exponential backoff is a retry strategy where the delay between attempts increases exponentially (e.g., 1s, 2s, 4s, 8s). Adding random jitter prevents many clients from retrying at the same time, which is known as the thundering herd problem.
Can I bypass rate limits?
Bypassing rate limits is generally against an API’s terms of service and can lead to your API key being revoked. Instead, request higher limits from the provider or use caching to reduce your request count.
What is the difference between rate limiting and throttling?
Rate limiting specifically limits the number of requests per time unit. Throttling is a broader term that can include rate limiting, but also encompasses controlling bandwidth or CPU usage. In practice, they are often used interchangeably.