Pessimistic vs. Optimistic Locking
Pessimistic and optimistic locking compared by contention, retries, and consistency.
Locking strategies exist because concurrent updates can corrupt state even when each individual transaction looks reasonable on its own. Pessimistic and optimistic locking are two ways of dealing with that risk, and they make opposite assumptions about how often conflicts happen.
Pessimistic locking assumes contention is likely enough that the safest move is to block early. A transaction acquires a lock before changing the row or record, and other transactions must wait until the lock is released. In SQL systems this often appears as SELECT ... FOR UPDATE or equivalent row-level locking. The benefit is strong protection against lost updates or conflicting business operations. The cost is waiting, reduced concurrency, and the possibility of deadlocks if transactions lock resources in inconsistent order.
Optimistic locking assumes conflicts are rare. Instead of blocking readers or competing writers up front, the system allows concurrent work and checks for interference at commit time. This is commonly implemented with a version number or timestamp column. A write succeeds only if the version read earlier still matches the version in storage. If another transaction has already updated the row, the write fails and the caller must retry or surface a conflict.
Optimistic locking often performs better in read-heavy systems because it avoids holding locks during user think time or long application processing. It is especially useful in web applications where a user may load a record, edit it for several minutes, and then submit changes. Keeping a database lock open for that entire period would be wasteful and fragile.
Pessimistic locking fits high-contention or high-value workflows where conflicts are common and retries are expensive. Inventory reservations, balance transfers, or tightly coordinated back-office operations often lean this way. Even then, lock scope should stay as narrow and short-lived as possible. Locking whole tables when only one row is contested is a classic source of unnecessary contention.
Neither approach removes the need for careful transaction design. Optimistic locking needs retry logic and a user experience that can handle conflict resolution gracefully. Pessimistic locking needs consistent access order, sensible timeouts, and monitoring for blocked sessions. In both cases, the real goal is not just mutual exclusion. It is preserving domain correctness under concurrency without destroying throughput.
A good rule is simple. If clashes are rare and throughput matters, start optimistic. If clashes are frequent and the cost of conflicting work is high, consider pessimistic locking. The real skill is not memorising which one is faster. It is understanding the conflict pattern in your domain and choosing the failure mode your system can handle cleanly.