Every public API needs a mechanism to prevent abuse, mitigate denial-of-service attempts, stop aggressive web scrapers, and insulate downstream databases from sudden spikes in load.
Rate limiting restricts how many requests a client can make within a specified timeframe. While the concept sounds simple, choosing the wrong algorithm can lead to spiky database load, unfair rejections, or excessive memory consumption on your API gateways.
This article reviews the four primary rate limiting algorithms—Token Bucket, Leaky Bucket, Fixed Window Counter, and Sliding Window Counter—and explains standard HTTP 429 response headers.
1. Token Bucket
The Token Bucket algorithm is the industry standard for REST APIs, used by companies like Stripe, AWS, and Cloudflare.
How it works
Imagine a bucket with a maximum capacity of $N$ tokens.
- Tokens are added to the bucket at a constant refill rate (e.g., 10 tokens per second).
- If the bucket fills up to capacity, extra tokens overflow and are discarded.
- Each incoming request attempts to remove one token from the bucket.
- If tokens are available, the request proceeds. If the bucket is empty, the request is rejected with
429 Too Many Requests.
Refill (e.g. 5 tokens/sec)
│
▼
┌─────────────┐
│ ● ● ● │ Capacity: 10 tokens
│ ● ● │
└──────┬──────┘
│ Request takes 1 token
▼
PassedAdvantages
- Supports bursts: If a user makes zero calls for 10 seconds, the bucket fills to capacity. When they suddenly trigger a batch operation, they can execute 10 requests instantaneously without getting blocked.
- Low memory overhead: You only need to store two numbers per user in Redis: the current token count and the timestamp of the last refill.
2. Leaky Bucket
While Token Bucket controls the arrival rate allowing for brief bursts, the Leaky Bucket algorithm enforces a strictly constant outflow rate.
How it works
Imagine a bucket with a small hole at the bottom:
- Requests enter the top of the bucket at arbitrary rates and queue up (FIFO buffer).
- The bucket leaks requests at a steady, fixed rate (e.g., 2 requests per second) to your backend processing workers.
- If the queue overflows because incoming requests exceed the bucket's capacity, newly arriving requests are immediately dropped or rejected.
Advantages and tradeoffs
- Smooths traffic spikes: Completely prevents sudden traffic surges from overwhelming fragile downstream dependencies or payment gateways.
- Drawback: Burst requests must wait in a queue or get dropped, adding latency to client operations even when total usage across a minute is low.
3. Fixed Window Counter
The simplest and most intuitive approach: divide time into fixed intervals (such as 60-second windows).
How it works
- A counter is tracked for each user and window (e.g.,
user:123:window:12:00). - Each request increments the counter.
- Once the count reaches the limit (e.g., 100 requests/min), requests are dropped until the clock hits
12:01, when the counter resets to zero.
The Boundary Spike Problem
Fixed windows suffer from an edge-case weakness: boundary spikes.
If a client makes 100 requests at 11:59:59 and another 100 requests at 12:00:01, both requests fall into different windows and are allowed. However, the client successfully delivered 200 requests within a 2-second window, potentially crashing your server.
4. Sliding Window Counter / Log
To solve the boundary spike issue without the memory penalty of logging every timestamp, systems use a Sliding Window Counter approximation.
How it works
Instead of resetting on an absolute clock boundary, the algorithm estimates usage based on a weighted average of the current and previous windows:
$$\text{Requests in Window} = (\text{Requests in Prev Window} \times \text{Overlap Percentage}) + \text{Requests in Current Window}$$
For example, if you are 15 seconds into a 60-second window, the previous window contributes 75% ($1 - \frac{15}{60}$) of its requests to your rate calculation.
Advantages
- Eliminates the boundary spike vulnerability.
- Minimal memory: requires keeping only two integer counters per client.
Algorithm comparison summary
| Algorithm | Burst Friendly? | Traffic Smoothing | Memory Footprint | Best Used For |
|---|---|---|---|---|
| Token Bucket | Yes | Moderate | Low (Counter + Timestamp) | General REST APIs, SaaS platforms (Stripe-like) |
| Leaky Bucket | No | Excellent | High (Requires request queue) | Background processing, external rate-capped APIs |
| Fixed Window | High boundary bursts | Poor | Very low (Single counter) | Simple low-scale microservices, rapid prototyping |
| Sliding Window | Smooth bursts | Good | Low (Two counters) | Large-scale edge proxies, Cloudflare, API Gateways |
Standard HTTP 429 response headers
When rejecting or warning clients, your API should communicate rate limits using standard headers:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 30
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 1762248630
{
"error": "Too Many Requests",
"message": "API rate limit exceeded. Retry in 30 seconds."
}Retry-After: The number of seconds (or HTTP date) the client must wait before making another request.RateLimit-Limit: The maximum number of allowed requests in the period.RateLimit-Remaining: The number of remaining requests in the current window.RateLimit-Reset: The Unix timestamp (in seconds) when the limit resets.
You can inspect all HTTP status codes, headers, and client behaviors in ToolDock's HTTP Status Codes Reference.
Calculate and simulate your limits
Sizing rate limits requires balancing burst allowance against server capacity.
- Use the Rate Limit Calculator to quickly convert limits between queries per second (QPS), per minute, or per day, and calculate burst thresholds.
- Test your configuration interactively with the Rate Limiter Simulator, where you can adjust bucket capacities, trigger simulated requests, and view real-time hit logs.