Step 1: clarify requirements
These are the questions worth asking up front, with reasonable assumptions for each:
- What are we limiting, and by what key? Per user, per API key, per IP, per endpoint? Assume per API key, with different limits for different plans, plus a coarser per-IP limit for unauthenticated traffic.
- Where does it run? As a library inside each service, or as a shared layer in front of them? Assume a shared layer in the API gateway, so every service is protected the same way.
- How strict? Can a few extra requests slip through at the edges, or must the limit be exact? Assume approximate is fine — the goal is protecting the backend and enforcing fair use, not billing.
- What happens to rejected requests? Assume HTTP 429 Too Many Requests with a
Retry-Afterheader, plus headers telling clients how much quota they have left. - What scale? Assume 50 million daily active clients and a peak of about 500,000 requests per second across the fleet.
The non-functional requirements: the limiter adds very little latency (a few milliseconds at most), it's highly available, and if it fails, it shouldn't take the API down with it.
Step 2: estimate scale
- Checks: 500,000 per second at peak, each one a read-and-update of a counter.
- Memory: if about 10 million clients are active in a given hour and each needs a small counter, then at roughly 100 bytes per key including overhead, that's on the order of 1 GB — easily held in memory.
- Throughput: a single Redis instance handles on the order of 100,000 simple operations per second, so 500,000 checks per second needs a cluster of several shards, partitioned by client key.
These numbers settle the main design choice: counters live in a fast, shared, in-memory store, sharded by key. (The estimation cheat sheet has the numbers behind this kind of arithmetic.)
Step 3: choose an algorithm
This is the heart of the question. Name the common algorithms, then pick one and give a reason.
| Algorithm | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Token bucket | A bucket holds up to N tokens and refills at a steady rate. Each request takes a token; no token, no request. | Allows short bursts up to N while enforcing an average rate. Tiny state: a token count and a timestamp. | Two parameters to tune. Bursts can still hurt a fragile backend. |
| Leaky bucket | Requests join a queue that drains at a fixed rate; overflow is rejected. | Perfectly smooth output rate. | Bursts wait in the queue, adding latency; new requests can starve behind old ones. |
| Fixed window counter | Count requests per fixed window, such as per minute, and reset at the boundary. | Simplest option: one counter per key. | Bursts at boundaries: up to twice the limit across the edge of two windows. |
| Sliding window log | Store a timestamp for every request and count those inside the last window. | Exact. | Memory grows with the limit — one entry per request. |
| Sliding window counter | Weight the previous window's count by how much of it still overlaps the sliding window. | Close to exact, smooths boundary bursts, only two counters per key. | An approximation that assumes the previous window's requests were evenly spread. |
The fixed window problem, concretely. With a limit of 100 per minute, a client can send 100 requests at 12:00:59 and another 100 at 12:01:00 — 200 requests in two seconds, all allowed.
The sliding window counter, concretely. Say the previous one-minute window had 80 requests, the current window has 30 so far, and we're 25% of the way into the current window. The estimated count is 30 + 80 × 0.75 = 90. Under a limit of 100, the request is allowed.
A reasonable choice: token bucket for most APIs, because it tolerates the short bursts real clients produce — a single page load can fire several calls at once — while still enforcing the average rate. Sliding window counter is an equally defensible choice if you want to avoid bursts altogether. Either way, saying why is what earns the credit.
Step 4: the design
client ──> API gateway ──> rate limit check ──> backend service
│
├──> Redis cluster (counters, sharded by key)
└──> rules config (limits per plan/endpoint)
- A request reaches the gateway, which extracts the key — the API key, or the IP address for unauthenticated traffic.
- The gateway looks up the limit for that key's plan and endpoint in a rules configuration, cached in memory and refreshed periodically.
- It runs an atomic check-and-update against the client's counter in Redis.
- If the request is allowed, it goes through with quota headers attached. If not, the gateway returns 429 with
Retry-After.
Making the check atomic
The naive version — read the count, compare it with the limit, write the new count — has a race. Two concurrent requests both read 99, both decide they're under a limit of 100, and both write 100. Under load, clients exceed their limits.
The fix is to make the read and the update one atomic operation. In Redis, the usual way is a Lua script, which runs atomically on the server. Here's a token bucket as a script:
-- KEYS[1] = the client's bucket key
-- ARGV = capacity, refill rate (tokens per second), current time (seconds), cost
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local bucket = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(bucket[1]) or capacity
local ts = tonumber(bucket[2]) or now
-- refill for the time elapsed since the last request, up to capacity
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call("HSET", KEYS[1], "tokens", tokens, "ts", now)
-- let idle buckets expire once they would have refilled completely
redis.call("EXPIRE", KEYS[1], math.ceil(capacity / rate) * 2)
return allowed
That's one round trip, no race, and keys clean themselves up once a client goes idle. For a fixed window, an INCR plus setting an expiry on first use is enough — but those two commands need to be atomic too (in a script or a transaction), or a crash between them can leave a counter that never expires.
One subtlety worth mentioning: the current time here comes from the gateway, and different gateway hosts have slightly different clocks. Reading the time inside the script with Redis's TIME command avoids that skew.
Scaling the counters
- Shard by key. Partition counters across the Redis cluster by client key, so each client's counter lives on exactly one shard and each check is a single round trip.
- Handle hot keys. One very heavy client concentrates load on one shard. For the largest clients, split the limit across several sub-keys — say ten buckets, each with a tenth of the limit, picked at random per request — trading a little accuracy for spread.
- Decide on multiple regions. A single global Redis adds cross-region latency to every request. The usual compromise is a limiter per region, with each region given a share of the global limit, or regional counters that sync asynchronously — accepting that a client spreading traffic across regions can briefly exceed its limit.
- Add a local pre-check if needed. At very high traffic, gateways can keep a small in-memory counter and only consult Redis periodically or near the limit, cutting Redis load at the cost of precision.
Step 5: trade-offs and failure modes
Fail open or fail closed? If Redis is unreachable, the gateway can either allow every request (fail open) or reject them (fail closed). For most APIs, fail open is the right default: a limiter outage shouldn't become an API outage. Pair it with a coarse local limit on each gateway host so a total failure doesn't leave the backend completely unprotected. For limits that guard against abuse or direct cost — login attempts, sending SMS — failing closed may be the better call. Say this out loud; it's the trade-off interviewers most want to hear.
Accuracy versus latency. An exact global limit needs a synchronous check against shared state on every request. Local counters and regional splits are faster and more available but allow some overshoot. Since the requirement was approximate limits, lean toward speed and availability.
Where to enforce. At the gateway, every service is protected and limits are consistent — but the gateway sees requests, not their cost. Expensive endpoints may need their own lower limits, or limits based on cost, where a heavy request consumes several tokens instead of one.
Client experience. Return 429 with Retry-After and remaining-quota headers so well-behaved clients can back off. Silently dropping requests or returning generic 500 errors makes clients retry harder, which makes overload worse.
What a strong answer covers
- Clarifies the key, the scope, how strict the limit is, and what rejected clients see.
- Compares at least three algorithms and picks one with a reason tied to the requirements.
- Spots the read-modify-write race and fixes it atomically.
- Shards the counters and addresses hot keys and multiple regions.
- Explicitly chooses fail open or fail closed, and explains why.
