Module 2 · Backend architectureLesson 19 of 886 minIntermediate

Rate limiting

A rate limiter caps how many requests a client can make, so one noisy client can't take the service down for everyone.

Try it

Start with the limiter off and push traffic high. Then turn it on and watch extra requests get a quick 429 while the server stays healthy.

Every public service eventually meets a client that sends too much: a buggy script in a loop, a scraper, a sudden viral spike, or an attack. A rate limiter decides who gets served.

Token bucket

The most common algorithm:

  • Each client has a bucket that holds up to N tokens.
  • Tokens are added at a steady rate, say 5 per second, up to N.
  • Each request takes one token. No token? Rejected.

It allows short bursts (up to N) while keeping the long-term average at the refill rate.

Other algorithms

  • Fixed window: max 100 requests per minute, counter resets on the minute. Simple, but allows 200 in two seconds around the reset.
  • Sliding window: counts the last 60 seconds at every moment. Smoother.
  • Leaky bucket: requests queue and leave at a fixed rate. Smooths output to downstream systems.

Where to limit

  • Per user or API key: fairness between customers.
  • Per IP: for anonymous traffic and login pages.
  • Globally per service: protects a fragile dependency.

In a fleet of servers, counters must be shared, usually in Redis, or each server's limit must be divided by the number of servers.

Rejecting politely

Return 429 Too Many Requests with a Retry-After header. Good clients back off and try later. Cheap rejection is the point: a fast "no" costs far less than a slow, overloaded "maybe".

Quick check

In a token bucket with 10 tokens refilling at 2 per second, a client sends 15 requests at once after a quiet minute. What happens?