System Design: Designing a Rate Limiter
A practical walk through rate-limiter design: what you are actually protecting, token bucket versus sliding window, a Java sketch, and how to make it correct across many servers.
7 min read

Every public API eventually needs a rate limiter: the component that decides whether a caller has asked for too much, too fast. Get it wrong and you either let one client melt your backend or you throttle honest traffic and generate support tickets. Here is how to reason about the design, whether you are building one or being asked to design one in a system design interview.
Start with the goal, not the algorithm
A rate limiter protects three different things, and which one you care about shapes the design:
- Fairness so no single tenant starves the others.
- Cost control to cap calls to an expensive downstream or a metered third-party API.
- Abuse prevention to blunt credential-stuffing and scraping.
Decide the limit's dimension too: per API key, per IP, or per user. Most real systems layer several of these at once.
In an interview: pin down the requirements first
"Design a rate limiter" is one of the most common system design interview questions because it is small enough to finish in 45 minutes and still touches algorithms, distributed state and API design. Do not start with token buckets. Spend the first five minutes on questions like these:
- Where does it run? In an API gateway in front of every service, as middleware inside one service, or in a client SDK?
- What is the key? API key, user ID, IP address, or a combination such as user plus endpoint?
- What are the limits? For example 100 requests per minute per user, with short bursts allowed. Are there different tiers for free and paid plans?
- How exact must it be? Is letting 102 requests through instead of 100 under a race acceptable? Usually yes, and saying so simplifies the design.
- Scale and latency. How many requests per second in total, and how many milliseconds can the check add? The limiter sits on every request, so it must be fast.
- What happens on rejection? Reject with 429, queue the request, or degrade (serve a cached response)?
A quick estimate helps too. With 10 million active keys and a token bucket stored as two numbers per key, with per-key overhead that is roughly a gigabyte in Redis: one node, or a small cluster for headroom.
Pick an algorithm
Two designs cover the large majority of cases:
- Token bucket - a bucket refills at a steady rate up to a cap, and each request spends one token. It absorbs short bursts, which users love, while bounding the sustained rate. This is the sensible default.
- Sliding window - counts requests across a moving time window, which is more accurate at the boundary than a fixed window but costs more memory.
A fixed-window counter is the easiest to build but suffers the double-burst problem: a client can fire a full window of requests at 0:59 and again at 1:00.

The sliding window comes in two flavours. A sliding log stores a timestamp for every request (in Redis, a sorted set) and counts the ones inside the window: exact, but memory grows with traffic. A sliding window counter keeps only the current and previous fixed-window counts and estimates the rest: with a 60-second window, 15 seconds into the current minute, the estimate is current + previous × 45/60. It is cheap and close enough for most APIs.
You may also hear about the leaky bucket: requests join a queue that drains at a constant rate. It smooths traffic into a steady stream, which suits work sent to a slow downstream, but it adds queueing delay instead of answering immediately.
A token bucket, sketched
class TokenBucket {
private final long capacity;
private final double refillPerSecond;
private double tokens;
private long lastRefillNanos;
TokenBucket(long capacity, double refillPerSecond) {
this.capacity = capacity;
this.refillPerSecond = refillPerSecond;
this.tokens = capacity; // start full, so a new client can burst
this.lastRefillNanos = System.nanoTime();
}
synchronized boolean tryAcquire() {
refill();
if (tokens >= 1) {
tokens -= 1;
return true;
}
return false;
}
private void refill() {
long now = System.nanoTime();
double elapsed = (now - lastRefillNanos) / 1_000_000_000.0;
tokens = Math.min(capacity, tokens + elapsed * refillPerSecond);
lastRefillNanos = now;
}
}Make it work across many servers
The in-memory bucket above breaks the moment you run more than one instance: each replica keeps its own count, so a limit of 100/s quietly becomes 100/s per node. Move the state into a shared store, usually Redis, and make the check-and-decrement atomic so two concurrent requests cannot both spend the last token. A small Lua script that reads the counter, tests it, and writes it back runs atomically on the Redis server:
-- limiter.lua: a fixed-window counter. KEYS[1] = counter key, ARGV[1] = limit, ARGV[2] = window in seconds
local count = redis.call('INCR', KEYS[1])
if count == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
end
if count > tonumber(ARGV[1]) then
return 0
end
return 1# evaluate the limiter script: KEY, then limit and window-seconds as args
redis-cli --eval limiter.lua rate:key123 , 100 60A token bucket in Redis works the same way: store the token count and the last refill time in a hash, and do the refill, the check and the decrement inside one script. Give the keys an expiry, so idle clients do not fill memory.
Where the limiter lives
- API gateway or reverse proxy – one place for every service, and abusive traffic is dropped before it reaches your code. Most gateways (and NGINX's
limit_req) offer this out of the box. - Middleware in the service – a filter or interceptor that can use business context, such as the user's plan or the cost of the endpoint. In Spring Boot this is a servlet filter or a
HandlerInterceptor; libraries such as Bucket4j and Resilience4j provide the algorithms. - Both – a coarse per-IP limit at the edge to absorb floods, and a precise per-user limit in the service. This is the common answer for a real product.
Tell the client what happened
- Return 429 Too Many Requests when the limit is exceeded.
- Send a
Retry-Afterheader so well-behaved clients back off instead of hammering. - Expose
X-RateLimit-LimitandX-RateLimit-Remainingso callers can self-throttle before they hit the wall.
Finally, decide up front whether the limiter fails open or closed: if Redis is unreachable, do you drop the limit or reject traffic? Either can be right, but silence is not a decision.
Follow-up questions interviewers ask
- Two requests arrive at the same moment on different servers. How do you stop both spending the last token? Make the check-and-decrement atomic in the shared store (a Lua script or a single atomic command); never read, decide and write back from the application.
- Redis adds a network round trip to every request. Can you avoid it? Keep a small local allowance per node and sync with Redis in batches, accepting a slightly less exact limit. Or shard keys across Redis nodes placed close to the service.
- How do you limit across several data centres? Usually you do not share exact counts globally: give each region its share of the limit, or accept eventual consistency between regional counters.
- How do you change a limit without a deploy? Store limits per tier in configuration or a database, cache them in the limiter, and refresh them periodically.
- How would you test it? Unit-test the algorithm with an injected clock instead of
System.nanoTime(), then load-test the deployed limiter and check that the 429 rate matches the configured limit.
Go further
Rate limiting sits next to the other resilience patterns that microservices interviews ask about: circuit breakers, retries with backoff, timeouts and bulkheads. Our microservices interview questions guide covers them with 150+ questions and answers. Before you ship a service behind a limiter, run through the Spring Boot production checklist, and if you are preparing for interviews in general, start with the 30-day Java interview roadmap.
Run a rate limiter lab
Case 2 of System Design 2026: Classic + AI Era designs a distributed rate limiter across regions, and its Java lab runs a token bucket in Redis with a Lua script, so you can see why a read-then-write check lets too many requests through and a fixed window lets a burst slip past the window edge. The product page has a free 5-page sample.




