Skip to content

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.

Text by needcode team, licensed under CC BY-SA 4.0. You may share and adapt it with credit to the author, under the same licence.

Other approaches to Design a rate limiter

Submit your approach

No other approaches yet. Think you can explain it differently? Write one.

Comments

Loading comments…