System design concepts · Staying Up and Staying Safe

Rate Limiting Algorithms and Overload Protection

Every system has a breaking point. The difference between a good system and a bad one is what happens just past it: a good one slows down gracefully, a bad one falls over and takes its neighbours with it.

What you'll be able to explain
  • Explain why systems collapse under overload instead of just slowing down
  • Choose and implement rate-limiting algorithms, locally and across a cluster
  • Apply backpressure, admission control and load shedding
  • Prioritise critical traffic and degrade features on purpose
  • Stop retry storms and cascading failures before they start

Why overload is so dangerous

Intuition says a server at 120% load should serve 100% and queue the rest. Reality is worse. Past saturation, three feedback loops kick in:

  1. Queues grow without bound. Each request waits longer, so it holds memory, threads and connections longer, so fewer are free.
  2. Timeouts fire. Clients give up after 2 seconds, but the server is still working on the abandoned request. It's now doing work nobody wants.
  3. Retries multiply load. Each timed-out client retries, often 3 times. Load on the struggling server can triple exactly when it can least afford it.
50% load50% goodput100% load98% goodput150% load, no protection35%, latency explodes150% load, with shedding95%, extra load rejected fast300% load, no protectionnear-total outage
Goodput vs offered load. Without protection, useful work collapses past saturation; with load shedding it plateaus.

The goal of overload protection is to keep goodput (successful, useful responses) near capacity no matter how much traffic arrives, by rejecting excess work early and cheaply.

Analogy

A popular restaurant with no host lets everyone in. The kitchen drowns, every table waits two hours, and half the diners walk out after ordering (wasting the food). A restaurant with a host at the door turns some people away with "45-minute wait", and everyone inside gets dinner on time. Rate limiting and load shedding are the host.

Rate limiting: fair shares per client

Rate limiting caps how much any one client (user, API key, IP, tenant) can send. It protects you from abusive or buggy clients and makes sure one tenant can't starve the rest.

What to limit by

Key Good for Watch out
API key / user ID Fair use per customer, paid tiers Needs authentication first
IP address Anonymous endpoints, login, sign-up NAT and mobile carriers put thousands of users behind one IP
Tenant / organisation B2B fairness Big tenants need bigger quotas
Endpoint / cost class Expensive operations (search, exports) Weigh by cost, not just count
Global Protecting a fragile dependency Coarse; combine with per-client limits

The algorithms

Algorithm How it works Bursts Memory Notes
Fixed window Count requests per calendar minute 2× burst at window edges 1 counter Simplest; edge spikes
Sliding log Store each request's timestamp; count those in the last 60 s Exact One entry per request Precise but memory-hungry
Sliding window counter Weighted mix of this and the previous window's counts Smooth 2 counters Great default for APIs
Token bucket Tokens refill at rate r up to capacity b; each request takes one Allows bursts up to b 2 numbers Most popular; easy to reason about
Leaky bucket Requests queue and drain at a constant rate Smooths to a steady rate A queue Good for shaping outbound traffic
Bucket full (20 tokens)A burst of 20 requests passes instantlyBucket emptyRequest 21 is rejected with 429 until tokens refillRefill+1 token every 100 ms, never above 20Steady stateLong-run rate can't exceed 10/s, whatever the pattern
Token bucket with rate 10/s and capacity 20: a client can burst 20 requests, then is held to 10 per second.

Distributed rate limiting

With 50 API servers, each needs to know the client's global count. Options:

  1. Central store (Redis): each request runs an atomic script (INCR + EXPIRE, or a Lua token-bucket) on the client's key. Accurate; adds ~0.5 ms and a dependency.
  2. Local limits with a share: each of 50 servers allows limit / 50. No coordination, but inaccurate when traffic is uneven across servers.
  3. Hybrid: count locally, sync to Redis every 100 ms. Slightly loose, far fewer Redis calls.

If Redis is down, fail open (allow traffic) for ordinary APIs, so the limiter doesn't cause an outage, but fail closed for abuse-sensitive endpoints like login and OTP. Case Study C2 of the book designs this in full.

Telling clients what happened

Return HTTP 429 Too Many Requests with Retry-After, plus headers like RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset. Good clients back off; your own SDKs should honour these automatically.

Backpressure: slow the producer down

Rate limiting protects you from clients. Backpressure protects each stage of a pipeline from the stage before it. When a consumer can't keep up, it signals upstream to slow down instead of buffering forever.

  • Bounded queues: when the queue is full, the producer blocks or gets an error, rather than the queue eating all memory.
  • Pull-based consumption: consumers fetch work when ready (Kafka, SQS), so they can't be flooded.
  • Flow control: TCP windows, HTTP/2 stream windows and reactive streams all carry "I can take N more" signals.
Common trap

"Just make the queue bigger." An unbounded queue doesn't remove overload; it converts it into latency and then into an out-of-memory crash. By the time a request reaches the front of a 10-minute queue, the user has long gone. Bound every queue, and decide what happens when it's full.