Compare-and-swap (CAS), also called compare-and-set, is an algorithm you might have used many times without knowing its name. It checks a value and writes a new one in a single indivisible step. We can use it to make sure something runs only once, even when two users click the same button.
The problem
If I have a button which should only be clicked by one user, e.g. executing a retry workflow, a decommission, or something else, there is a chance two users, or two stale tabs, can click this button, and nothing on the JavaScript (client) side can guarantee that only one workflow is spawned.
Example
Very often we need to protect something from running more than once, and as the problem above shows, frontend protection is not enough.
CAS to the rescue. It’s a very clever algorithm which lets us protect it. Here is an example of a Retry feature, which runs some workflow and should run only once:
sequenceDiagram
participant FE as Frontend
participant BE as Backend
participant DB as Database
FE->>BE: retry
BE->>DB: fetch status, requestedAt
DB-->>BE: status, requestedAt
BE->>DB: update where id, status and requestedAt still match
DB-->>BE: matchedCount = 1
BE->>BE: start workflow
On the backend (Node.js with MongoDB), it looks like this:
const job = await db.jobs.findOne({ _id: id })
if (!job) return notFound()
const res = await db.jobs.updateOne(
{ _id: id, status: "FAILED", requestedAt: job.requestedAt }, // the check
{ $set: { status: "RETRYING", requestedAt: new Date() } } // the write
)
if (res.matchedCount === 0) return conflict() // 409: already retried by someone else
await startWorkflow(id)
Here the database does the synchronization. MongoDB applies the filter and the update to a single document atomically. Only one request will be able to update the value, leaving the second one with stale metadata (stale claims), so its update will fail.
The term comes from multiprocessor hardware. IBM added a compare-and-swap instruction to the System/370, and CPUs still use it to synchronize threads.
Example of a simple C++ function:
bool cas(int* p, int old, int new_) {
if (*p != old) return false;
*p = new_;
return true;
}
Theory
The core idea behind this is that check and write happen as one indivisible step.
The simple C++ version above isn’t safe, because another thread can change *p between the if and the write. An improved version would be:
#include <atomic>
bool cas(std::atomic<int>& p, int old, int new_) {
return p.compare_exchange_strong(old, new_);
}
// typical use
void increment(std::atomic<int>& counter) {
int current = counter.load();
while (!counter.compare_exchange_strong(current, current + 1)) {
// another thread won: current now holds the latest value, so just retry
}
}
Here, counter.compare_exchange_strong compares counter with current and, only if they are equal, writes current + 1, all in one atomic step. If another thread got there first, it returns false and loads the latest value into current, so the loop retries with fresh data.
CAS has a blind spot called the ABA problem. If another thread changes the value from A to B and back to A, the check still passes. That’s why the Retry example compares requestedAt as well as status. A timestamp only moves forward, so it works as a version number.
In assembly, it looks roughly like this:
retry:
ldxr w1, [p] // load-exclusive: read *p and start "watching" its cache line
cmp w1, old // compare the value from *p with old
b.ne fail // if not equal, branch to fail
stxr w2, new, [p] // store-exclusive: write only if nobody touched the line since ldxr
cbnz w2, retry // if w2 is not zero (the store failed), branch to retry
fail:
// fail scenario
Usages
Synchronization on one machine
Synchronization coordinates threads so they don’t corrupt shared data. A lock does it by letting one thread in at a time. CAS does it without a lock. Each thread tries to write, and if another one was faster, it retries.
Synchronization in a distributed world
In a distributed world, we can’t take atomicity for granted. That’s why, most of the time, we use a database to get it.
In the MongoDB world, this is done via:
db.counters.updateOne(
{ _id: "x", value: old }, // the check: *p == old
{ $set: { value: newVal } } // the write: *p = new
)
// matchedCount === 1 → true, 0 → false
The extra complexity is that in a distributed world everything can go wrong, e.g. a database node can fail and lose a recent write. But this is beyond the scope of CAS.
Real usages:
- etcd: transactions that compare a key’s value or
mod_revisionbefore writing - ZooKeeper:
setData(path, data, version), which fails if the node’s version has changed - SQL: optimistic locking with
UPDATE ... SET v = v + 1 WHERE id = ? AND v = ?
So whenever two requests can race to change the same thing, make the check part of the write. If nothing matched, someone else got there first.