Chapter 20: Rate Limiting and Backpressure

Why Rate Limit?

Algorithms

AlgorithmHowPros/Cons
Token BucketBucket fills at rate R, each request takes a tokenAllows bursts up to bucket size. Most common.
Leaky BucketRequests queue, processed at fixed rateSmooth output, no bursts. Good for APIs.
Fixed WindowCount requests per time window (e.g., per minute)Simple but allows 2x burst at window boundary.
Sliding WindowWeighted count across current + previous windowSmooth, no boundary burst. Slightly more complex.

Token Bucket (Most Common)

// Config: rate=10 req/sec, burst=20
// Bucket starts full (20 tokens)
// Each request consumes 1 token
// Bucket refills at 10 tokens/sec
// If empty → reject with 429 Too Many Requests

// Redis implementation (atomic):
// MULTI
//   GET tokens:{client_id}
//   if tokens > 0: DECR tokens:{client_id}; allow
//   else: reject 429
// EXEC

Distributed Rate Limiting

With multiple app servers, rate limit state must be shared (Redis):

App Server 1 ──► Redis (shared counter) ◄── App Server 2 key: "ratelimit:user123" value: tokens remaining

Backpressure

When a system is overloaded, push back on the caller rather than accepting and failing:

Key Takeaways