Quick revision
The short answer
We can put limit, used and windowStart into one immutable record and replace the whole record with AtomicReference using a compare-and-set loop, so every reader sees a consistent triple without any lock. The price is a new object for every update and wasted retries when many threads update at once. A lock is simpler to reason about and can perform as well or better under heavy write contention, so the honest answer is to benchmark both at the expected thread counts and pick the simpler one unless the numbers say otherwise.
What to remember
In this answer, we saw that three separate atomic fields cannot keep a rate limiter's invariant, because the fields must change together. Putting them into an immutable record behind an AtomicReference and swapping it with a compare-and-set loop gives readers a consistent triple without locks, at the cost of an allocation per update and wasted retries under contention. A lock gives the same correctness with simpler code and often competes well under heavy writes, so we benchmark both at realistic thread counts and keep the simpler one unless the numbers say otherwise.
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 can put limit, used and windowStart into one immutable record and replace the whole record with AtomicReference using a compare-and-set loop, so every reader sees a consistent triple without any lock. The price is a new object for every update and wasted retries when many threads update at once. A lock is simpler to reason about and can perform as well or better under heavy write contention, so the honest answer is to benchmark both at the expected thread counts and pick the simpler one unless the numbers say otherwise.
Why this question is asked
Rate limiters, circuit breakers and quota trackers all share this shape: a few fields that only make sense together. If one thread resets the window while another increments used, we can end up with a used count from the old window attached to the new start time. Interviewers ask this design question to see whether we know how to update several fields atomically without a lock, and whether we can judge when that is actually worth it. In this answer, we will see why separate atomic fields fail, build the immutable-state version step by step, look at what it costs, write the lock version for comparison, and then decide with a benchmark.
1Why Three Atomic Fields Are Not Enough
The obvious first attempt makes each field atomic: an AtomicLong for used and another for windowStart. Each field is then safe on its own, but the rule of the rate limiter involves both: 'if the window has expired, start a new one and reset used to zero; otherwise allow the request only if used is below limit'. Two threads that both notice the expiry can both reset, and a third thread can increment used between the reset of windowStart and the reset of used, so its request is counted in the wrong window or lost.
The problem is that the three values form one piece of state with an invariant, a rule that must always hold among them. Any design must make each change to the triple appear all at once.
2Fix 1: One Immutable Record in an AtomicReference
The trick is to stop changing fields at all. We put the three values into an immutable record, a class whose fields never change after construction, and keep one AtomicReference pointing at the current record. To update, we build a new record from the old one and swap the reference with compareAndSet. Since a reference swap is a single atomic step, readers see either the whole old triple or the whole new one, never a mix.
Notice that we used a hand-written loop rather than updateAndGet, because we also need to know whether the request was allowed, and updateAndGet only returns the new state. Notice too that compareAndSet on an AtomicReference compares references with ==, not equals(). That is exactly what we want here, because each record object is created once and never reused, so 'the same object' means 'nobody has updated since we read it'.
The reader side is the real gift of this design. remaining() takes no lock, cannot block, and always sees a triple that some writer actually created. AtomicReference has volatile semantics, so the fields of the record a thread reads are fully visible to it.
3What the Immutable Design Costs
Every successful update allocates a new Window, about 32 bytes. At 100,000 updates per second that is roughly 3 MB per second of short-lived garbage, which modern collectors handle easily, but it is not free on a hot path. The bigger cost appears under contention. If 32 threads call tryAcquire at the same moment, only one CAS can win each round. The other 31 threw away the object they built and loop again, so a lot of CPU goes into building records that are never used, and the shared reference bounces between CPU caches with every attempt.
So the design shines when reads are frequent and writes are moderate or spread out, and it degrades when many threads hammer the same reference.
| Aspect | AtomicReference + record | Lock |
|---|---|---|
| Reader cost | One volatile read, never blocks | Lock or ReadWriteLock acquire |
| Consistency | Always a whole triple | Whole triple while locked |
| Allocation | New record per update | None |
| Heavy write contention | Retries waste CPU | Threads queue, little wasted work |
| Reasoning | Must keep records immutable | Plain code inside the lock |
4Fix 2: The Same Logic Under a Lock
For comparison, here is the lock version. The fields can be plain longs because every access happens while holding the lock, which gives both mutual exclusion and visibility.
This is shorter, has no allocation and no retry loop, and anyone can check it by reading it top to bottom. Under heavy contention, a ReentrantLock lets one thread work while the others wait, parking after a short spin, so CPU is not burned on discarded attempts. Each request does a tiny amount of work inside the lock, so throughput is often perfectly adequate. Its weakness is that readers must take the lock too, or the fields must be made volatile with care.
5Choosing With a Benchmark
Both designs are correct, so the choice is about cost, and intuition about concurrent performance is unreliable. A JMH benchmark, the standard Java microbenchmark harness, run with the thread counts we really expect, for example @Threads(4) and @Threads(32) on the production instance type, and with the expected mix of reads and writes, gives us numbers instead of opinions.
My default would be the lock version, because it is the easiest to read and maintain, unless the benchmark shows that the lock-free reader path or throughput matters for this service. If neither is fast enough at very high rates, the next step is not more clever CAS code but less sharing: one limiter per thread or per shard, each with its share of the limit, combined approximately.
6Follow-up questions
Why not use AtomicLong for used and recompute the window from the clock?
For a fixed window we can derive the window number from the time and store used per window number, which avoids the reset race in some designs. But the reset of used still has to be tied to the window atomically, so we end up packing both into one value or one object anyway.
Could we pack the fields into a single long?
Sometimes. If used fits in 20 bits and the window number in 44 bits, one AtomicLong can hold both and a CAS updates them together with no allocation. It is fast but hard to read, so it should be hidden in a small, well-tested class.
Would a ReadWriteLock help readers?
Only if reads are long or very frequent compared with writes. A ReentrantReadWriteLock has more overhead per acquisition than a plain lock, and here both reads and writes are tiny. A StampedLock with optimistic reads can help, but it is harder to use correctly.
7Conclusion
In this answer, we saw that three separate atomic fields cannot keep a rate limiter's invariant, because the fields must change together. Putting them into an immutable record behind an AtomicReference and swapping it with a compare-and-set loop gives readers a consistent triple without locks, at the cost of an allocation per update and wasted retries under contention. A lock gives the same correctness with simpler code and often competes well under heavy writes, so we benchmark both at realistic thread counts and keep the simpler one unless the numbers say otherwise.
Open with
The three fields have an invariant between them, so making each one atomic separately doesn't help; a reset of the window and an increment of used can interleave and count requests in the wrong window.
Then, if they want more
One lock-free option is to put limit, used and windowStart in an immutable record and hold it in an AtomicReference. To acquire, I read the current record, build the next one, a new window or used plus one, and compareAndSet the reference; if the CAS fails, someone else updated it, so I loop with the fresh record.
I'd write the loop by hand rather than use updateAndGet, because I also need to return whether the request was allowed. The big benefit is that readers just read the reference and always get a consistent triple, without locking or blocking.
The costs are an allocation for every update, and under heavy contention most threads lose the CAS, throw away the record they built and retry, which burns CPU and bounces the cache line.
The lock version is plain code inside lock and unlock, no allocation, easy to review, and under heavy writes it often does as well, because waiting threads park instead of spinning. So I'd benchmark both with JMH at the thread counts we actually expect, and default to the lock unless the numbers justify the lock-free version.
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 documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.concurrent, package documentation, JLS chapter 17, Threads and Locks
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 object holds three related fields (limit, used, windowStart) that must be updated...": https://scrivio-interview-library.netlify.app/java/atomics/3b7617d310/