AI Hints
Home›PostgreSQL Tutorial›Isolation, Locks and Job Queues
PostgreSQL · Lesson 68 of 120

Locks and Deadlocks

Waiting your turn.

⏱ 2 min read▶ Video at 1:01:15🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Readers never wait, but two writers on the same row must take turns. The second one waits for a lock. And if two sessions wait for each other, that's a deadlock.

  • Two writers
  • One waits
  • Deadlock?

Waiting for a lock

Alice updates book one, and keeps her transaction open. Bob tries to update the same row, but only waits one second, thanks to lock timeout. Run it. Bob gives up, because Alice holds the lock.

locks.pypython
import psycopg

URL = "postgresql://postgres:postgres@localhost:5432/riverside"
alice = psycopg.connect(URL)   # first session
bob = psycopg.connect(URL)     # second session

alice.execute("UPDATE books SET stock = stock - 1 WHERE book_id = 1")

bob.execute("SET lock_timeout = '1s'")
try:
    bob.execute("UPDATE books SET stock = stock - 1 WHERE book_id = 1")
except psycopg.errors.LockNotAvailable as e:
    print("Bob:", e.diag.message_primary)
Output
Bob: canceling statement due to lock timeout

Avoiding trouble

Keep transactions short. Touch rows in the same order everywhere, so deadlocks can't happen. Set a lock timeout, so nothing waits forever. Postgres detects deadlocks and cancels one side, so retry when that happens.

keyvalue
Shorttransactions
Same orderno deadlocks
lock_timeoutno endless waits
Deadlockretry

Summary

Writers on the same row wait for locks, so keep transactions short and ordered. Next, a job queue with skip locked.

Key takeaways
  • Row locks
  • lock_timeout
  • Same order
Next up: FOR UPDATE SKIP LOCKED — a safe job queue