Pessimistic Locking
ELI5 — The Vibe Check
Pessimistic locking assumes conflicts are likely, so it locks the row the moment you read it. Nobody else can touch it until you are done. Use SELECT FOR UPDATE and the row is yours until you COMMIT. Great for 'only one person can buy the last ticket' scenarios.
Real Talk
Pessimistic locking acquires an exclusive lock on a row (or set of rows) at read time using SELECT FOR UPDATE. The lock is held until the transaction commits or rolls back, preventing other transactions from reading or modifying the locked rows. It prevents race conditions but reduces concurrency and can cause deadlocks if not managed carefully.
Show Me The Code
BEGIN;
-- Lock the row so nobody else can change it
SELECT * FROM tickets
WHERE id = 1 AND available = true
FOR UPDATE;
-- Now safely decrement
UPDATE tickets SET available = false WHERE id = 1;
COMMIT;
When You'll Hear This
"Use SELECT FOR UPDATE (pessimistic locking) to guarantee only one transaction can reserve the ticket." / "Pessimistic locking hurts throughput under high concurrency."
Related Terms
Deadlock
A deadlock is when two things are each waiting for the other to go first, and neither ever does. Thread A holds Lock 1 and wants Lock 2.
Locking
Locking prevents two transactions from modifying the same data at the same time. It is how databases coordinate concurrent access.
Optimistic Locking
Optimistic locking assumes conflicts are rare so it does not lock the row upfront. Instead, it adds a version number to each row.
Race Condition
A race condition is when two parts of your code are racing to do something at the same time and the winner isn't guaranteed — leading to unexpected, hard-t...
Transaction
A transaction groups multiple database operations into one all-or-nothing bundle. Either ALL of them succeed, or NONE of them happen.