Compare-and-Swap

Change only the state you observed

Compare-and-swap (CAS) conditionally replaces a value only if its current value matches an expected value. The comparison and change form one atomic operation. Reading the value in application code and later writing unconditionally does not provide this property: another writer can change the value between those steps.

Two publishers expect the same version

Suppose two publishers both observed v1. The first changes the current pointer from v1 to v2. The second tries to publish v3 while still expecting v1 and must fail. In a database, UPDATE current SET version=? WHERE id=1 AND version=? expresses that condition. Check the affected-row count and commit outcome. In the worked example, zero changed rows raises a publication conflict.

A conflict needs a decision

After a conflict, inspect the current version and whether the candidate is still valid. Blindly reading the latest pointer and retrying can overwrite newer work with an older candidate. If a commit response is lost, reconcile the destination before repeating it. Accepting a repeat request for an already-current immutable candidate is a separate idempotency rule, not part of basic CAS.

What the comparison cannot prove

A matching pointer does not prove that source data is fresh or that a candidate covers every required day. Validate those separately. If a value changes from v1 to v2 and back to v1, a check against v1 misses the intervening change, often called the ABA problem. An increasing revision can distinguish those states. Fencing tokens instead identify ordered writer generations and require enforcement at the protected resource; do not treat every pointer comparison as fencing.

Worked example: Production Airflow: Idempotency, Retries, and Backfills.

Further reading


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.