Quick revision
The short answer
I would give each API key a token bucket with a capacity of 100 that refills 100 tokens per minute, using Bucket4j, and keep the buckets in Redis so all instances share one limit. A servlet filter resolves the key and consumes a token before the controller runs; when the bucket is empty it returns 429 Too Many Requests with a Retry-After header. I also decide up front whether to fail open or fail closed if Redis is unavailable.
What to remember
In this answer, we built a per-API-key limit of 100 requests per minute. We used a token bucket with Bucket4j, stored the buckets in Redis so the limit holds across every instance, checked it in a servlet filter before the controller, and returned 429 with Retry-After when the bucket was empty. Finally, we decided how to behave when Redis is unavailable: fail open, fail closed, or fall back to an approximate local limit.
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.
I would give each API key a token bucket with a capacity of 100 that refills 100 tokens per minute, using Bucket4j, and keep the buckets in Redis so all instances share one limit. A servlet filter resolves the key and consumes a token before the controller runs; when the bucket is empty it returns 429 Too Many Requests with a Retry-After header. I also decide up front whether to fail open or fail closed if Redis is unavailable.
Background to this question
Rate limiting per API key protects a service from one noisy client and is often part of a paid plan, so it has to be correct across every instance of the service. The coding question tests whether we know the algorithm, why a local in-memory limit is wrong behind a load balancer, where the check belongs in a Spring Boot request, and what the client should see. In this answer, we will recap the token bucket, show why the bucket must be shared, write the filter with Bucket4j and Redis, return a proper 429 response, and decide what happens when Redis is down.
1A Quick Recap of the Token Bucket
A token bucket holds up to a fixed number of tokens, its capacity. Each request takes one token. Tokens are added back at a steady rate. If the bucket is empty, the request is refused. For 100 requests per minute we use a capacity of 100 and a refill of 100 tokens per minute, added gradually, so about one token every 600 ms.
This allows a client that was quiet to send a burst of up to 100 requests at once, and then limits it to the refill rate. That behaviour suits most APIs: clients are rarely perfectly smooth, and a burst after a quiet period is harmless. Bucket4j is a Java library that implements token buckets and can store their state locally or in a shared store such as Redis.
2Why a Local Bucket Is Not Enough
Suppose the service runs on 4 instances behind a round-robin load balancer and each instance keeps its own bucket per key in memory. A client then gets 100 requests per minute on each instance, 400 in total. And the limit changes whenever we scale: 10 instances during peak means 1,000 per minute. Local buckets only limit per instance.
To enforce 100 per minute per key across the whole service, all instances must consume from the same bucket. So the bucket state lives in Redis, keyed by the API key. Bucket4j's Redis integration (for example the Lettuce-based proxy manager) stores each bucket as a Redis value and updates it atomically with compare-and-swap or a Lua script, so two instances cannot both take the last token.
| Setup | Effective limit with 4 instances | Correct? |
|---|---|---|
| Bucket in each instance's memory | up to 400 per minute per key | no, grows with instances |
| Bucket in Redis, shared | 100 per minute per key | yes |
| Sticky routing by key, local bucket | 100 until rebalancing moves keys | fragile |
3Writing the Filter
The check belongs before the controller, so a refused request costs as little as possible and every endpoint is covered. A OncePerRequestFilter fits well. It reads the API key from a header, asks the proxy manager for that key's bucket (creating it from a configuration if it does not exist yet), and tries to consume one token.
Notice that tryConsumeAndReturnRemaining gives us both the decision and the time until the next token, which is exactly what Retry-After needs. refillGreedy adds tokens continuously rather than all 100 at the start of each minute. The Bucket4j builder method names have changed between versions (older versions used Bandwidth.classic and Refill), so check your version. In a Spring Cloud Gateway setup, the same check would sit in the gateway instead of each service.
4What the Client Sees
A refused request gets HTTP 429 Too Many Requests, the status code defined for this case, with a Retry-After header in seconds. Well-behaved clients wait that long instead of retrying in a tight loop. Adding X-RateLimit-Remaining (or the newer RateLimit header fields being standardised by the IETF) on successful responses lets clients slow down before they hit the limit. We should also log and count refusals per key, so support can answer "why am I being throttled?" with data.
9 messages in order. Play them, or step through them one at a time.
5When Redis Is Unavailable
Every request now depends on Redis, so we must decide what happens when it is slow or down. Failing open means letting requests through without a limit; the API stays available, but abusive clients are not stopped during the outage. Failing closed means rejecting requests (or returning 503); the limit holds, but a Redis problem becomes a full API outage. Most public read APIs fail open with a short Redis timeout of a few milliseconds and an alert, because availability matters more than precise limits for a few minutes. An API where the limit protects something expensive, such as SMS sending, may fail closed.
A middle path is to fall back to a local bucket per instance with the limit divided by the instance count, say 25 per minute with 4 instances. It is approximate, but it still stops runaway clients. Whatever we choose, we wrap the Redis call in a timeout and a circuit breaker, so a slow Redis does not add seconds to every request.
6Follow-up questions
Why a token bucket rather than a fixed window counter?
A fixed window counter, such as INCR on a Redis key per minute, is simpler, but it lets a client send 100 requests at 12:00:59 and 100 more at 12:01:00, which is 200 in two seconds. The token bucket refills smoothly, so the most a client can send is the capacity plus the refill, and its state is just two numbers per key. Both are fine for many APIs; the bucket gives smoother limits for little extra cost.
How would you give different plans different limits?
The configuration supplier would look up the key's plan, for example 100 per minute for free keys and 2,000 for paid ones, and build the BucketConfiguration from it. Caching the plan lookup for a minute keeps it cheap. If a customer upgrades, Bucket4j can replace the configuration of an existing bucket, or we simply let the old bucket expire and a new one is created with the new limit.
7Conclusion
In this answer, we built a per-API-key limit of 100 requests per minute. We used a token bucket with Bucket4j, stored the buckets in Redis so the limit holds across every instance, checked it in a servlet filter before the controller, and returned 429 with Retry-After when the bucket was empty. Finally, we decided how to behave when Redis is unavailable: fail open, fail closed, or fall back to an approximate local limit.
Open with
I would use a token bucket per API key, with a capacity of 100 and a refill of 100 tokens per minute, so a client can burst up to 100 and is then held to about one request every 600 milliseconds.
Then, if they want more
In Java I would use Bucket4j rather than writing the algorithm myself. The important design point is where the bucket lives.
Since the service runs on several instances behind a load balancer, a bucket in each instance's memory would give a client 100 per minute per instance, so 400 with four instances, and the limit would change every time we scale.
So I store the buckets in Redis with Bucket4j's Redis proxy manager, which updates them atomically, and every instance consumes from the same bucket. I would do the check in a OncePerRequestFilter, before any controller runs: read the X-API-Key header, get the bucket for that key, and try to consume one token.
If it succeeds I add a remaining-requests header and continue the chain. If not, I return 429 Too Many Requests with a Retry-After header computed from the time until the next token. Finally, I decide what happens if Redis is down.
For most read APIs I would fail open with a very short timeout and an alert, or fall back to a local bucket with the limit divided by the number of instances, and I would fail closed only where the limit protects something expensive.
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 "Describe how you would implement a per-API-key rate limit of 100 requests per minute in...": https://scrivio-interview-library.netlify.app/spring-boot/scalability/15d09bffd1/