Course map

Topic 096 / Core

Rate limiting: token bucket, leaky bucket, sliding window

Chapter 6.4 · Traffic Control and Workload Shaping

What and why

Without a limit, one client — malicious or just buggy — can consume capacity meant for everyone else; rate limiting caps how many requests a given identity (user, IP, API key) may make in a window, rejecting the excess before it costs real work. Because instances are stateless and multiple (→ 91, → 92), the count has to live somewhere every instance can see — a shared distributed cache (→ 87). Builds on: → 87 (Redis and distributed caching).

Diagram

Algorithm Behavior Burst handling
Token bucket a bucket holds up to N tokens; each request consumes one; tokens refill at a fixed rate allows a burst up to the bucket size, then throttles to the refill rate
Leaky bucket requests queue and drain at a fixed outflow rate smooths to constant output; no burst above the drain rate
Sliding window counts requests in a moving window, not a fixed reset point accurate at the window boundary, costlier to compute

How it works

  1. Token bucket: start with N tokens; each request takes one if available (allowed) or is rejected if the bucket is empty; tokens are added back at a fixed refill rate up to capacity N — this is why it allows a burst (spend the whole bucket at once) but settles to the refill rate for sustained traffic.
  2. Leaky bucket: incoming requests join a queue (or are dropped if full); the queue drains at a fixed rate regardless of arrival speed — output is smoothed, with no equivalent of "spend the whole bucket."
  3. Sliding window: count requests in the last fixed duration, continuously, not reset at a fixed clock boundary — this avoids the fixed-window bug where two bursts straddling a reset can together exceed the intended limit within a short span.
  4. Distributed enforcement: the count (tokens remaining, queue depth, or window count) lives in a shared cache (→ 87) so every stateless instance (→ 91) checks and updates the same number — typically an atomic increment-with-expiry, since two instances racing to check-then-increment separately would both allow a request the shared limit should have rejected.
  5. On rejection, return HTTP 429 with a Retry-After header; a well-behaved client backs off accordingly (→ 152) rather than retrying immediately and making the problem worse.

Practical example

(numbers illustrative). A token bucket allows 100 tokens, refilling at 10/second. A client idle until now sends 100 requests instantly — all 100 succeed (the full bucket) — then the 101st request needs 1 new token, available after 1 ÷ 10 = 0.1 s. Over the next 60 seconds, the now-empty bucket allows at most 10 × 60 = 600 further requests at the sustained rate — so total allowed in that first minute = 100 (burst) + 600 (sustained) = 700 requests, not 600, and not unlimited.

When to use it

  • Use token bucket when bursts should be tolerated up to a known size.
  • Use leaky bucket when a constant, smoothed outflow matters more than accommodating bursts.
  • Use sliding window when precise, abuse-resistant counting matters more than the extra cost of computing it.
  • Avoid a naive fixed-window counter as the default — it allows up to 2× the intended limit across a reset boundary.
  • Failure scenarios: enforcing the limit locally per instance instead of in a shared store, so the real limit becomes (per-instance limit × instance count); rate-limiting by an identity an attacker can rotate freely (IP alone) instead of something costlier to obtain (an API key); returning a bare 429 with no Retry-After.
  • Simpler alternative: for internal, trusted traffic with no abuse risk, a connection or concurrency limit at the load balancer (→ 92) may be enough — full rate limiting is for untrusted or billable traffic.

Practice

(mechanism kind — implement, 20–30 min, lab: Redis).

  1. Implement a token bucket in Redis using an atomic increment-with-expiry pattern; verify a burst up to bucket size succeeds and the next request is rejected.
  2. Measure the actual allowed request count over 60 seconds with bucket = 100 and refill = 10/second, and confirm it lands at 700, not 600 or unlimited.
  3. Run two application-instance processes both enforcing the same limit against the same Redis key; confirm the shared limit holds, not double it.

Done when the 60-second allowed-request count matches the computed 700, and two instances together never exceed the single configured limit.

Shared lab setup

Key takeaway

Rate limiting caps consumption per identity before it costs real work; token bucket tolerates bursts, leaky bucket smooths to a constant rate, sliding window is the most accurate and most costly — all three need a shared store to work across stateless instances (→ 91, → 87). Done when you can: compute a token bucket's allowed request count over a given window, and name which algorithm fits a given burst tolerance. Used next in → 97 (backpressure and load shedding, what happens to requests rate limiting doesn't even see), → 99 (fan-out abuse protection); Projects 2, 4 and 16.

References

None — this topic makes no external claims.

Source directory

Search the guide