Limit requests per client
One client (or a bot) floods the API and degrades it for everyone.
Say it like this
I need a per-client cap that is accurate across the fleet, so I count in Redis with a token bucket in one atomic Lua script and return 429 with Retry-After when the bucket is empty.
Basic solution
Count requests per key in a shared store with a token bucket or sliding window; return 429 with Retry-After when exceeded.
One atomic check per request
Every request costs one Redis script call that refills, checks and decrements the bucket in a single step. Denied requests never reach the backend.
How it works
- The gateway derives the limit key from the request: the api_key, the user_id, or the client IP, combined with the rule that applies (say, 100 requests per minute). That key is the bucket's name in Redis.
- It runs one atomic script against Redis that does three things in a row on the Redis thread: load the bucket's token count and last refill time, add tokens for the time elapsed since then up to the bucket's capacity, and then, if at least one token is present, subtract one and return "allow", otherwise return "deny".
- The script sets an EXPIRE on the key, so a client that goes idle costs no memory once a window has passed.
- On allow, the gateway forwards the request to the backend and adds X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset headers so the client can pace itself.
- On deny it returns 429 with a Retry-After header computed from the refill rate (how long until one token exists), and emits a rejection event so metrics can show who is being limited.
Why the script must be atomic
- If two gateways each read the same count and both decide to allow, the limit is exceeded by one; that is the classic race. One Lua script runs read, compute and write as a single step on the Redis thread, so no other command can slip in between.
Worked example
Public API, 100 requests per minute per API key
- Token bucket: capacity 100, refill rate 100 / 60 = 1.67 tokens per second. A client that spends tokens faster than they refill is slowed to exactly 100 per minute.
- A client idle for 30 s has 50 tokens; a burst of 50 requests passes, the 51st is denied until 0.6 s later when the next token has dripped in. That burst allowance is what distinguishes a token bucket from a plain counter.
- 50K API keys active per minute × 1 Redis call per request at 20K req/s total: one Redis node handles ~100K ops/s, so one shard suffices with a replica for failover. The limiter is not a scaling problem until the API is five times bigger.
- Memory: 50K keys × ~100 B ≈ 5 MB. Negligible.
- Added latency: one in-region round trip, ~0.5 ms per request. If the gateway and Redis are in different zones, budget 1–2 ms.
Variants and when each wins
Token bucket
- Tokens drip into a bucket at the refill rate and each request spends one, so a client can burst up to the capacity and is then held to the steady rate. It stores two numbers per key and is the default for public APIs where short bursts are fine.
Fixed window counter
- One counter per key per minute, incremented with INCR and expired with EXPIRE. It wins on simplicity, but a client can send the full limit at the end of one minute and again at the start of the next, 2× the limit in a few seconds.
Sliding window log
- Every request timestamp is stored in a sorted set, and the limiter counts the entries inside the trailing window. It is exact, so it wins for small strict limits such as 5 login attempts per minute; memory grows with the limit, so it is wrong for 10K per minute.
Sliding window counter
- Keep the current and previous window counts and weight the previous one by how much of it still overlaps the trailing window. It smooths the fixed-window edge burst at the cost of being approximate, and wins when smoothness matters more than allowing bursts.
Local per-server limits
- Each server counts in memory, with the limit divided by the number of servers. It wins only when a round trip per request is unaffordable, because uneven load balancing makes it inaccurate.
Use a token bucket in Redis by default; sliding window counter when smoothness matters more than bursts; local limits only when a round trip per request is unaffordable.
Failure modes
Redis unavailable
- Every request waits on a Redis timeout before anything else happens. It happens because the limiter sits on the critical path of every request. Fix it with a circuit breaker: after a few failures stop calling Redis, fail open for ordinary endpoints using a per-server local bucket as a fallback, and fail closed for login and payment endpoints where unlimited calls are dangerous.
Race between INCR and EXPIRE
- Counters that never expire, or counts that double. It happens because INCR and EXPIRE are two separate commands, and a crash or a second client between them leaves the key in a half-set state. Fix it by doing both in one Lua script, or with a single SET command using the NX and EX options.
Hot limit key
- One tenant sending 50K requests per second saturates the one Redis shard that owns its key. It happens because every request for that key is one Redis call to one node. Fix it by counting locally on each gateway and flushing the total with INCRBY every 100 ms, accepting a small overshoot in exchange for a 100× drop in Redis calls.
Thundering herd at window reset
- Every blocked client retries at the same second and the spike repeats. It happens because fixed windows reset at the same instant for everyone and the Retry-After value is identical for all. Fix it with a token bucket, whose refills are continuous, plus random jitter added to Retry-After.
Wrong key choice
- A shared office IP is blocked for everyone behind it, or one user with many API keys bypasses the limit entirely. It happens because the limit is keyed on one dimension only. Fix it by limiting on more than one dimension, user and IP, and denying if either limit is hit.
Interviewer follow-ups
Answer out loud before you open each one.
Walk through the token bucket maths for 100 requests per minute.
Capacity 100 tokens, refill 1.667 per second. On each request compute tokens = min(100, tokens + (now − last) × 1.667). If tokens ≥ 1, subtract one and allow; otherwise deny and Retry-After = (1 − tokens) / 1.667 seconds. Store tokens and last as two fields, updated atomically.
Fail open or fail closed when Redis is down?
Fail open for most endpoints because an outage of the limiter should not become an outage of the API, backed by a per-server local bucket so abuse is still bounded. Fail closed for endpoints where unlimited calls are dangerous, such as login, OTP and payments.
How do you rate limit by user and by IP at once?
Run two checks with separate keys and rules, and deny if either denies. Order them so the cheap, broad one (IP) runs first. Return the headers for the rule that is closest to its limit so clients can back off correctly.
Where should the limiter live?
In the API gateway or an edge middleware so every service gets it for free and the rules are in one place. Services add their own finer-grained limits only for genuinely service-specific rules, such as per-conversation message rates.
Connections
- In study paths
- Staying up under load
- Built on
- Ring buffer · Count-Min sketch
- Pairs with
- Do read-modify-write atomically · One front door for many services · Decide what happens when a guard is down · Drop load before you fall over
- Pulls against
- Keep servers stateless
- Used in
- Distributed Rate Limiter
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon API Gateway | API gateway | API Gateway, Apigee | API Management | Kong, Tyk |
| Amazon ElastiCache | Redis | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon EC2 Auto Scaling | Backend | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |