Skip to content

Pessimistic Locking

Spicy — senior dev territoryDatabase

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.