Skip to main content

Pessimistic Locking

Pessimistic locking acquires locks before using data to prevent concurrent modification, ensuring correctness under high contention. It trades throughput and risks deadlocks, unlike optimistic control.

Type
Concurrency
When to Use
High Contention, Long Critical Sections, Must Prevent Conflicts

Pessimistic locking assumes conflicts are likely, so it locks data before working with it, blocking other transactions from modifying (and sometimes reading) it until the lock is released. Where optimistic control bets that conflicts are rare and checks at commit, pessimistic locking prevents conflicts up front. It guarantees that a transaction operating on locked data sees no interference.

How It Works

A transaction explicitly acquires a lock on the rows or resources it intends to use — in SQL, via SELECT ... FOR UPDATE (exclusive) or FOR SHARE (shared) — and holds it until the transaction commits or rolls back. Other transactions requesting an incompatible lock block until it is released. Lock granularity ranges from row to page to table; finer granularity allows more concurrency but costs more overhead. Databases combine pessimistic locks with isolation levels and deadlock detection that aborts one transaction in a cycle. Application-level distributed locks (Redis Redlock, ZooKeeper, etcd leases) extend the idea across processes.

When to Use It

Use pessimistic locking when contention on the same data is high, when critical sections are long or involve external side effects that cannot be cheaply retried, and when correctness absolutely must not be compromised: inventory decrements at scale, financial ledgers, and seat or ticket reservation. It avoids the wasted, repeated work that optimistic retries incur under heavy contention.

Trade-offs

Locks serialize access and reduce throughput; held too long they create contention bottlenecks. They introduce deadlocks (two transactions each waiting on the other), requiring detection, timeouts, and consistent lock-ordering discipline. Distributed locks add failure modes: a holder can crash or stall, so leases and fencing tokens are needed to stay safe. Under low contention, the lock overhead is pure cost compared with optimistic control.

Related Patterns

Pessimistic locking is the counterpart to optimistic-concurrency, generalizes the exclusive side of a read-write-lock, and is often coordinated across resources by two-phase-commit.

Example

A ticketing system selling limited seats uses SELECT ... FOR UPDATE to lock the chosen seat rows within a transaction before marking them sold. Concurrent buyers attempting the same seats block until the first transaction commits or rolls back, guaranteeing no seat is ever double-sold even during a high-demand on-sale.