Optimistic Concurrency / CAS
When to Use Optimistic Concurrency / CAS
In Practice
ConditionExpression, S3's If-Match ETag, HTTP PUT with If-Match, Git's push (rejects non-fast-forward). Postgres multi-version concurrency control (MVCC) + SELECT FOR UPDATE NOWAIT is a hybrid.How Optimistic Concurrency / CAS Comes Up in Interviews
Scenario
Two writers occasionally update the same DynamoDB item. Contention is rare so you don't want a pessimistic lock. Instead you read the item with its version, send the update with a ConditionExpression on that version, and retry on rejection. What's the pattern?
Optimistic concurrency / compare-and-swap (CAS) reads-with-version and writes-if-unchanged, surfacing conflicts as retryable failures. Idempotency keys dedupe retries of the same operation, different problem.
Optimistic concurrency (compare-and-swap on a version field) wins when contention is rare because it avoids the throughput cost of pessimistic locks: no lock acquisition, no holdup of other readers, no deadlock potential. DynamoDB's ConditionExpression (e.g., attribute_not_exists(#v) OR #v = :expected), S3's If-Match ETag, HTTP PUT with If-Match, and Git's push (rejects non-fast-forward) are all OCC patterns. The contention/throughput crossover matters, if conflicts happen >10% of the time, the retry overhead can dominate and pessimistic locking becomes faster. Idempotency keys solve a different problem (dedupe retries of the same operation), so they wouldn't help here where the issue is two different writers stepping on each other.
Scenario
Two API clients both update a document concurrently. Conflicts are rare (<1% of updates). You'd rather not hold a row lock for the duration of a multi-step user workflow. Which approach lets writes proceed without blocking and surface conflicts as a retry?
Optimistic concurrency / CAS attaches a version to the read; the update is conditional on the version unchanged. Conflicts surface as 'retry the workflow' instead of blocking everyone. A mutex would serialize all writers regardless of conflict rate.