Rate Limiting Algorithms
By Ankur NayakReviewed
Rate limiting caps how many requests a client may make in a period, protecting services from abuse and overload. The main algorithms are token bucket, leaky bucket, fixed window, sliding log and sliding window counter, each trading accuracy against memory.
How it works
Token bucket: each client has a bucket of up to B tokens refilled at R tokens per second; a request spends one token or is rejected. It allows short bursts up to B while enforcing the average rate R, and needs only two numbers per client. Stripe uses a token bucket for its request rate limiter.
Leaky bucket: requests enter a queue that drains at a fixed rate, smoothing bursts into a steady output, which suits protecting a downstream with a fixed capacity.
Fixed window counts requests per calendar window (for example per minute). It is cheap but allows up to twice the limit around a window boundary. Sliding log stores every request timestamp and is exact but memory-hungry. The sliding window counter blends the current and previous window counts, weighted by how far into the window you are; Cloudflare measured only 0.003% of requests wrongly allowed or limited with this approximation.
Key points
- Token bucket: bursts allowed, average enforced, O(1) memory
- Fixed window: simplest, but bursts at boundaries
- Sliding window counter: near-exact with two counters
- Return 429 with Retry-After, and limit per user, key or IP
When to use it, and pitfalls
Use it for
- Public APIs and login endpoints
- Protecting expensive resources from noisy neighbours
- Load shedding during incidents
Watch out for
- Read-then-write races on shared counters; use atomic increments or scripts
- A central limiter store becoming a single point of failure; fail open for non-critical limits
- Limits that are invisible to clients; publish them in headers
Trade-offs
Exact vs. approximate
Use a sliding window counter or token bucket; reserve sliding logs for strict, low-volume limits.
Pros: Constant memory per key; Accurate enough for abuse protection
Cons: Small error near window edges
Used in
Related building blocks
Frequently asked questions
What is the difference between token bucket and leaky bucket?
A token bucket allows bursts up to its capacity and enforces an average rate. A leaky bucket queues requests and releases them at a constant rate, so output never bursts. Token bucket is the usual choice for API limits; leaky bucket for shaping traffic to a fixed-capacity system.
Why does a fixed window allow double the limit?
A client can send the full limit at the end of one window and again at the start of the next, so twice the limit arrives within a few seconds. Sliding windows and token buckets avoid this.
Sources
- Scaling your API with rate limiters · Stripe
- How we built rate limiting capable of scaling to millions of domains · Cloudflare Blog
- Rate Limiting pattern · Microsoft Azure Architecture Center