I got paged at 2:13 AM because our public API started returning 502s to every customer. The cause wasn't traffic volume — we were well under our provisioned capacity. The cause was our own rate limiter. We had implemented a naive fixed-window counter in Redis, and at the window boundary, a burst of queued retries from a single misbehaving integration slipped through, doubled our downstream database connections, and cascaded into a full outage. In my experience, most rate limiting failures don't come from choosing the wrong algorithm on paper; they come from misunderstanding how that algorithm behaves under real-world traffic patterns, retries, and distributed race conditions.
Rate limiting is not just about protecting your servers. It's about defining a contract with your consumers, enforcing fairness between tenants, and providing predictable degradation under load. If you are building APIs that will see more than a few hundred requests per second or serve multiple tenants with different quotas, the implementation details matter immensely. This article breaks down the patterns I've used in production, where each one fails, and how to implement them correctly for distributed systems.
Why Fixed Windows Fail You at Scale: The Midnight Burst Problem
The fixed window is where everyone starts, and for good reason. It's simple to understand and cheap to implement: divide time into buckets, say one minute, and count requests per key. If a client exceeds 100 requests in minute 1:00:00 to 1:01:00, you reject them until 1:01:00.
The problem is the boundary effect. A client can make 100 requests at 1:00:59 and another 100 requests at 1:01:01. That's 200 requests in two seconds, while your system thinks it allowed only 100 per minute. For low limits this is a rounding error. For high-throughput APIs with expensive operations, that 2x burst can overwhelm your workers, connection pools, or downstream dependencies. I have seen this exact pattern take down search indexing pipelines where each request triggered a heavy Elasticsearch query.
The Thundering Herd on Window Reset
The second failure mode is less obvious. When you return 429s with a fixed window, many clients will retry exactly when the window resets. If you tell 5,000 clients "retry at 12:00:00," you will get 5,000 requests at 12:00:00.000. This creates a self-inflicted DDoS. Add jittered Retry-After values and staggered windows if you must use fixed windows, but understand you are patching a fundamental flaw in the model.
Fixed windows are still useful for coarse, low-precision limits — like a daily quota of 10,000 requests per API key where bursts don't matter. For anything requiring smooth enforcement, you need a different approach. When you are structuring your overall REST API Design: Principles That Stand the Test of Time, consider fixed windows as an accounting mechanism, not a protection mechanism.
Token Bucket Mechanics: Implementing Burstable Throughput Without Starvation
The token bucket is my default choice for most user-facing APIs. It allows bursts while enforcing a long-term average rate, which matches how humans and well-behaved integrations actually use APIs. The mental model is simple: imagine a bucket that holds capacity tokens. Tokens are added at a fixed refill_rate per second. Each request costs one token. If the bucket is empty, the request is rejected.
The two parameters control the trade-off. Capacity defines your burst size. Refill rate defines your sustained throughput. For example, a bucket with capacity 100 and refill rate 10 tokens/second allows a client to burst 100 requests immediately, then sustain 10 req/s thereafter. If they go idle for 10 seconds, the bucket refills and they can burst again. This is ideal for interactive applications where a user action might trigger 20 parallel API calls followed by silence.
Correct Refill Logic and Floating Point Drift
I've found that most buggy token bucket implementations calculate refills incorrectly. Don't use a background timer that adds tokens every N milliseconds. Instead, calculate tokens lazily on each request based on elapsed time. This avoids timers, race conditions, and clock drift.
import time
import threading
class TokenBucket:
def __init__(self, capacity: int, refill_rate_per_sec: float):
self.capacity = float(capacity)
self.refill_rate = float(refill_rate_per_sec)
self.tokens = float(capacity)
self.last_refill_ns = time.monotonic_ns()
self.lock = threading.Lock()
def allow_request(self, tokens_needed: int = 1) -> bool:
with self.lock:
now_ns = time.monotonic_ns()
elapsed_sec = (now_ns - self.last_refill_ns) / 1e9
# Lazily refill based on elapsed time
if elapsed_sec > 0:
self.tokens = min(
self.capacity,
self.tokens + (elapsed_sec * self.refill_rate)
)
self.last_refill_ns = now_ns
if self.tokens >= tokens_needed:
self.tokens -= tokens_needed
return True
return False
Notice the use of time.monotonic_ns() instead of wall-clock time. Wall-clock time can jump backward due to NTP corrections, which would cause your bucket to incorrectly withhold tokens. The Python Documentation is explicit about this distinction. Also, store tokens as a float. If you truncate to integers, a refill rate of 0.5 tokens/sec will never refill.
For multi-tenant systems, I typically configure token buckets per tenant tier. Free tier: capacity 60, refill 1/sec (burst 60, sustained 1 req/s). Pro tier: capacity 600, refill 10/sec. This gives paying users a better interactive experience without giving them 10x sustained load on your infrastructure.
Sliding Window Log vs Sliding Window Counter: Memory and Precision Trade-offs
If you need precise limits with no burst cheating, sliding windows are the answer. There are two distinct variants and they have very different operational costs.
Sliding Window Log: Precise but Expensive
The log keeps a sorted set of timestamps for every request within the window. To check a new request at time T, you evict timestamps older than T - window_size, count the remaining entries, and allow if count < limit. This is perfectly accurate. It also allows you to answer "how many requests in the last 37.5 seconds?" with precision. In my experience, this is necessary for strict compliance or financial rate limits where you cannot allow even 1% overage.
The cost is memory and operation time. For a limit of 10,000 requests per minute per API key, you might store 10,000 timestamps per key. With 100,000 active keys, that is a billion entries. In Redis, each timestamp is ~16 bytes plus overhead, so you can exhaust memory quickly. Pruning and counting also becomes O(n) or O(log n) depending on implementation.
Sliding Window Counter: The Hybrid Compromise
The counter approximates the log by combining two fixed windows with a weighted calculation. You keep the count for the previous window and the current window. The estimated count in the sliding window is: prev_count * (overlap / window_size) + current_count.
For example, with a 1-minute window and at 00:01:20 (20 seconds into the current window), the overlap with the previous window is 40 seconds. So weight = 40/60 = 0.66. If previous window had 80 requests and current has 30, estimated sliding count = 80 * 0.66 + 30 = 82.8. This smooths the fixed window boundary burst to within about 5-8% error while using only two integer counters per key. I've found this is the sweet spot for 90% of production APIs — it prevents the 2x burst without the memory blowup.
-- Sliding Window Counter in Redis + Lua (atomic)
-- KEYS[1] = rate_limit_key, ARGV[1] = window_size_ms, ARGV[2] = limit
local key = KEYS[1]
local window_size = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local current_window = math.floor(now / window_size)
local prev_window = current_window - 1
local current_key = key .. ":" .. current_window
local prev_key = key .. ":" .. prev_window
local current_count = tonumber(redis.call("GET", current_key) or "0")
local prev_count = tonumber(redis.call("GET", prev_key) or "0")
local elapsed_in_current = now % window_size
local weight = (window_size - elapsed_in_current) / window_size
local estimated = prev_count * weight + current_count
if estimated >= limit then
return {0, estimated}
else
redis.call("INCR", current_key)
redis.call("PEXPIRE", current_key, window_size * 2)
redis.call("PEXPIRE", prev_key, window_size * 2)
return {1, estimated + 1}
end
This script must run as a Lua script for atomicity. Without atomicity, two parallel requests can both read count=99 for a limit of 100 and both increment to 101, violating your limit. Choosing how to version and communicate these limits to clients is closely tied to your broader strategy for API Versioning Strategies: URL Path, Header and Query Parameter Approaches, because changing limit algorithms is a breaking behavioral change.
Leaky Bucket as a Traffic Shaper: When Smoothing Matters More Than Burst
Token bucket and leaky bucket are often confused but they are opposites. Token bucket allows bursts and enforces average rate. Leaky bucket smooths bursts into a constant rate. Imagine requests pouring into a bucket with a hole at the bottom that leaks at a fixed rate. If the bucket overflows, requests are rejected. If implemented as a queue, it delays requests instead of rejecting them.
Use leaky bucket when downstream systems cannot handle bursts at all — for example, when calling a legacy database, a third-party payment gateway, or a webhook delivery system that will throttle you. I've used a leaky bucket to protect a PDF rendering service that could handle 5 concurrent renders but would crash at 10. By queuing requests and leaking them at 5 per second, we smoothed a 50-request burst over 10 seconds instead of rejecting 45 of them.
The implementation is typically a queue with a single worker. In Python with asyncio:
import asyncio
import time
from collections import deque
class LeakyBucketQueue:
def __init__(self, leak_rate_per_sec: float, capacity: int):
self.leak_rate = leak_rate_per_sec
self.capacity = capacity
self.queue = deque()
self.last_leak_ns = time.monotonic_ns()
async def submit(self, item) -> bool:
self._leak()
if len(self.queue) >= self.capacity:
return False # bucket full, reject
self.queue.append((item, time.monotonic_ns()))
return True
def _leak(self):
now = time.monotonic_ns()
elapsed = (now - self.last_leak_ns) / 1e9
leaks = int(elapsed * self.leak_rate)
for _ in range(min(leaks, len(self.queue))):
self.queue.popleft()
if leaks > 0:
self.last_leak_ns = now
async def worker(self, process_fn):
while True:
self._leak()
if self.queue:
item, _ = self.queue.popleft()
await process_fn(item)
await asyncio.sleep(1 / self.leak_rate)
Don't use leaky bucket for user-facing synchronous APIs if you can avoid it. Queuing adds latency, and if the queue fills, you still have to reject. It shines for asynchronous, background processing where smoothing is more valuable than immediate response.
Distributed Rate Limiting With Redis and Lua: Avoiding Race Conditions Across Nodes
Local in-memory limiters are useless once you have more than one API server. A client can make 100 requests to each of your 10 nodes and get 1000 requests through a limit of 100. You need a centralized store. Redis is the de facto choice because it is fast and its single-threaded execution model makes atomic operations straightforward.
The critical rule is: never implement check-then-set in your application code. This pattern is broken:
# DO NOT DO THIS - race condition
count = redis.get(key)
if int(count or 0) < limit:
redis.incr(key) # another process incremented between GET and INCR
return True
Two servers can both read 99, both decide to allow, and both increment to 101. The only safe way is to execute the read, decision, and write inside Redis itself using a Lua script or Redis 7+ Functions. The sliding window Lua script above is an example. For token bucket, you need to store tokens and timestamp in a hash and update them atomically in Lua.
Handling Redis Failures
What happens when Redis is down? You have two options: fail open (allow all requests) or fail closed (reject all requests). I've found that failing open is correct for availability-focused public APIs — you don't want to take your entire API down because your rate limiter has an issue. Failing closed is correct for abuse prevention or costly operations. Implement a circuit breaker with a local fallback like a simple in-memory token bucket with conservative limits if Redis becomes unreachable. In microservice environments where you might consider gRPC for Microservice Communication: Protocol Buffers and Streaming, you can also push rate limiting to an Envoy or Istio sidecar, which handles the distributed state for you via a global rate limit service.
Also consider key sharding and TTLs. Always set PEXPIRE on keys. Without TTLs, a key per IP address or API key will grow forever. Use hash tags in Redis Cluster like {api}:ratelimit:12345 to ensure related keys land on the same shard if your Lua script touches multiple keys.
Communicating Limits to Clients: Headers, Retry-After and 429 Handling Strategies
A rate limiter that just returns 429 without context creates a terrible developer experience and encourages clients to hammer your API. The IETF has been standardizing rate limit headers in the RateLimit fields draft, and adopting them early pays off. The current de facto standard uses three headers, as documented on MDN Web Docs and the IETF RFC Standards drafts:
RateLimit-Limit: The quota for the window. RateLimit-Remaining: How many requests remain. RateLimit-Reset: Seconds until the window resets. For token bucket, Reset is not meaningful, so send Retry-After on rejection instead.
Always send these headers on both successful and rejected responses. Clients use Remaining to pace themselves. On a 429, you MUST send Retry-After as either seconds or an HTTP-date. I've seen SDKs that treat 429 without Retry-After as a fatal error because they have no idea when to retry.
Be careful with the status code. Use 429 Too Many Requests for quota violations. Do not use 503 Service Unavailable — that implies a server problem and will cause most HTTP clients to retry aggressively with exponential backoff, making your overload worse. Include a JSON body with a machine-readable error code like rate_limit_exceeded and a human message indicating whether the limit is per-second, per-minute, or per-day. Log the limit key, the configured limit, and the estimated count at rejection time. Without that, you cannot debug customer complaints that "the API is randomly throttling me."
| Algorithm | Allows Burst? | Precision | Memory per Key | Best For |
|---|---|---|---|---|
| Fixed Window | Yes — 2x at boundary | Low | 1 counter | Daily quotas, simple billing limits |
| Token Bucket | Yes — controlled by capacity | Medium | 2 values (tokens + timestamp) | User-facing APIs needing bursty UX |
| Sliding Window Log | No | Perfect | N timestamps | Strict compliance, financial APIs |
| Sliding Window Counter | Minimal (~5% error) | High (approx.) | 2 counters | General purpose high-throughput APIs |
| Leaky Bucket | No — smooths bursts | Medium | Queue length | Protecting fragile downstream systems |
Frequently Asked Questions
Should I rate limit by IP address or by API key?
Rate limit by the finest-grained identity you have. For authenticated APIs, limit by API key or user ID first, then apply a secondary coarse limit by IP to mitigate credential stuffing or key-less endpoints. IP-only limits are ineffective behind NAT — a university or corporate proxy can put thousands of users behind one IP — and they are trivial to bypass with rotating proxies. In my experience, tiered limits (authenticated key limit + IP limit + global concurrency limit) provide the best coverage without punishing legitimate users sharing an IP.
How do I handle rate limiting for GraphQL or batch APIs where one request can be expensive?
Request-count limiting breaks down when one request can represent vastly different costs. Assign a cost or complexity score to each operation. For GraphQL, calculate query complexity based on depth, number of fields, and resolver cost — then consume that many tokens from your bucket. For batch REST endpoints, charge tokens per item in the batch. This prevents a single 1000-item batch request from bypassing a 100 req/s limit. Store and enforce complexity-based limits alongside traditional count limits.
Can I implement distributed token bucket without Redis?
Yes, but with trade-offs. Options include using your database with optimistic locking (slow, contention heavy), using a consensus system like etcd or Consul, or using a local limiter with a gossip protocol for approximate limits. For strong consistency without Redis, consider a dedicated rate limiting service like Envoy's global rate limit service or a sidecar using the ratelimit gRPC service. If you accept approximate limits, each node can run a local token bucket at limit / N nodes. This is simpler and works well when slightly exceeding the global limit for a short time is acceptable.
What is the difference between throttling and rate limiting?
The terms are often used interchangeably, but there is a useful distinction. Rate limiting rejects requests that exceed a count in a window (hard limit, returns 429). Throttling slows down or degrades responses when under load — it might add latency, reduce response fidelity, or queue requests via a leaky bucket. I've found that combining both works best: rate limiting enforces the contract and fairness, while throttling via concurrency limits and adaptive queuing protects your infrastructure from traffic that is technically within limits but still heavy.