Atomic read-modify-write
A read, a check and a write the store performs as one indivisible step, so when two requests saw the same count, one takes the last unit and the other is refused. The standard fix for lost updates.
What it is
A read-modify-write is any update whose new value depends on the old one: a stock count minus one, a version plus one, a locker going from free to held. Done as three separate calls from the application (read the value, compute, write it back) it works with a single client and can break when two clients run it at about the same time: both read 1, both compute 0, both write 0, and two units are promised while the count dropped by one. The Redis transactions guide uses this GET, add, SET sequence as its example of a race, and notes it is reliable with one client and not with several overlapping ones. Making the step atomic means the store performs the read, the check and the write as one operation that other requests see as a whole: it has either happened or not yet happened.
Stores offer that in several shapes; this page covers three, and taking a lock first is a fourth covered in the comparison below.
Unconditional atomic increment. Redis INCR adds one to a key, treats a missing key as 0, is limited to 64-bit signed integers, and returns the value after the increment; DECR and INCRBY are the same idea in other directions. DynamoDB's UpdateItem can act as an atomic counter, applying write requests in the order received. The increment carries no condition, so the check moves to the returned value: a reply above the limit means this request is refused.
Conditional update. The write carries the check: UPDATE ... WHERE units_left > 0. In PostgreSQL 17 under Read Committed, its default level, an update finds rows committed as of the command's start; if another transaction has updated the same row, the second updater waits for it to finish, then re-evaluates its WHERE clause against the new row version and skips the row when the clause no longer holds. DynamoDB condition expressions do the same job: the write succeeds when the expression is true against the most recently updated version of the item and returns an error otherwise.
Compare-and-set. At the CPU level, compare-and-swap compares a memory location with an expected value and writes a new value when they match, as one instruction; IBM 370 machines and their successors have carried it since 1970. Stores offer the same idea one level up: Redis WATCH (since 2.2) makes an EXEC conditional on the watched keys not having changed, and Redis 8.4 adds SET with IFEQ to update a string key when its value still equals what you read. A version column in a SQL row (WHERE version = 7) does it with a plain update.
-- One statement: the read, the check and the write happen together.
UPDATE stock
SET units_left = units_left - 1
WHERE sku = 'shoe-42' AND units_left > 0;
-- 1 row updated: this request got a unit.
-- 0 rows updated: no row matched both conditions. For a SKU known
-- to exist, that means sold out; tell the caller no.The result of the atomic step is the decision. A row count of 1, an INCR reply at or under the limit, an EXEC reply that is not null and holds no errors: that is the signal to create the order or assign the locker. A row count of 0 or a reply past the limit is a refusal. A timeout or transport error is neither, and needs its own retry or recovery path. The request should not read the count again to double-check, because that read can go stale right after it returns. A refused EXEC is retried from the WATCH onward; a refused conditional update is usually final, since the stock is gone.
When to use it
Use it wherever many writers contend for one small piece of state and the answer must be exact: the last units of a sale, the last large locker at a site, the last allowed request in a rate-limit window. The Redis documentation describes the rate-limit shape under its counter pattern: INCR a key for the client and the window and EXPIRE it, so the key counts recent requests and then disappears. Counting upward helps with stock too: INCR sold and compare the reply with the total; a request whose reply is above the total is refused, and the overshoot is harmless because the counter records attempts while the total stays fixed.
Say where the count lives and what a crash there loses. The count lives in one place that performs the atomic step; copies elsewhere are for display. If that place is Redis, name its persistence mode: RDB takes point-in-time snapshots at intervals, AOF logs each write and replays the log at startup, and with appendfsync everysec the documentation warns that a disaster can lose about one second of data. For a sale counting sold units upward, losing a second of accepted increments leaves the restarted counter lower than the number of requests already accepted, so the requests that follow pass a check that should have failed, and the units accepted in that window can be promised twice; how many depends on the write rate during the lost interval. A strong answer therefore also records each accepted request durably (an order row, an event) and rebuilds or reconciles the counter from that record after a restart. If the system of record is a SQL row, the open question is usually throughput on one hot row rather than lost writes.
When not to
Skip the condition when the number may be approximate. Page views, likes and metrics do fine with a plain INCR; the increment is already atomic and a check adds nothing. At very high rates on one key, an approximate counter or a counter split across several keys may be the better shape, because one key on one node is a hot key.
It also stops being enough when the change spans more than one row or key: moving money between two accounts, or assigning a locker and recording the parcel in another table. Then reach for the store's multi-key atomic operation if it has one, a transaction or a saga, and the atomic update is one step inside it. A hold that must outlive one request, such as a locker reserved until the courier arrives, can be modeled as a lease with an expiry rather than a single write: the atomic step claims the locker, and the expiry gives it back when nobody shows up.
Watch the retry path. DynamoDB's documentation says its atomic counters are not idempotent: a retried UpdateItem applies the change again, overcounting or undercounting, and it recommends a conditional update where that matters, giving banking as the example. A retried INCR after a timeout has the same problem. When a client may retry, pair the atomic step with an idempotency key or make the write conditional on the state it expects.
When writers rarely collide, optimistic locking with a version check is the simpler fit: read, do your work, write with WHERE version = ?, retry on zero rows. The Redis guide makes the same point about WATCH: when clients mostly touch different keys, collisions are rare and a repeat is seldom needed.
Compared
| Shape | How the loser finds out | Right when | Weak when |
|---|---|---|---|
Atomic increment ( | The returned value is past the limit | Counting upward against a fixed total; rate limits | Retries double-count; the rule lives in the client |
Conditional update ( | Zero rows affected, or a condition error | Exact stock; state changes such as free to held | One hot row; a failed DynamoDB condition still consumes write capacity |
Compare-and-set ( | Null | Low contention, or the new value needs computing in the app | Heavy contention turns most attempts into retries |
Lock first ( | Usually waits for the lock; some APIs offer no-wait or timeout variants that fail instead | Work the store does not do itself must happen between read and write | Holds the lock across the work; a holder that dies can stall others until the lock is released or its lease expires |