System Design · Concept Library · Free article
Atomic Counters — incrementing a shared number without losing writes
Why "read it, add one, write it back" silently loses updates when many servers do it at once — and the three ways to make the increment safe: an atomic operation, compare-and-swap, and a transaction. The read-modify-write race and how to close it, for interns through principal engineers.
Adding one to a shared number looks trivial, but "read the value, add one, write it back" is three separate steps — and if two servers do it at the same instant, both read the same starting value and one increment silently vanishes. That’s the read-modify-write race (the lost update). The fix is to make the change happen as one indivisible step that nothing can interleave with — atomically. Three tools, in order of reach: a built-in atomic operation (INCR, or SQL’s UPDATE n = n + 1) when the change is a simple mutation; compare-and-swap (read a version, write only if it hasn’t changed, retry if it has) when the change is conditional; and a Lua script or transaction when several steps — like a rate limiter’s "read the count, and only if it’s under the limit, increment" — must run as one uninterruptible unit. The counter that guards a rate limit, a click count, or an inventory all live or die by this.
The increment that quietly disappears
Hatch’s rate limiter keeps a counter per client — "requests this minute" — and the rule is simple: read the count, and if it’s under 100, allow the request and add one. It works perfectly in testing on one machine. Then it goes to production, where the gateway is a pool of nodes, and two of them handle a request from the same client at the very same millisecond. Both read the counter: 99. Both see "99 is under 100," so both allow. Both compute 99 + 1 = 100 and write it back. The counter now reads 100 — but two requests were let through and two increments happened, so it should read 101. One increment vanished into thin air, and a client just slipped past a limit that was supposed to be airtight.
Nothing crashed. No error was logged. The code is exactly what you’d write, and it’s wrong — not always, just sometimes, precisely when two things touch the same number at once. This is the lost update, the most fundamental bug in all of concurrency, and it isn’t special to rate limiters: it’s the same bug that under-counts a viral link’s clicks, oversells the last item in inventory, and double-spends a balance. Learn to see it here on a counter, and you’ll recognise it everywhere.
Read-modify-write is three steps, not one
The trap hides in a single line of code. count = count + 1 reads as one action, but the machine does it in three: read the current value into memory, add one to that local copy, and write the result back. Those three steps take time, and in that time another server can slip in between your read and your write. If it reads the same value you did before you’ve written yours, you’re both working from a stale number, and whoever writes last wins — silently erasing the other’s work. Step through it one operation at a time and watch the increment get lost, then flip to the order that saves it:
The interactive version of this example is available when JavaScript loads.
The deeper name for the broken pattern is check-then-act (or read-then-write): you look at a shared thing, decide based on what you saw, and act — but the gap between the look and the act is where another actor invalidates your decision. "Read 99, decide it’s under the limit, write 100" is check-then-act, and so is "check the seat is free, then book it" and "check the file doesn’t exist, then create it." Every one of them is safe alone and a race in a crowd. And it gets worse with scale, not better — the more requests hammering the same value, the more collisions, and the more updates you lose:
The interactive version of this example is available when JavaScript loads.
The atomic operation — make the three steps one
The cleanest fix is to stop doing read-modify-write in your code at all, and hand the whole "add one" to something that does it as a single, indivisible step. That’s what atomic means: all-or-nothing, with no possibility of another operation wedging itself into the middle. Redis’s INCR is the classic example — you send one command, "increment this key," and because Redis handles one command at a time to completion, there is no window between the read and the write for anyone to sneak into. Two INCRs on the same key from a thousand servers simply run one after another: 99 → 100 → 101, every increment counted. In a SQL database the same idea is UPDATE counters SET n = n + 1 WHERE id = ? — the database applies the change in place under a row lock, so the read and write are fused into one atomic statement.
So the first question to ask of any shared-counter update is: is there a built-in atomic operation for exactly this? For "add one," "add N," "set to the max of," and many more, the answer is usually yes, and it’s the simplest, fastest, most bulletproof fix. You only need the next two tools when your update is more than a single built-in operation can express.
Compare-and-swap — write only if nobody moved it
Sometimes the new value depends on the old one in a way no single built-in op covers — "double it, but cap at 1000," say. You’re forced back into read-compute-write, so you need a way to make the write safe. Compare-and-swap (CAS) does it with a clever twist: alongside the value, you track a version that bumps on every change. You read both the value and its version, compute your new value, and then issue a write that says, in effect, "set this to my new value, but only if the version is still the one I read." If nobody touched it in between, the versions match and your write lands. If someone did, the version has moved, your write is rejected, and you simply read the fresh value and try again. Step through a conflict and its retry:
The interactive version of this example is available when JavaScript loads.
This is called optimistic concurrency, and the name captures the bet: you assume no one will clash, so you take no locks and pay nothing in the common case — you only do extra work (a retry) on the rare occasion there’s an actual conflict. It’s a brilliant fit when contention is low. When contention is high, though, those retries pile up and can thrash, which is when you reach for the heavier tools. (One classic subtlety to name for the interview: the ABA problem — if a value changes from A to B and back to A between your read and your CAS, a naive check on the value alone thinks nothing happened. That’s exactly why you compare a version that only ever counts up, not the value itself.)
When the whole thing must be one step: scripts & transactions
Now back to the rate limiter, because its update is trickier than a plain increment: it’s "read the count, and only if it’s under the limit, increment it." That’s a read, a decision, and a conditional write — three steps that must happen with nothing in between, or two nodes both read 99, both decide "under 100," and both increment. A single INCR can’t express the "only if under the limit" condition, and CAS would work but thrash under a flood. The clean answer is to bundle the whole sequence into one unit the store runs atomically end to end: a Lua script in Redis, or a transaction in a database. The store guarantees the entire script runs start to finish with no other command interleaved, so the read, the check, and the write are one indivisible move again — exactly the property we lost in §2, restored for a multi-step operation.
This is why real distributed rate limiters — the ones the distributed rate limiting and sliding window counter pages describe — do their check-and-increment inside a tiny Lua script on Redis rather than in application code. The exact script lives on the Redis page; the reason it has to be a script and not two round trips is everything on this page. One rule of thumb: if your "atomic" operation is really several steps that must all-or-nothing together, a built-in op won’t cut it — wrap it in a script or a transaction.
The same race, in SQL
It’s worth seeing this in a database too, because the identical trap catches people who think "the database will handle it." The safe way to bump a column is one atomic statement: UPDATE posts SET likes = likes + 1 WHERE id = ? — the database reads and writes the row under a lock, so concurrent bumps serialise and none are lost. The unsafe way is to do it in two trips from your app: SELECT likes … (compute likes + 1 in code) … UPDATE posts SET likes = ?. That’s read-modify-write with a network gap in the middle — the exact race from §2, now spanning two queries. When the update genuinely needs app-side logic between the read and the write, you protect it with a row lock (SELECT … FOR UPDATE grabs the row so no one else can read-to-write it until you commit — the pessimistic route) or with a version column and a conditional UPDATE … WHERE version = ? (the optimistic, CAS route in SQL clothing).
Which tool, when
| Your update is… | Reach for | Why |
|---|---|---|
| A simple built-in mutation (add, set-max) | Atomic operation (INCR, UPDATE n = n+1) | One indivisible command — simplest, fastest, no window to race in |
| Compute-from-old, low contention | Compare-and-swap (version + retry) | No locks; pays only on the rare real conflict |
| Multi-step read-check-write | Lua script / transaction | Runs the whole sequence atomically, nothing interleaves |
| Compute-from-old, high contention | Pessimistic lock (SELECT … FOR UPDATE) | Serialises upfront so retries don’t thrash |
Atomic is not the same as safe-to-retry
One trap worth heading off: atomicity and idempotency solve different problems, and you often need both. Atomicity stops two concurrent increments from clobbering each other. Idempotency stops one increment from being applied twice when the same request is retried — a client times out, resends, and now your perfectly-atomic INCR runs a second time and over-counts. An atomic operation run twice is still two increments. So a counter that must be exactly right under both concurrency and retries needs an atomic op and a way to recognise a duplicate request (an idempotency key), which is the whole subject of the idempotency page. Keep them separate in your head: atomic = "no interleaving," idempotent = "safe to repeat."
Pitfalls
- Read-modify-write in application code —
x = get(); set(x + 1)across a network is the lost update waiting to happen. Push the increment into an atomic op, script, or single SQL statement. SELECTthenUPDATEin two trips — the SQL version of the same race; useUPDATE n = n + 1, a version check, orSELECT … FOR UPDATE.- Comparing the value, not a version, in CAS — invites the ABA problem; version numbers that only ever increase avoid it.
- Assuming atomic means idempotent — an atomic increment run twice still counts twice; retries need an idempotency key on top.
- Optimistic CAS under heavy contention — a hot counter can thrash on endless retries; switch to a lock, a serialised owner, or a sharded counter.
- A single hot counter key — even atomic, one key hammered by the whole fleet is a write hotspot; splitting it is the hot-key fix.
Best practices
- Prefer a built-in atomic operation for simple mutations — it’s the simplest thing that’s correct.
- Use CAS with a version for compute-from-old updates at low contention; retry on conflict.
- Wrap multi-step read-check-write in a script or transaction so the whole thing is indivisible (the rate limiter’s pattern).
- Reach for a lock only when contention makes optimistic retries thrash — pessimism is a cost you pay for a reason.
- Add idempotency separately when the same request can be retried — atomicity alone won’t stop double-counting.
- Watch for hot counter keys and shard them if one value becomes a write hotspot.
The interview deck
- What’s a race condition on a counter? (intern)
- Two actors both read the same value before either writes back, both add one, and one increment is silently overwritten — the lost update.
count = count + 1is really read, add, write, and the gap between read and write is the race. - How do you fix it? (intern → SDE2)
- Make the change atomic — one indivisible step nothing can interleave with. Simplest is a built-in atomic op like Redis
INCRor SQLUPDATE n = n + 1, which fuse the read and write into one command under the hood. - What if the update isn’t a simple increment? (SDE2 → senior)
- Compare-and-swap: read the value plus a version, compute, and write only if the version hasn’t changed — retry if it has. It’s optimistic: no locks, pays only on a real conflict. For multi-step read-check-write, wrap it in a Lua script or a transaction so the whole thing is atomic.
- Why a version and not the value in CAS? (senior)
- The ABA problem — a value can change A→B→A between your read and your write, and a value-only check would miss it. A version that only counts up can’t be fooled.
- Isn’t an atomic increment also idempotent? (senior → staff)
- No — different problems. Atomicity stops concurrent increments clobbering each other; idempotency stops one increment being applied twice on a retry. An atomic
INCRrun twice still adds two. For correctness under retries you need an idempotency key as well.
The one thing to carry
"Add one to a shared number" is the smallest possible concurrency problem, and it teaches the whole discipline. count = count + 1 is three steps — read, add, write — and the instant two actors overlap on those steps, an update silently disappears. The cure is always the same shape: collapse the steps into one thing nothing can interrupt. A built-in atomic op does it for a simple change; compare-and-swap does it optimistically for a computed change; a script or transaction does it for a multi-step change. Get this reflex for a counter, and the exact same instinct protects a seat, a balance, and an inventory later on.
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.