Quick revision
The short answer
A fixed window counter is one counter per client per minute: cheap, but a client can send 100 requests at the end of one minute and 100 at the start of the next, 200 in two seconds. A sliding window log keeps every timestamp in a sorted set per client, which is exact but costs memory per request. A sliding window counter keeps the current and previous minute's counts and weights the previous one by how much it still overlaps the window, which is approximate but needs only two counters. With Redis behind many gateway instances, I would use the sliding window counter (or a token bucket if controlled bursts are wanted) in a Lua script, so check and increment happen as one atomic step.
What to remember
In this answer, we compared three algorithms for 100 requests per minute per client. The fixed window counter is cheap but allows up to 200 requests across a boundary. The sliding window log is exact but stores every timestamp in a sorted set. The sliding window counter weights the previous minute by its overlap and needs only two counters, with small approximation error. The token bucket is a good alternative when controlled bursts are wanted. Across many gateways we keep the state in Redis and use a Lua script so the check and increment are atomic, with hash tags for Redis Cluster and a fail-open policy when Redis is down.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A fixed window counter is one counter per client per minute: cheap, but a client can send 100 requests at the end of one minute and 100 at the start of the next, 200 in two seconds. A sliding window log keeps every timestamp in a sorted set per client, which is exact but costs memory per request. A sliding window counter keeps the current and previous minute's counts and weights the previous one by how much it still overlaps the window, which is approximate but needs only two counters. With Redis behind many gateway instances, I would use the sliding window counter (or a token bucket if controlled bursts are wanted) in a Lua script, so check and increment happen as one atomic step.
Why this question is asked
Rate limiting protects services from abusive clients, runaway retry loops and plain overload, and it is part of the product too, since API plans are often defined by their limits. A limit enforced by many gateway instances has to share state, which brings in Redis, network round trips and race conditions. Interviewers ask this to see whether we know the algorithms, their exact failure cases and their costs, and whether we can make them correct in a distributed setting. In this answer, we will recap the requirement, walk through the fixed window, the sliding log and the sliding counter with their trade-offs, mention the token bucket, and then make the chosen algorithm atomic in Redis.
1The Requirement and Why State Must Be Shared
The rule is 100 requests per minute per client. If we had a single gateway, an in-memory map from client id to state would do. With, say, 20 gateway instances behind a load balancer, each instance sees only part of a client's traffic. Per-instance limits of 5 per minute would be unfair and inaccurate, because traffic is not spread evenly. So the state lives in a shared store, usually Redis, and every request costs at least one round trip to it, about 0.2 to 1 millisecond inside a data centre. That latency, and Redis's memory, are the main costs we trade against accuracy.
2Fixed Window Counter
The simplest algorithm divides time into fixed minutes and keeps one counter per client per minute, with a key like rl:client42:28734512 where the number is the epoch minute. Each request increments the counter and is rejected if the result exceeds 100. The key expires after the minute, so memory is one small counter per active client.
The flaw is at the boundaries. A client sends 100 requests at 12:00:59 and 100 more at 12:01:00. Each window sees only 100, so all 200 are allowed, within about one second. In the worst case, a fixed window allows twice the limit in a short burst across a boundary, which may be exactly the overload the limiter was meant to prevent.
| Time | Window | Count in window | Allowed? |
|---|---|---|---|
| 12:00:59.0 | 12:00 | 1 to 100 | yes |
| 12:01:00.0 | 12:01 | 1 to 100 | yes |
| last 60 seconds at 12:01:00.5 | real sliding minute | 200 | should have been 100 |
3Sliding Window Log
The exact algorithm keeps a log of the timestamps of each client's requests in the last minute. In Redis that is a sorted set per client, with the timestamp as the score. For each request we remove entries older than now - 60 seconds with ZREMRANGEBYSCORE, count the rest with ZCARD, and add the new timestamp with ZADD if the count is below 100. The limit then holds for every 60 second interval, not just aligned minutes.
The cost is memory and work proportional to traffic. Each sorted set entry costs tens of bytes, and a client at its limit has 100 of them. For 1 million active clients with a limit of 100, that can reach several gigabytes. For low limits it is fine; for limits like 10,000 per minute, it becomes expensive.
4Sliding Window Counter
The sliding window counter approximates the log with only two numbers. We keep fixed window counters for the current minute and the previous minute. When a request arrives 15 seconds into the current minute, the real sliding window covers the last 45 seconds of the previous minute and the first 15 of the current one. Assuming the previous minute's requests were spread evenly, the estimate is previous x 45/60 + current.
It removes the boundary burst of the fixed window, because requests at 12:00:59 still count heavily at 12:01:00. It is approximate, because real traffic in the previous minute was not even. Cloudflare has described using this method at large scale and finding the error very small in practice. Memory is two counters per client, the same order as the fixed window.
5Token Bucket as Another Choice
A token bucket holds up to a maximum number of tokens, for example 100, and refills at a steady rate, 100 per minute, about 1.67 per second. Each request takes one token and is rejected when the bucket is empty. It allows controlled bursts up to the bucket size and then a steady rate, which matches how many APIs want to behave. It needs only two values per client, the token count and the last refill time, and the refill can be computed lazily on each request. Libraries such as Bucket4j implement it with Redis and other back ends.
| Algorithm | Accuracy | State per client |
|---|---|---|
| Fixed window counter | allows up to 2x at boundaries | 1 counter |
| Sliding window log | exact | 1 entry per request in the window |
| Sliding window counter | approximate, no boundary burst | 2 counters |
| Token bucket | exact rate, bursts up to capacity | tokens + last refill time |
6Making It Atomic in Redis
With many gateway instances, read then write from Java is a race: two instances both read 99, both decide to allow, both increment, and the client gets 101. The check and the increment must be one atomic step. A Redis Lua script runs atomically on the server, so the whole decision happens in one round trip with no interleaving.
We pass the elapsed fraction from the gateway, or better, read the time inside the script with redis.call('TIME') so that gateway clock differences do not matter. In Redis Cluster, both keys must share a hash slot, which we ensure with a hash tag such as rl:{client42}:28734512. We also decide what happens when Redis is unavailable: usually fail open with a local per-instance limit for a short time, because rejecting all traffic is worse. Finally, we accept small inaccuracy for latency: a local cache that allows a few extra requests between syncs is a reasonable trade at very high volume, as long as we can explain the bound.
7Follow-up questions
Why not use Redis INCR and EXPIRE without a script for the fixed window?
INCR is atomic on its own, so the fixed window works with INCR followed by EXPIRE on the first increment. The risk is a crash between the two leaving a key without expiry; using a script, or SET with NX and EX before INCR, avoids that. The sliding counter reads two keys, so it needs a script to stay atomic.
What should the gateway return when a client is limited?
HTTP 429 Too Many Requests with a Retry-After header, and ideally headers that show the limit and remaining requests, so well-behaved clients can slow down. The response should be cheap to produce, since limited clients often retry quickly.
How would you rate limit by plan, not a fixed 100?
The limit becomes a per-client value looked up from the plan, cached in the gateway, and passed into the script as an argument. The algorithm does not change.
8Conclusion
In this answer, we compared three algorithms for 100 requests per minute per client. The fixed window counter is cheap but allows up to 200 requests across a boundary. The sliding window log is exact but stores every timestamp in a sorted set. The sliding window counter weights the previous minute by its overlap and needs only two counters, with small approximation error. The token bucket is a good alternative when controlled bursts are wanted. Across many gateways we keep the state in Redis and use a Lua script so the check and increment are atomic, with hash tags for Redis Cluster and a fail-open policy when Redis is down.
Open with
I would compare them on accuracy and cost. A fixed window counter keeps one counter per client per minute, which is cheap, but a client can send 100 requests at the end of one minute and 100 at the start of the next, so it allows up to 200 in about a second.
Then, if they want more
A sliding window log stores every request timestamp in a Redis sorted set per client and trims entries older than a minute, which is exact but stores up to a hundred entries per client, so memory grows with traffic.
A sliding window counter keeps the current and previous minute counts and estimates the sliding window as previous times the fraction of the previous minute still in the window, plus current. It needs two counters, removes the boundary burst, and its error is small in practice.
A token bucket is the other common option if we want to allow controlled bursts. For many gateway instances I would use the sliding window counter in Redis, and make the decision atomic with a Lua script that reads both counters, compares with the limit and increments, so two gateways cannot both allow the hundred and first request.
I would read time inside Redis, keep both keys in one hash slot with a hash tag, return 429 with Retry-After, and fail open with a local limit if Redis is down, accepting small inaccuracy to keep latency low.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "An API gateway must enforce 100 requests per minute per client. Compare a fixed window...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/37de0bc0e9/