Quick revision
The short answer
A token bucket holds up to 100 tokens and refills at 50 per second; tryAcquire() first adds elapsed time x rate tokens, capped at the capacity, measured with System.nanoTime rather than the wall clock, then takes one token if one is available. A synchronized method is simple and fast enough for most services, and a lock-free version swaps an immutable state with compareAndSet. Across 40 instances we either give each instance a share of the limit, simple but uneven under skewed load, or keep the bucket in Redis behind an atomic Lua script, which adds latency and a dependency whose failure behaviour we must decide. In production I would prefer Bucket4j, Resilience4j or the gateway limiter, tested with a controllable clock.
What to remember
In this answer, we implemented a token bucket with a capacity of 100 and a refill of 50 tokens per second, refilling lazily on each call from System.nanoTime and taking a token if one is available. A synchronized method is simple and fast enough for most services, and a compareAndSet on an immutable state object is a lock-free alternative to measure against it. Across 40 instances we either divide the limit, which is cheap but uneven under skewed load, or share a bucket in Redis through an atomic Lua script, which is accurate but adds latency and a dependency whose failure mode, open, closed or local fallback, we must decide. In production, a library or gateway limiter tested with a controllable clock is the better choice.
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 token bucket holds up to 100 tokens and refills at 50 per second; tryAcquire() first adds elapsed time x rate tokens, capped at the capacity, measured with System.nanoTime rather than the wall clock, then takes one token if one is available. A synchronized method is simple and fast enough for most services, and a lock-free version swaps an immutable state with compareAndSet. Across 40 instances we either give each instance a share of the limit, simple but uneven under skewed load, or keep the bucket in Redis behind an atomic Lua script, which adds latency and a dependency whose failure behaviour we must decide. In production I would prefer Bucket4j, Resilience4j or the gateway limiter, tested with a controllable clock.
Why this question is asked
Rate limiters protect services from overload and enforce fair use: an API that allows 50 requests per second per customer, a worker that must not flood a database, a gateway shielding a fragile backend. The token bucket is the most common algorithm because it allows short bursts while enforcing an average rate. Interviewers ask for an implementation to check concurrency basics and time handling, and then the distributed version to see how we reason about consistency, latency and failure. In this answer, we will recap the token bucket, implement it for one instance, make it thread-safe in two ways, extend it to 40 instances, decide what happens when the shared store fails, and discuss libraries and testing.
1A Quick Recap of the Token Bucket
Picture a bucket that holds at most 100 tokens and receives 50 new tokens per second, continuously, so one token every 20 ms. Each request takes one token; if the bucket is empty, the request is rejected. When traffic is quiet the bucket fills up to 100, so a burst of 100 requests can pass at once. After that, requests pass at the refill rate, 50 per second.
We do not need a timer thread that adds tokens. Instead, every call computes how much time has passed since the last update and adds the tokens that time would have produced. This lazy refill makes the limiter cheap: constant work per call, and nothing running in the background.
2A Simple Thread-Safe Implementation
The state is the current number of tokens, kept as a double so fractional refills are not lost, and the time of the last refill. The clock is injected so tests can control it.
- Read now = nanoTime()monotonic clock
- Refilltokens =
min(100, tokens + elapsed x 50/s) - tokens >= 1?YesTake one token, return trueNoReturn false: rejected
3 steps in order. Play them, or step through them one at a time.
The refill is computed lazily on each call; no timer thread is needed.
Two details deserve explanation. We use System.nanoTime because it is monotonic: it only moves forward and is meant for measuring elapsed time. System.currentTimeMillis follows the wall clock, which NTP adjustments or a manual change can move backwards or forwards, which would create a burst of free tokens or a long freeze. And we compute now - lastRefill as a difference, which is how nanoTime must be used, since its absolute value has no meaning.
synchronized makes the read-refill-take sequence atomic, so two threads cannot both take the last token. The critical section is a few arithmetic operations, so even under heavy load the lock is held for nanoseconds, and for most services this is fast enough. Since JDK 24, virtual threads no longer pin their carrier inside synchronized, which removes an older reason to avoid it.
3A Lock-Free Version
Under very high contention we can avoid the lock by putting both fields into one immutable object and replacing it atomically. Each call reads the current state, computes the new one, and installs it with compareAndSet only if no other thread changed it in the meantime; otherwise it retries.
This allocates a small object per call and can spin under extreme contention, so it is not automatically faster; we would measure both with JMH. Libraries go further, for example packing state into a single AtomicLong, but the synchronized version is the right default.
4Holding the Limit Across 40 Instances
With 40 instances behind a load balancer, a local bucket per instance with the full limit would allow 40 x 50 = 2,000 requests per second in total, so we must choose. The first option divides the limit: each instance gets 50 / 40 = 1.25 tokens per second and a capacity of 2.5. It needs no coordination and adds no latency, but it is only correct when traffic is spread evenly. If one client's requests all land on 5 instances, that client gets at most 6.25 per second while the configured limit is 50, and the shares must be recomputed whenever the number of instances changes during scaling.
The second option keeps one shared bucket in a store such as Redis. Each request runs a short Lua script that reads the bucket, refills it, takes a token and writes it back. Redis runs a script atomically, so concurrent requests from all instances cannot double-spend tokens. The script should use the Redis server's time rather than each instance's clock, so clock differences between machines do not matter. The cost is a network round trip on every request, typically under a millisecond in the same data centre, plus a new dependency in the request path.
| Aspect | Local share (50 / 40) | Shared bucket in Redis |
|---|---|---|
| Accuracy | exact only with even load | exact across all instances |
| Latency per request | nanoseconds | a network round trip, often under 1 ms |
| New dependency | none | Redis in the request path |
| Scaling to 60 instances | recompute every share | no change |
| If the dependency fails | not applicable | must choose fail open or fail closed |
5Deciding What Happens When the Shared Store Fails
If Redis is slow or unreachable, every request must still get an answer. Failing open lets requests through without limiting, which keeps the service available but removes protection exactly when something is already wrong. Failing closed rejects requests, which protects the backend but turns a Redis outage into a full outage of our service. The right choice depends on what the limit protects: a limit that guards a fragile downstream system or enforces paid quotas may fail closed, while a fairness limit usually fails open.
A good middle path is a local fallback: each instance keeps a local bucket with its 1.25 per second share and switches to it when the Redis call times out after a short deadline, such as 5 ms. Protection degrades gracefully instead of disappearing. Whatever we choose, we record it in metrics and alerts, so we know when the limiter is running in fallback mode.
6Libraries and Testing
In production I would rather not maintain my own limiter. Bucket4j implements token buckets locally and on top of distributed stores such as Redis, Resilience4j's RateLimiter provides per-instance limiting with Spring Boot integration, and an API gateway, such as Spring Cloud Gateway's Redis-based request rate limiter, can enforce limits before traffic reaches the service at all; check the current names and options for your versions.
Testing needs a clock we control, which is why the constructor takes a LongSupplier. A test uses a fake clock backed by an AtomicLong, calls tryAcquire 100 times and expects 100 passes and then a rejection, advances the clock by 20 ms and expects exactly one more pass, and advances by 10 seconds and expects the bucket to be capped at 100, not 500. For thread safety, a test starts many threads behind a CountDownLatch so they call tryAcquire at the same moment with the clock frozen, and asserts that exactly 100 calls succeed in total.
7Follow-up questions
How do you test a rate limiter without real sleeps?
I inject the time source. The limiter takes a LongSupplier for nanoTime, and the test passes a fake clock it can advance by exact amounts. Then every assertion is deterministic: 100 passes with a frozen clock, one more pass after advancing 20 ms, no more than 100 after a long pause. Sleeping in tests is slow and flaky because the scheduler can delay a thread by many milliseconds, which changes how many tokens appear. For concurrency, I freeze the clock, release many threads at once with a CountDownLatch, and count the successes.
Why a token bucket rather than a fixed window counter?
A fixed window, such as 50 requests per calendar second, is simpler but allows bursts at window boundaries: 50 requests at the end of one second and 50 at the start of the next give 100 in a few milliseconds. A token bucket smooths that and makes the allowed burst explicit as the capacity. Sliding window algorithms are another option with similar smoothing.
8Conclusion
In this answer, we implemented a token bucket with a capacity of 100 and a refill of 50 tokens per second, refilling lazily on each call from System.nanoTime and taking a token if one is available. A synchronized method is simple and fast enough for most services, and a compareAndSet on an immutable state object is a lock-free alternative to measure against it. Across 40 instances we either divide the limit, which is cheap but uneven under skewed load, or share a bucket in Redis through an atomic Lua script, which is accurate but adds latency and a dependency whose failure mode, open, closed or local fallback, we must decide. In production, a library or gateway limiter tested with a controllable clock is the better choice.
Open with
For one instance, I keep two fields, the current tokens as a double and the time of the last refill from System.nanoTime, which is monotonic, unlike the wall clock. tryAcquire computes the elapsed time, adds elapsed times 50 per second worth of tokens, caps the total at 100, and then, if at least one token is there, takes it and returns true, otherwise returns false.
Then, if they want more
That allows a burst of 100 and then 50 per second, one token every 20 milliseconds, with no background timer. I make tryAcquire synchronized. The critical section is a few arithmetic operations, so it is fast enough for most services.
If profiling showed contention, I could make it lock-free with an immutable state record in an AtomicReference and a compareAndSet loop. Across 40 instances there are two main options.
I can give each instance a share, 1.25 tokens per second and a capacity of 2.5, which needs no coordination but is only accurate when the load balancer spreads traffic evenly, and the shares change with scaling.
Or I keep one bucket in Redis and update it with an atomic Lua script using the Redis server's time, which is accurate but adds a round trip per request and a dependency. Then I decide what happens if Redis fails, fail open, fail closed, or ideally fall back to the local share.
In production I would rather use Bucket4j, Resilience4j or the gateway's limiter, and I would test with an injected clock instead of sleeps.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 24
- 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 "Implement a thread-safe token bucket rate limiter in Java (tryAcquire() returns true if...": https://scrivio-interview-library.netlify.app/java/coding-problems/6a4a2bbb3e/