Featured article for the topic Design a rate limiter · picked by the needcode team
Design a rate limiter: token bucket vs sliding log
needcode teamFeatured AuthorPosted · 1 min read
A rate limiter answers one question per request: allow or reject? The interesting parts are the algorithm and keeping counts consistent across many servers.
Token bucket#
Each client has a bucket of N tokens that refills at a fixed rate. A request takes a token or is rejected. It allows short bursts, and it's cheap to store: two numbers per client.
function allow(bucket: { tokens: number; updatedAt: number }, now: number, rate: number, capacity: number) {
bucket.tokens = Math.min(capacity, bucket.tokens + ((now - bucket.updatedAt) / 1000) * rate);
bucket.updatedAt = now;
if (bucket.tokens < 1) return false;
bucket.tokens -= 1;
return true;
}
Sliding log#
Store a timestamp per request and count those in the last window. It's exact, but memory grows with traffic.
Distributed counts#
Keep counters in Redis and update them atomically with a Lua script, so two servers can't both spend the last token.
Comments