Rate Limiting Algorithms Explained: Token Bucket, Sliding Windows, and GCRA
Fixed windows, sliding logs, sliding window counters, token buckets, and GCRA all answer the same question with different memory and burst trade-offs. This guide compares them, shows a tested Python implementation, and covers atomic Redis limiters and HTTP 429 responses.

Every public API eventually meets a client that sends far more traffic than intended: a retry loop with no backoff, a scraper, a misconfigured cron job, or a genuine spike from a product launch. A rate limiter decides, request by request, whether to serve or refuse. The decision sounds simple, but the algorithm behind it determines how bursts are treated, how much memory each client costs, and how the limiter behaves when it runs across many servers.
This explainer walks through the four algorithms that show up most often in production — fixed window, sliding window log, sliding window counter, and token bucket — plus GCRA, a compact variant of the leaky bucket. It then covers how to make a limiter correct when it is shared across a fleet, and how to tell clients what happened using HTTP 429 and the emerging RateLimit headers.
What a rate limiter is actually deciding
Every limiter answers the same question: given what this client has done recently, is one more request acceptable? The differences come from how each algorithm remembers "recently". That memory is the core trade-off. Remembering every timestamp is exact but expensive. Remembering one counter is cheap but crude. The useful algorithms sit in between.
It also helps to separate two goals that often get blurred together. One is fairness: no single customer should consume capacity meant for everyone. The other is protection: the service itself should not fall over. Stripe's engineering write-up on its limiters makes this distinction explicit, pairing per-user request-rate and concurrency limiters with fleet-wide load shedders that drop lower-priority traffic first when the system is under stress. The algorithms below are mostly about the first goal.
Fixed window: one counter per time bucket
The simplest approach splits time into fixed buckets — say, each calendar minute — and keeps a counter per client per bucket. Each request increments the counter; if it passes the limit, the request is refused. When the minute rolls over, a fresh counter starts at zero. In Redis this is a single INCR on a key such as the client ID plus the current minute, with an expiry so old keys clean themselves up. The Redis documentation shows exactly this pattern, wrapping INCR and EXPIRE in MULTI/EXEC so both always happen together.
The weakness is the boundary. With a limit of 100 per minute, a client can send 100 requests at 12:00:59 and another 100 at 12:01:00. Both windows look fine on their own, but the service just absorbed 200 requests in about one second. For protecting a fragile backend, that double burst is often exactly the traffic pattern you were trying to prevent.
Sliding window log: exact, but you pay per request
The sliding window log removes the boundary problem by storing the timestamp of every accepted request, typically in a Redis sorted set. On each request, entries older than the window are trimmed, the remaining entries are counted, and the new request is admitted only if the count is below the limit. The result is precise: at any instant, the limiter knows exactly how many requests landed in the last 60 seconds.
The cost is memory and work proportional to the limit. A client allowed 10,000 requests per hour may need 10,000 stored timestamps. Multiply that by every active client and the limiter can become a meaningful share of your cache's footprint. The log is a reasonable choice for low limits where precision matters, such as login attempts, and a poor one for high-volume API quotas.
Sliding window counter: two numbers and a weighted guess
The sliding window counter keeps the cheapness of fixed windows while smoothing out the boundary. It stores only two counts — the current window and the previous one — and estimates the rolling rate by assuming the previous window's requests were spread evenly. The previous count is weighted by how much of that window still overlaps the last 60 seconds.
estimate = previous_count × (window − elapsed) / window + current_count
— Sliding window counter formula, as described by Cloudflare
Cloudflare's write-up uses a worked example worth repeating. The limit is 50 requests per minute. The current minute began 15 seconds ago and has seen 18 requests; the previous minute saw 42. The estimate is 42 × 45/60 + 18 = 49.5, so the very next request would push the client over the limit. Cloudflare reported that when it checked this approximation against 400 million requests from 270,000 sources, only 0.003% of requests were wrongly allowed or limited, and none of the limited sources were actually under the threshold.
The approximation fails in a predictable direction: if the previous window's traffic was all packed into its final seconds, the even-spread assumption undercounts it. For most API quotas that error is acceptable given that each client costs two integers.
Token bucket: a budget that refills
The token bucket models the limit as a budget. Each client has a bucket holding up to a fixed capacity of tokens. Tokens are added at a steady refill rate, and each request spends one (or more, for expensive operations). When the bucket is empty, requests are refused until tokens trickle back. Stripe has described using the token bucket for its request-rate limiter.
What makes the token bucket popular is that it expresses two separate knobs. The refill rate sets the long-term average, and the capacity sets how big a burst is tolerated. A bucket with capacity 20 and a refill of 5 per second lets a client fire 20 requests at once after a quiet period, then settle to 5 per second. That matches how real clients behave: a page load triggers a cluster of calls, followed by silence.
No background process is needed to add tokens. The limiter stores the token count and the time it was last updated, and on each request it adds elapsed time multiplied by the refill rate, capped at capacity. State per client is two numbers, the same as the sliding window counter.
Leaky bucket and GCRA
The leaky bucket is the mirror image: requests pour into a queue that drains at a constant rate, which smooths output rather than permitting bursts. A naive implementation needs a drip process to drain the bucket, and that process can fall behind. GCRA, the generic cell rate algorithm, reaches the same behavior without any drip. It stores a single timestamp per client, the theoretical arrival time, and admits a request if that time minus the allowed burst tolerance is not in the future. Brandur Leach's write-up on GCRA points out that removing the drip removes a whole category of failure, and that when several servers share the limit, the timestamp should come from the data store's clock rather than each machine's own.
A worked example in Python
The following script implements a token bucket and a sliding window counter in memory. Both accept an injectable clock so the behavior is deterministic, and the final lines reproduce the 49.5 example from above.
import time
class TokenBucket:
def __init__(self, capacity, refill_per_sec, clock=time.monotonic):
self.capacity = capacity
self.rate = refill_per_sec
self.clock = clock
self.tokens = capacity
self.last = clock()
def allow(self, cost=1):
now = self.clock()
elapsed = now - self.last
self.last = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
if self.tokens >= cost:
self.tokens -= cost
return True
return False
class SlidingWindowCounter:
def __init__(self, limit, window_sec, clock=time.time):
self.limit = limit
self.window = window_sec
self.clock = clock
self.counts = {} # window index -> request count
def allow(self):
now = self.clock()
idx = int(now // self.window)
elapsed = now - idx * self.window
prev = self.counts.get(idx - 1, 0)
curr = self.counts.get(idx, 0)
estimate = prev * (self.window - elapsed) / self.window + curr
if estimate + 1 > self.limit:
return False
self.counts[idx] = curr + 1
# keep only the two windows the estimate needs
self.counts = {k: v for k, v in self.counts.items() if k >= idx - 1}
return True
if __name__ == "__main__":
# Fake clock so the demo is deterministic.
t = [0.0]
clock = lambda: t[0]
bucket = TokenBucket(capacity=5, refill_per_sec=1, clock=clock)
burst = [bucket.allow() for _ in range(7)]
print("burst of 7:", burst)
t[0] = 2.0
print("after 2s:", [bucket.allow() for _ in range(3)])
# Previous minute: 42 requests; current minute: 18 so far; 15s in.
swc = SlidingWindowCounter(limit=50, window_sec=60, clock=clock)
swc.counts = {0: 42, 1: 18}
t[0] = 75.0
print("estimate before:", 42 * (60 - 15) / 60 + 18)
print("next request allowed?", swc.allow())
Running it with Python 3 prints the output below. The bucket allows the first five requests of the burst, refuses the next two, and after two seconds has earned back exactly two tokens. The sliding window counter refuses the request that would lift the estimate from 49.5 past 50.
burst of 7: [True, True, True, True, True, False, False]
after 2s: [True, True, False]
estimate before: 49.5
next request allowed? FalseMaking it work across many servers
An in-memory limiter only works when a single process sees all of a client's traffic. Behind a load balancer with ten instances, each instance would allow the full limit, so the effective limit becomes ten times larger. The usual fix is to keep the state in a shared store such as Redis, which is what Stripe described doing.
Shared state introduces a race. If two servers each read the token count, both see one token left, and both write back zero, two requests got through on one token. The read-modify-write must be atomic. Redis guarantees that a Lua script runs atomically, with no other commands interleaved while it executes, so the entire token bucket update can live in one script:
-- KEYS[1] bucket key, e.g. "rl:user42"
-- ARGV[1] capacity (max tokens)
-- ARGV[2] refill rate (tokens per second)
-- ARGV[3] cost of this request
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
-- Use the Redis server clock so every app server agrees on "now".
local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
local state = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(state[1]) or capacity
local ts = tonumber(state[2]) or now
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HSET', KEYS[1],
'tokens', string.format('%.6f', tokens),
'ts', string.format('%.6f', now))
redis.call('EXPIRE', KEYS[1], math.ceil(capacity / rate) + 1)
-- Return tokens as a string: Lua numbers become truncated integers in replies.
return {allowed, string.format('%.3f', tokens)}A few details in that script are deliberate. The key is passed through KEYS rather than built inside the script, because Redis requires scripts to declare the keys they touch so they work correctly in both standalone and clustered deployments. The clock comes from Redis TIME so that application servers with drifting clocks still agree. The expiry lets idle buckets disappear once they would have refilled anyway. And the token count is returned as a string because Redis converts Lua numbers to integers in replies, which would silently drop the fraction.
Because the script is sent with EVALSHA in normal use, remember that the Redis script cache is volatile and can be emptied by a restart or failover. Most client libraries retry with the full script when Redis answers NOSCRIPT, but confirm that yours does.
Telling clients what happened
A refused request should be easy for a well-behaved client to handle. RFC 6585 defines status 429 Too Many Requests for this purpose, allows a Retry-After header saying how long to wait, and states that 429 responses must not be stored by a cache. Beyond that, the IETF HTTP API working group is developing standard RateLimit-Policy and RateLimit header fields; at the time of writing the specification is still an Internet-Draft (revision 11), so treat the exact syntax as subject to change. In that draft, the policy header advertises the quota q and window w, while the RateLimit header reports the remaining quota r and the seconds t until it resets.
HTTP/1.1 429 Too Many Requests
Retry-After: 2
RateLimit-Policy: "burst";q=100;w=60
RateLimit: "burst";r=0;t=2
Content-Type: application/json
{"error": "rate_limited", "message": "Limit is 100 requests per minute. Retry in 2 seconds."}A production checklist
- Choose the key deliberately: API key or account ID for fairness, IP address only when there is no authenticated identity, since many users can share one address.
- Pick the algorithm from the traffic shape: token bucket when bursts are normal, sliding window counter for cheap rolling quotas, a sliding log for small limits that must be exact.
- Make shared-state updates atomic with a single script or a single atomic command, never a read followed by a separate write.
- Decide what happens when the limiter's store is down. Stripe's advice is to fail open so a limiter outage does not take the API down with it; a login-attempt limiter may reasonably fail closed instead.
- Dark-launch a new limiter by logging what it would block before enforcing it, then tune thresholds with real data.
- Return 429 with Retry-After and a message that names the limit, and add a kill switch plus metrics on how often each limiter fires.
None of these algorithms is universally best. Fixed windows are fine for coarse daily quotas, token buckets match interactive API traffic, and GCRA packs the same behavior into a single timestamp. The real engineering work is in the surrounding decisions: which identity to limit, where the state lives, how the limiter fails, and how clearly the refusal is explained to the caller.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter