Ankit KanojiyaIntermediate

Evergreen guide by Ankit Kanojiya · Intermediate · System Design

Designing a Rate Limiter

How to design a rate limiter: token bucket, sliding window, where it sits in the stack, Redis atomicity, and the interview questions it comes up in.

Every API that is open to the internet eventually meets a client that calls it too often. Sometimes it is a bug in a retry loop, sometimes a scraper, sometimes a paying customer whose cron job fires 10,000 times at midnight. A rate limiter is the component that decides, per client and per time window, whether a request goes through or gets a 429 Too Many Requests.

"Design a rate limiter" is one of the most common system design questions because it is small enough to finish in 40 minutes and still touches the things interviewers care about: choosing an algorithm, keeping state in a distributed system, and handling the edge cases at scale.

What you are protecting

Before any algorithm, be clear about the goal. A rate limiter protects three things: your backend from overload, your other users from one noisy neighbour, and your business rules (a free tier gets 100 requests a minute, a paid tier gets 10,000). The interviewer wants to hear you ask which one matters most, because the answer changes the design. Overload protection can be approximate; billing tiers cannot.

Also settle what you count by. The usual keys are user ID for authenticated traffic, API key for developer platforms, and IP address for anonymous traffic. IP-based limits punish everyone behind a corporate NAT or a mobile carrier's gateway, so say that out loud when you pick it.

The algorithms

Fixed window counter

Divide time into windows (say, one minute). Keep a counter per key per window. Increment on each request; reject when it passes the limit. Reset at the window boundary.

It is a single integer per key, so it is cheap. The problem is the boundary. With a limit of 100 per minute, a client can send 100 requests at 11:59:59 and 100 more at 12:00:00: 200 requests in two seconds while never breaking the rule.

Sliding window log

Store the timestamp of every request per key. On a new request, drop timestamps older than the window and count what is left. This is exact, and it is also expensive: a key with a limit of 10,000 a minute stores 10,000 timestamps. Memory grows with the limit, which is the opposite of what you want for your biggest customers.

Sliding window counter

The compromise most production systems use. Keep counters for the current window and the previous one, and weight the previous one by how much of it still overlaps the sliding window.

If the limit is 100 per minute, the previous minute had 80 requests, the current minute has 30 so far, and we are 15 seconds into the current minute, the estimate is:

estimate = current + previous × (1 − elapsed/window)
         = 30 + 80 × (1 − 15/60)
         = 30 + 60
         = 90

90 is under 100, so the request is allowed. The estimate assumes the previous window's requests were spread evenly, which is not always true, but the error is small and it costs two integers per key.

Token bucket

Each key has a bucket that holds up to capacity tokens and refills at rate tokens per second. A request takes one token; if the bucket is empty, the request is rejected. The bucket lets a client burst up to capacity requests at once, then settle to rate per second on average.

This is the algorithm behind most cloud provider API limits because the burst allowance matches how real clients behave: idle, then a flurry. You do not need a background thread to refill. Store the token count and the last-refill timestamp, and compute the refill lazily when the next request arrives.

Leaky bucket

Requests enter a queue of fixed size and leave at a constant rate. It smooths bursts into a steady stream, which is useful when the thing downstream cannot handle bursts at all. The cost is latency: a request may sit in the queue. For public APIs, token bucket is the usual pick; leaky bucket shows up in front of things like payment processors.

A worked example: token bucket in Redis

Here is the shape of a token bucket check for a single key, written so that the read-modify-write happens atomically on the Redis server. Without atomicity, two app servers can both read "1 token left" and both allow the request.

-- KEYS[1] = bucket key
-- ARGV[1] = capacity, ARGV[2] = refill rate per second, ARGV[3] = now (seconds)
local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens') or ARGV[1])
local last   = tonumber(redis.call('HGET', KEYS[1], 'last') or ARGV[3])
local now    = tonumber(ARGV[3])

local refill = (now - last) * tonumber(ARGV[2])
tokens = math.min(tonumber(ARGV[1]), tokens + refill)

local allowed = 0
if tokens >= 1 then
  tokens = tokens - 1
  allowed = 1
end

redis.call('HSET', KEYS[1], 'tokens', tokens, 'last', now)
redis.call('EXPIRE', KEYS[1], 60)
return allowed

The script runs as one unit, so concurrent requests from different servers are serialised by Redis. The EXPIRE keeps idle keys from living forever. In an interview you do not need to write the Lua; you need to say "the check and the decrement must be atomic, so I would use a Lua script or MULTI/EXEC", and explain why.

Where the limiter sits

Three places, in order of how often they come up:

At the API gateway or reverse proxy. Nginx, Envoy and the cloud gateways all have rate limiting built in. Requests get rejected before they touch your application servers, which is the whole point. This is the default answer.

As middleware in the application. Useful when the limit depends on something only the app knows, such as the user's plan after a database lookup. Costs you an app server's time on every rejected request.

At the client, via SDKs that read the X-RateLimit-Remaining and Retry-After headers and back off. Never rely on this alone; it is a courtesy, not a control.

The distributed problem

One server with an in-memory counter is easy. The question gets interesting when you have 50 API servers behind a load balancer, because each server only sees its share of the traffic.

The standard answer is a shared store, almost always Redis, with the atomic script above. That introduces a network hop on every request and a dependency: if Redis is down, do you fail open (allow everything) or fail closed (reject everything)? Most teams fail open for overload protection and fail closed for billing, and the interviewer will ask.

If one Redis is a bottleneck, shard by key so that each client's counter lives on one node. Clustered Redis does this for you. Do not try to split one client's counter across nodes; you lose atomicity and the estimate drifts.

The response matters as much as the decision. Return 429 with a Retry-After header saying how long to wait, plus X-RateLimit-Limit and X-RateLimit-Remaining so well-behaved clients can pace themselves. A limiter that rejects silently just produces retries.

Questions interviewers ask

Why token bucket over fixed window? Bursts. Fixed window either blocks a legitimate burst or allows double the limit at the boundary.

How do you make the counter atomic across servers? Lua script in Redis, or INCR with EXPIRE for the simple fixed-window case. INCR is atomic on its own.

What happens when Redis goes down? Fail open or fail closed, and why. Mention a local fallback: each server keeps an in-memory limiter at 1/N of the global limit as a crude safety net.

How do you limit by multiple dimensions at once? Run checks against more than one key (per user and per IP and per endpoint) and reject if any fails. Keep the number small; each is a Redis call.

How do you handle a limit that varies by plan? Look up the plan once, cache it with the session or in the JWT, and pass the capacity and rate as arguments to the script.

What about clock skew between servers? Use Redis's TIME command inside the script instead of trusting each app server's clock.

Go deeper

Stripe's engineering blog post on how they scaled rate limiting is the most-cited real-world write-up and covers the layered approach (request limiter, concurrency limiter, load shedder).

The IETF draft "RateLimit header fields for HTTP" standardises the response headers.

Redis's documentation on Lua scripting explains the atomicity guarantee the example relies on.

Chapter 4 of Alex Xu's System Design Interview covers this exact question with diagrams, and it is the version most interviewers have read.