Quick revision
The short answer
We keep one token bucket per API key and endpoint in a Redis cluster and update it with a Lua script, so the read, refill and decrement happen as one atomic step. A small Java client library, used by the gateway and the 40 services, calls Redis with a timeout of a few milliseconds and a defined fail-open or fail-closed rule. Hot keys get local token batches to save round trips, limits come from cached configuration that reloads without a restart, and metrics show rejections per key and Redis latency.
What to remember
In this answer, we designed a distributed rate limiter around a token bucket per API key and endpoint. Its state lives in a Redis cluster and is updated by a Lua script, so concurrent instances cannot race. A shared Java library calls it with a short timeout and a per-endpoint fail-open or fail-closed rule, hot keys use local pre-checks or token batches at a small cost in accuracy, limits come from cached configuration that reloads on change, and metrics on rejections and Redis latency tell us whether the limiter is protecting anything.
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.
We keep one token bucket per API key and endpoint in a Redis cluster and update it with a Lua script, so the read, refill and decrement happen as one atomic step. A small Java client library, used by the gateway and the 40 services, calls Redis with a timeout of a few milliseconds and a defined fail-open or fail-closed rule. Hot keys get local token batches to save round trips, limits come from cached configuration that reloads without a restart, and metrics show rejections per key and Redis latency.
Why this question is asked
A rate limiter sits in front of almost every request, so its design decides two things at once: whether one noisy client can hurt everyone else, and how much latency every caller pays for that protection. At 200,000 checks per second, small choices such as one extra network round trip or a race between two instances become visible. Interviewers ask it to see whether we can combine an algorithm, a shared store, failure handling and operations. In this answer, we will recap the token bucket, put its state in Redis with an atomic script, shard it, build the Java client with clear failure behaviour, reduce Redis traffic for hot keys, keep limits in configuration, and decide what to measure.
1A Quick Recap of the Token Bucket
A rate limiter answers one question per request: may this caller do this now? The token bucket is the most common way to answer it. Picture a bucket that holds up to a fixed number of tokens, its capacity, and that is refilled at a steady rate. Each request takes one token. If a token is there, the request goes through; if the bucket is empty, the request is rejected with HTTP 429 Too Many Requests.
The two numbers map directly to business rules. A limit of 100 requests per second with bursts up to 200 means a refill rate of 100 tokens per second and a capacity of 200. A client that was quiet for two seconds can send 200 requests at once, but over time it cannot exceed 100 per second.
Our limits are per API key and per endpoint, so the bucket is identified by both. A key such as rl:k_8f3a:POST/orders names the bucket for API key k_8f3a calling POST /orders.
2Keeping the Bucket in Redis With an Atomic Lua Script
The gateway and the 40 services run many instances, so the bucket cannot live in one process's memory. Redis is a good home: it is in memory, it answers in well under a millisecond inside a data centre, and every instance can reach it.
But there is a catch. If the client reads the token count, decides in Java, and then writes the new count, two instances can read the same value of 1 at the same moment, both allow their request, and both write 0. The limit is broken by a race. The fix is to do the whole read, refill and decrement inside Redis, in a Lua script. Redis runs a script to the end before it serves any other command on that node, so the script is atomic.
5 messages in order. Play them, or step through them one at a time.
The whole decision is one round trip; nothing can run between the read and the write.
Notice that the script uses the Redis clock rather than a timestamp sent by the caller. With 40 services on many hosts, clocks drift by a few milliseconds, and a caller with a clock running ahead would get extra tokens.
3Sharding the Keys Across a Redis Cluster
A single Redis node runs a short script like this tens of thousands of times per second, depending on hardware. For 200,000 checks per second with room to grow, we use Redis Cluster with, for example, six primaries and a replica each. Redis Cluster splits the key space into 16,384 hash slots by hashing the key, so buckets spread across the primaries without any work from us.
Memory stays small if the keys are small. A bucket is a hash with two fields, about 100 bytes with overhead. The PEXPIRE in the script means a bucket that has been idle long enough to refill completely is deleted, because at that point it holds no information: a missing key and a full bucket mean the same thing.
4The Java Client: Short Timeouts and a Clear Failure Rule
We do not want 40 teams writing their own Redis calls, so we ship a small Java library, plus the same logic as a gateway filter. It builds the key, calls the script and returns allow or reject. The important part is what happens when Redis is slow or unreachable.
The library uses a timeout of a few milliseconds, because a limiter that adds 200 ms to every request has become the outage. When the call fails or times out, the library applies a rule chosen per endpoint. Fail open means we allow the request: right for most read traffic, because a short loss of limiting is better than rejecting all users. Fail closed means we reject: right for an expensive or abuse-prone endpoint such as sending SMS. A circuit breaker pauses Redis calls for a few seconds after repeated failures.
The timeout itself is set on the Redis client, for example with spring.data.redis.timeout for the Lettuce client that Spring Boot creates.
5Fewer Round Trips for Very Hot Keys
A large customer sending 20,000 requests per second to one endpoint would put all its load on one Redis shard, because one key lives on one node. Two techniques help.
The first is a local pre-check: each instance keeps a small in-memory bucket per key, and if the local view already says the key is far over its limit, the instance rejects without asking Redis. The second is token batching: instead of taking one token per request, an instance takes 50 at a time and spends them locally. That cuts Redis calls for that key by a factor of 50.
The cost is accuracy. Tokens sitting in one instance's batch cannot be used by another instance, and an instance that dies loses its unspent tokens. With 20 instances each holding up to 50 tokens, the global count can be off by up to 1,000 at any moment, so we use batching only for keys whose limit is large compared with the batch size.
6Limits as Configuration, and What We Measure
Limits change: a customer upgrades, an endpoint gets a new default. So limits live in a configuration store, a database table or a config service, keyed by plan, API key and endpoint, with defaults for keys that have no override. Each instance caches them and reloads on a change event, so an update takes effect in seconds without a restart.
Finally, we measure. We need rejected requests per API key and endpoint, so support can answer a customer who asks why they are getting 429s. We need Redis latency at the 99th percentile and the error and fail-open counts, because a limiter that quietly fails open looks healthy while protecting nothing.
| Metric | Why we watch it |
|---|---|
| Rejections per key and endpoint | explain 429s to customers, spot abuse |
| Redis p99 latency | the limiter adds this to every request |
| Fail-open and fail-closed count | shows how often limiting was skipped |
| Checks per shard | finds hot keys before a node saturates |
| Config reload age | proves limit changes reached every instance |
7Follow-up questions
What happens to accuracy if you allocate token batches to each instance?
The limit becomes approximate. Each instance holds tokens that other instances cannot use, so a client spread across instances may be rejected slightly early on one instance while another still holds unspent tokens, and when an instance crashes its unspent tokens are simply lost. The worst-case error is the number of instances times the batch size, for example 20 instances with batches of 50 gives up to 1,000 tokens of drift. We keep it acceptable by using batches only for keys with large limits, making the batch a small fraction of the limit, and letting batches expire after a second so unused tokens are not held for long.
Why not use a fixed window counter with INCR and EXPIRE?
It is simpler and atomic on its own, but it allows bursts of up to twice the limit at window edges: a client can send the full limit in the last 100 ms of one window and again in the first 100 ms of the next. A token bucket or a sliding window avoids that, and with a Lua script the token bucket costs the same single round trip.
What should the client receive when it is limited?
HTTP 429 with a Retry-After header saying when a token will be available, plus headers with the limit and the remaining tokens, so well-behaved clients can slow down instead of retrying blindly.
8Conclusion
In this answer, we designed a distributed rate limiter around a token bucket per API key and endpoint. Its state lives in a Redis cluster and is updated by a Lua script, so concurrent instances cannot race. A shared Java library calls it with a short timeout and a per-endpoint fail-open or fail-closed rule, hot keys use local pre-checks or token batches at a small cost in accuracy, limits come from cached configuration that reloads on change, and metrics on rejections and Redis latency tell us whether the limiter is protecting anything.
Open with
I would use a token bucket per API key and endpoint, with the state in Redis, because every gateway and service instance needs to see the same bucket.
Then, if they want more
The check is a Lua script that refills the bucket using the Redis clock, compares, decrements and sets a TTL, all atomically, so two instances can never both spend the last token.
At 200,000 checks per second I would run Redis Cluster with several primaries; each bucket is one small hash and idle buckets expire once they would be full anyway.
The 40 services and the gateway use one shared Java library with a timeout of a few milliseconds and a circuit breaker, and each endpoint declares whether it fails open or closed when Redis is unavailable: reads fail open, expensive things like SMS fail closed.
For very hot keys I would add a local pre-check to shed obvious abuse and optionally take tokens in batches, accepting that the limit becomes approximate by up to instances times batch size. Limits live in a config store with defaults per plan, cached locally and reloaded on a change event.
And I would track rejections per key, Redis p99 latency and how often we failed open, because a limiter that silently fails open looks healthy while doing nothing.
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 "Design a distributed rate limiter service used by an API gateway and 40 Java services...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/3ea5748748/