Rate Limiter Design
Token bucket, leaky bucket, fixed window, sliding log and sliding counter as code you can trace, plus how to make one limit hold across many servers.
Overview
A rate limiter decides, for each request, whether a client has used up its allowance for a period of time. It protects a service from overload and abuse, and it is how an API sells tiers. HTTP has a status code for the refusal, 429 Too Many Requests (RFC 6585), with an optional Retry-After header.
The interview has two halves. The first is the algorithm: what state you keep per client, how much memory that is, and how the limiter behaves at the edges of a window. The second is the deployment: a limit that must hold across many API servers needs a shared counter, and a shared counter needs an atomic update. This topic builds each algorithm as a few lines of Python with a trace you can check, then moves the state into Redis.
Five algorithms
Five algorithms cover nearly every rate limiter, and they differ in three ways: the state they keep per client, how they treat a burst, and how exact they are.
- Fixed window: one counter and a window number. Around a window edge a client can get twice the limit through, so the count is rough. It suits simple in-process limits.
- Sliding log: a timestamp per request. Nothing gets past the limit, so it is exact. It suits low limits, where the memory is fine.
- Sliding counter: two counters. It can overshoot a little near the edge, but it is close: Cloudflare reports 0.003% of 400 million requests wrongly allowed or blocked. Cloudflare's rate limiting uses it.
- Token bucket: a token count and the last refill time. Bursts pass up to the bucket size, then the refill rate takes over, and it is exact for its own rule. Stripe (with buckets in Redis), Envoy's local rate limit and AWS API Gateway use it.
- Leaky bucket: a queue, or a level and a drain time. Bursts are absorbed into a queue and drained at a fixed rate, and it is exact. Nginx limit_req works this way.
The token bucket is the one most APIs reach for, so it comes first.
Interview questions
- Compare token bucket, leaky bucket, fixed window and sliding window rate limiting.
- Implement a distributed rate limiter using Redis.
- How do you make an in-process limiter safe for many threads and many clients?
- How do you handle rate limiting across multiple data centers?
- What should the API return when a client is limited?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio