Rate Limiting

A control that caps how many requests a client may make in a given window, protecting a service from overload, runaway clients and abuse.

Definition#

Rate limiting caps how much work a single client can ask of a service over a period of time — typically requests per second, per minute or per day, counted per API key, per user or per IP address. Requests over the cap are rejected rather than queued, so the service protects its own latency for everyone else.

The convention for HTTP is to reject with status 429 Too Many Requests and a Retry-After header saying how long to wait. Well-behaved clients also read RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset so they can slow down before being rejected at all.

Why it matters#

Without a limit, one client's retry loop can consume the capacity of every other client — a failure that looks like an outage but is really an unfair queue. Rate limiting converts an unbounded, shared risk into a bounded, per-client one: the noisy client gets 429s while everyone else keeps their normal latency. It also puts a ceiling on the cost of scraping and credential-stuffing, and gives you a contractual unit to sell against in API pricing tiers.

How it works#

Every algorithm answers the same two questions: what identifies the client, and what counter does a request consume. The identifier should be as specific as you can make it — an API key beats a user id, which beats an IP address, since many users share an IP behind a corporate NAT or mobile carrier.

Common algorithms#

AlgorithmHow it counts
Fixed windowCounts requests per clock interval; simple, but allows a double burst across a window boundary
Sliding window logKeeps a timestamp per request for exact limits, at the highest memory cost
Sliding window counterWeights the previous window's count to approximate a sliding limit cheaply
Token bucketTokens refill at a steady rate up to a cap, so short bursts are allowed and sustained rates are not
Leaky bucketDrains a queue at a fixed rate, smoothing bursts into a constant outflow

Token bucket is the usual default for public APIs: it expresses "100 requests per minute, bursts of 20" in two numbers a client can actually reason about.

Design patterns#

Common pitfalls#

  • Limiting by IP address alone, which throttles a whole office behind one NAT while barely inconveniencing a distributed scraper.
  • Fixed windows at round clock times, letting a client send a full window's worth on either side of the boundary — twice the intended rate.
  • Returning 503 instead of 429, so clients treat a deliberate limit as a server fault and retry harder.
  • Counting rejected requests against the limit's own store without a cheap path, so an attack makes the limiter the bottleneck.
  • Applying one global number to every endpoint, which is either too loose for expensive calls or too tight for cheap ones.