Notestransactions🌱 seedling

Optimistic Concurrency Control

Also: OCC · Optimistic Locking · Optimistic Concurrency · Validation · Read Refresh

Run transactions without locks, record what they read, and at commit validate that none of it has changed; if it has, abort and retry. It bets that conflicts are rare, and pays in wasted work when they aren't.

Why it exists

Locks cost the most when they turn out to be unnecessary: most transactions never conflict, yet under Two-Phase Locking they still wait. Optimism removes the waiting from the common case.

How it works

  • Read phase: execute, reading from a snapshot or recording versions read; buffer writes privately.
  • Validation phase: at commit, check the read set (keys or ranges) against writes committed since the transaction started.
  • Write phase: if validation passes, publish the writes atomically; otherwise abort and retry from the start.
  • At the application level, a version column with UPDATE … WHERE version = n is the same idea for one row.

Trade-offs

Gains Costs
no lock waits or deadlocks aborts and redone work under contention
good throughput when conflicts are rare retry storms on hot keys, worst when the system is near capacity
readers never block long transactions fail validation more often

In practice

  • FoundationDB: strict serializability with pure OCC; conflicts fail the commit with not_committed, bindings retry automatically, and transactions are capped at five seconds.
  • CockroachDB: a hybrid. Write intents lock against writers, a timestamp cache orders writes after reads, and a pushed transaction refreshes its reads; if they changed, it returns a retryable 40001 error.

Pitfalls

  • Hot rows (counters, inventory of a bestseller) turn optimism into constant aborts. Use an atomic update or pessimistic locking there.
  • Side effects inside the retried function happen once per attempt.

Recall

These cards are also in your review deck, scheduled with spaced repetition.