Rate limiting

Topic 2 of 8 in Week 6: Production concerns10 min readIntermediateFree course

Overview

Without limits, one buggy client, scraper or attacker can consume all of a service’s capacity and degrade it for everyone. Rate limiting caps how many requests a client may make in a time period. It protects services, enforces fair use and implements pricing plans. Designing a rate limiter is also a classic interview question (you’ll do the full design in week 7).

What to limit by

  • Per user or API key: the usual choice for authenticated APIs and plans.
  • Per IP address: for anonymous traffic, with care, since many users can share one IP.
  • Per endpoint: stricter for expensive or sensitive actions (login, password reset, search).
  • Global or per service: to protect a dependency’s total capacity.

Several limits often apply at once: 1,000 requests per minute per key and 5 login attempts per minute per account.

Algorithms

Rate-limiting algorithms. Token bucket: tokens refill at 10 per second into a bucket with capacity 20, which is the maximum burst; each request takes one token and an empty bucket means 429 Too Many Requests. Sliding window counter: with a limit of 100 per minute, the previous minute had 80 requests and this minute has 30 so far. A quarter of the way into this minute, the window covering the last 60 seconds is estimated as 80 times 75 percent plus 30, which is 90, at most 100, so the request is allowed. It is smooth and needs little memory per key, while fixed windows allow double bursts at the edges. Store counters in Redis with atomic INCR or a Lua script so all gateway instances share one limit per user or API key, and return 429 with Retry-After and rate-limit headers.

Token bucket

Each client has a bucket holding up to capacity tokens, refilled at a steady rate. Each request takes a token; with no tokens left, the request is rejected. Bursts up to the capacity are allowed, while the long-run average can’t exceed the refill rate. Only two numbers are stored per client (tokens and last refill time), and refills are computed lazily on each request. Used by AWS, Stripe and many gateways.

Leaky bucket

Requests enter a queue that drains at a fixed rate; when the queue is full, new requests are dropped. It smooths output to a constant rate, which suits protecting a downstream system that needs steady load.

Fixed window counter

Count requests per calendar window (for example per minute) and reject above the limit. Very simple, but a client can send the full limit at 10:00:59 and again at 10:01:00, getting double the rate across the boundary.

Sliding window log and sliding window counter

The log stores every request timestamp and counts those in the last 60 seconds: exact but memory-hungry. The sliding window counter approximates it with two fixed-window counts weighted by how far into the current window you are. It’s smooth, cheap and close enough for most uses.

Distributed rate limiting

With 20 gateway instances, each must see the same counts:

  • Central store: keep counters in Redis. Make the check-and-update atomic, using INCR with expiry for windows or a Lua script for token buckets, to avoid races between instances.
  • Local plus sync: each instance enforces a share of the limit locally and periodically syncs, trading accuracy for speed and resilience.
  • Sticky routing: hash clients to instances so each client’s limit lives in one place.

Decide what happens if Redis is down: fail open (allow traffic, keep the service usable) or fail closed (reject, safest for abuse-sensitive endpoints), usually with a coarse local limit as a backstop.

Where to enforce

  • At the edge (CDN, WAF, API gateway): stops abuse before it costs anything.
  • In services: for business rules (“3 password resets per hour”) and to protect specific resources.
  • Client side: well-behaved SDKs throttle themselves using the headers you return.

Responding to clients

Return HTTP 429 Too Many Requests with:

  • Retry-After: when to try again,
  • X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (or the newer standard RateLimit headers) so clients can pace themselves.

For internal callers, rate limiting combines naturally with load shedding (next lesson).

Recap

Rate limiting caps request rates per user, key, IP or endpoint to protect services and enforce plans. Token buckets allow controlled bursts; leaky buckets smooth output; sliding windows avoid fixed-window edge bursts. Share counters atomically in a store like Redis across instances, choose fail-open or fail-closed behaviour, and tell clients clearly with 429 and rate-limit headers.

Exercise

Limit the API

A public weather API has free and paid plans: free keys may make 60 requests per minute with short bursts allowed; paid keys 1,000 per minute. It runs on 20 gateway instances. (a) Which algorithm would you use and why? (b) Where are the counters stored, and how do you update them safely? (c) What does the API return when a client exceeds its limit? (d) What happens if the counter store (e.g. Redis) is unavailable?

Text
(a)
(b)
(c)
(d)

Summary

  • Rate limiting caps how many requests a client can make in a period, protecting services and enforcing fair use and plans.
  • Token bucket allows bursts up to the bucket size while enforcing an average refill rate; it's the most common choice.
  • Fixed windows are simple but allow double bursts at boundaries; sliding windows smooth this out.
  • Distributed limits need shared, atomic counters (for example Redis with a Lua script) or approximate local limits.
  • Return 429 with Retry-After and rate-limit headers, and decide whether to fail open or closed if the limiter breaks.