Compare-and-Swap (CAS) and Optimistic Concurrency Control

A concurrency control technique that commits updates only if the record version matches what was originally read. It prevents overwriting concurrent edits without acquiring heavyweight locks.

General Meaning

When multiple concurrent processes attempt to mutate the same data record, traditional pessimistic concurrency control locks the target row upfront, preventing others from accessing it until the transaction completes. In contrast, optimistic concurrency control allows processes to read records and perform computations concurrently without holding locks, verifying at write time that no concurrent modification occurred in the interim.

The fundamental atomic building block powering optimistic concurrency control is Compare-and-Swap (CAS). A CAS operation atomically inspects whether the current revision matches the expected revision read earlier; if matching, it swaps in the new values and reports success, but if another writer has altered the record, the operation leaves the data untouched and returns a conflict failure.

Why It Matters

  • Preventing lost update anomalies: If worker A and worker B read identical state concurrently and worker B saves first, CAS guarantees worker A's delayed write cannot overwrite worker B's changes silently.
  • Eliminating distributed deadlocks: Because workers do not hold long-lived exclusive locks across multiple records while computing, deadlock chains and system freezes are avoided.
  • Ideal for serverless and edge architectures: Modern edge datastores like Cloudflare D1 cannot sustain open stateful connections or durable row locks, making single-statement conditional SQL updates the safest concurrency model.

How the Site Factory Uses It

In the Site Factory, CAS using monotonic integer revisions (revision) and status flags (status) is applied systematically across Cloudflare D1 operations. For task updates in dispatch/src/authority.js, SQL queries enforce UPDATE work_items SET data=?, revision=revision+1 WHERE id=? AND revision=?, raising HTTP 409 revision conflict if rows affected is zero. Claiming execution jobs in authority.js and a2a-claim.js relies on UPDATE execution_jobs SET status='leased', ... WHERE id=(...) AND status='pending' RETURNING *. Similarly, A2A workflow advances in dispatch/src/workflow.js and a2a-evidence.js enforce WHERE w.work_id=? AND w.revision=?, rejecting mismatched writes as revision_or_lease_conflict, and direct upload evidence logging in dispatch/src/direct-upload-evidence.js checks expected revisions before appending.

When updating tasks via authority.js, callers supply an expected_revision. New tasks expect revision 0 via INSERT ... ON CONFLICT DO NOTHING, whereas subsequent mutations conditionally update WHERE id=? AND revision=expected_revision. If a competing worker updated the task first, the database reports zero changed rows (changes === 0), causing the endpoint to immediately return HTTP 409 to trigger safe retry logic.

Caveats & Operational Rules

  • Establish an explicit conflict retry strategy: When a CAS collision occurs, callers must have clear policies defining whether to fail immediately or reload the latest canonical record, merge changes, and retry.
  • Use monotonic revisions to prevent the ABA problem: Comparing payload values directly can create illusions of unchanged state if a value shifts from A to B and back to A; the Site Factory always compares an integer sequence that strictly increments (revision=revision+1).
  • Complete conditional mutations in a single atomic SQL statement: Splitting logic into a SELECT followed by an UPDATE opens a race window where concurrent mutations intervene; updates must always be evaluated atomically in one statement like UPDATE ... WHERE revision=?.

Related Terms

References

  • Book: Martin Kleppmann, *Designing Data-Intensive Applications*, Chapter 7 (Transactions: Preventing Lost Updates, Explicit Locking and CAS)

Verified: 2026-11-08