tezvyn:

Two-Phase Locking (2PL): Preventing Database Race Conditions

AI-drafted, machine-checkedSource: Wikipedia: Two-phase lockingintermediate

2PL is a database's pessimistic strategy for safe concurrency. A transaction acquires all necessary locks before releasing any, ensuring operations don't clash. It's used to guarantee consistency.

WHY IT EXISTS To prevent data corruption when multiple transactions try to read and write the same data simultaneously. Without a control mechanism like 2PL, systems face race conditions like lost updates or reading uncommitted, incorrect data, which compromises data integrity.

THE MENTAL MODEL Think of a library with a strict rule. You enter a "growing phase" where you gather all the books you need (acquire locks). You cannot return any books during this phase. Once you have everything, you enter a "shrinking phase" where you can start returning books (releasing locks), but you are no longer allowed to check out any new ones.

HOW IT WORKS A transaction operates in two distinct stages. First is the Growing Phase, where it can obtain locks on data items (like rows or tables) but cannot release any. Second is the Shrinking Phase, where it can release locks but cannot obtain any new ones. This ensures that all locking happens before any unlocking begins, guaranteeing that transactions that conflict appear to run sequentially, not interleaved. This property is called conflict-serializability.

WHEN TO USE IT 2PL is the default for systems where strong consistency is non-negotiable, which includes most transactional relational databases (like PostgreSQL or MySQL with InnoDB). Use it when you need to be absolutely sure that concurrent operations don't corrupt your data, especially for multi-step operations.

WHEN NOT TO USE IT In systems with very high contention and a need for maximum throughput, 2PL can be a bottleneck. The locking can reduce concurrency and increase the likelihood of deadlocks, where two or more transactions are stuck waiting for each other to release locks. In these cases, optimistic locking might be a better fit.

ONE CANONICAL EXAMPLE A bank transfer from account A to B. The transaction must lock both account records. It enters the growing phase, acquiring a lock on A, then a lock on B. Only after securing both can it perform the debit and credit operations. Then, it enters the shrinking phase, releasing both locks. Any other transaction trying to access A or B during this process is blocked, ensuring the transfer is atomic and consistent.

Read the original → en.wikipedia.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.