Video in progress

Strong Middle 🏗️ System design

How do the token bucket and sliding window rate limiter algorithms differ, and when do you pick which?

Token bucket allows short bursts and limits the average rate. Sliding window enforces an exact "M requests in the last N seconds" rule. For an API it's often token bucket; for a strict quota (for example, login attempts), sliding window.

📖 Answer

Token bucket. The bucket holds at most capacity tokens. rate tokens are added every second. Each request takes one token; no token — 429. If a user stays quiet for a while, the bucket fills up and they can suddenly send 20 requests. A mobile app calls several APIs in parallel when it opens — that's a natural burst, and there's no need to block it.

Fixed window (the simple variant): a key like count:user:12:00 that resets to zero when the minute ends. The problem is at the boundary: 100 at 12:00:59 and another 100 at 12:01:00, that is, 200 go through in one second.

Sliding window log stores the time of every request (a Redis sorted set) and counts those in the last 60 seconds. It's exact, but it means up to 100 entries per user — a lot of memory.

A sliding window counter adds the previous and current window counters with a weight: prev * (1 - elapsed/window) + curr. Memory is low, accuracy is good enough in practice; large systems like Cloudflare use a similar approach.

I usually go with:

  • the general API limit — token bucket (Bucket4j or the gateway itself);
  • password attempts, sending SMS codes — sliding window, because there you must not allow a burst.

Don't forget the response headers: Retry-After along with 429, so the client waits correctly.