Why you need it
Most callers are polite, but one buggy script or one attacker can send thousands of requests a second and use up every server, so everyone else waits. A rate limit caps how much any one caller may ask for, so one greedy caller cannot starve the rest.
Think of it like this
A shop's sale with a sign: "limit 3 per customer". One person cannot empty the shelf, so there is something left for everyone else.
Where you’ll find it
- GitHub: Lets each signed-in user make 5,000 API calls an hour, and says how many are left in every answer.
- Stripe: Puts several limiters in front of its payments API, and explains each one openly.
- Cloudflare and NGINX: Both offer it ready-made: Cloudflare rate limiting rules and NGINX's limit_req.
What to know first
Caller. Whoever is sending requests, told apart by a key: a user ID, an API key, or an IP address.
429. The standard answer for "too many requests, slow down". Polite clients wait and try again.
How it works
- Choose who to count. Count per user or per API key when callers sign in. Fall back to IP address when they do not, knowing that many people can share one IP.
- Fixed window: a count per second. Allow 3 requests in each second, and reset the count when the next second starts. This is the animation's boxes. Simple, but a caller can squeeze 6 requests around the moment the count resets.
- Token bucket: allow short bursts. Each caller has a bucket that refills with tokens at a steady speed, say one every 0.3 seconds, up to a small maximum. Each request spends one token; no token, no request. This lets a short burst through but holds the average down.
- Say no clearly. Answer
429 Too Many Requestswith aRetry-Afterheader saying when to come back. Good clients wait, and backing off is covered in Retries with backoff and jitter. - Count in one shared place. With many servers behind a Load balancing balancer, each server sees only part of a caller's traffic. Keep the counts in a fast shared store like Redis, or in the gateway at the front (see Reverse proxy and API gateway).
An example
An API allows each key 100 requests a minute. Thousands of normal apps use about 10 each.
One app ships a bug that loops forever and sends 10,000 a minute.
Without a limit, the servers drown and every app slows down. With it, 100 of those requests a minute get through, the other 9,900 get a 429 at almost no cost, and every other app carries on as normal.
Further reading
- Scaling your API with rate limiters, Paul Tarjan, Stripe. The four limiters Stripe runs, and why each one exists. Start with this one.
- How we built rate limiting capable of scaling to millions of domains, Cloudflare blog. A clever way to count fairly with very little memory.
- Rate limits for the REST API, GitHub docs. What a well-documented limit looks like from the caller's side.