Bloqueo Pesimista

SELECT … FOR UPDATE

Escrito por Darjus Kazakevic · revisado el

Lock the row as you read it, so the second writer waits.

Pessimistic locking takes the lock when you read. In Postgres or MySQL this is SELECT … FOR UPDATE: the row stays locked until your transaction commits, and any other transaction that wants to change it waits. Nobody's work is thrown away, because nobody can read stale data and then write.

Use it when conflicts are frequent or a retry is expensive. The cost is what locks always cost: writers wait, timeouts need tuning, and two transactions that lock the same rows in a different order can deadlock.

En esencia — Lock the rows when you read them and hold the lock until commit, so a second writer waits instead of doing work that will be thrown away.

Cuándo recurrir a él

Recurre a él cuando

  • Many writers update the same few rows, like stock or a balance
  • A retry would be costly or visible, like a seat booking
  • Several workers share one jobs table (FOR UPDATE SKIP LOCKED)

Reconsidéralo cuando

  • Conflicts are rare: optimistic locking is cheaper
  • Across a user's think time or a call to another service
  • Across services or databases: a row lock cannot reach them

The mechanics

SELECT … FOR UPDATE
A read that also takes a row lock. Until you commit or roll back, other writers and other FOR UPDATE reads on that row wait. In Postgres, plain SELECTs are not blocked; they see the last committed value.
Deadlock
Transaction A locks row 1 and waits for row 2. Transaction B locks row 2 and waits for row 1. Neither can move. Postgres checks after deadlock_timeout (1 second by default) and aborts one of them.
Lock timeout
A waiting writer waits as long as the holder keeps its transaction open. lock_timeout makes the waiter fail with an error after a limit instead of hanging.
NOWAIT and SKIP LOCKED
Two options for a row that is already locked. NOWAIT fails at once. SKIP LOCKED ignores the locked rows, which lets many workers share one jobs table without taking the same job.

Applying it well

Lock rows in one fixed order
Two transfers between the same accounts in opposite directions deadlock unless both lock in the same order. Sort the ids and lock them in one query with ORDER BY id.
Keep the locking transaction short
Locks are released only at commit, and every writer on those rows waits until then. Never call another service or wait for a user while you hold one.
Set a lock timeout
Set lock_timeout to a few seconds. Then one stuck transaction causes a clear error, not a queue of waiting requests and an exhausted connection pool.

Errores habituales

  • Two code paths lock the same rows in a different order. The symptom: deadlock errors only under load.
  • Calling an HTTP API while holding the lock. When that API is slow, requests pile up behind the row.
  • Forgetting FOR UPDATE on the read, or running it outside a transaction, so it locks nothing.
  • No lock timeout, so one stuck transaction freezes every request that touches the row.