Deadlocks happen when two or more database tasks wait for each other to finish, causing a standstill. Detecting and preventing deadlocks helps keep the database running smoothly without freezing.
Deadlock detection and prevention in PostgreSQL
Start learning this pattern below
Jump into concepts and practice - no test required
-- PostgreSQL automatically detects deadlocks and aborts one transaction. -- To prevent deadlocks, use consistent locking order and short transactions. -- Example: Lock rows in the same order in all transactions BEGIN; SELECT * FROM accounts WHERE id IN (1, 2) FOR UPDATE; -- perform updates COMMIT;
PostgreSQL detects deadlocks automatically and aborts one of the conflicting transactions.
Prevent deadlocks by accessing tables and rows in the same order in all transactions.
BEGIN; SELECT * FROM accounts WHERE id = 1 FOR UPDATE; SELECT * FROM accounts WHERE id = 2 FOR UPDATE; -- update balances COMMIT;
BEGIN; SELECT * FROM accounts WHERE id = 2 FOR UPDATE; SELECT * FROM accounts WHERE id = 1 FOR UPDATE; -- update balances COMMIT;
-- To detect deadlocks, check PostgreSQL logs or use: SELECT * FROM pg_stat_activity WHERE wait_event_type = 'Lock';
This example shows two sessions locking rows in opposite order, causing a deadlock. PostgreSQL detects it and aborts one transaction to resolve the deadlock.
-- Simulate deadlock detection -- Session 1 BEGIN; SELECT * FROM accounts WHERE id = 1 FOR UPDATE; -- Session 2 BEGIN; SELECT * FROM accounts WHERE id = 2 FOR UPDATE; -- Session 1 tries to lock account 2 SELECT * FROM accounts WHERE id = 2 FOR UPDATE; -- Session 2 tries to lock account 1 SELECT * FROM accounts WHERE id = 1 FOR UPDATE; -- PostgreSQL detects deadlock and aborts one transaction automatically.
Keep transactions short to reduce deadlock chances.
Use consistent locking order in your application code.
Check PostgreSQL logs for deadlock details if errors occur.
Deadlocks happen when transactions wait on each other in a cycle.
PostgreSQL detects deadlocks automatically and aborts one transaction.
Prevent deadlocks by locking resources in the same order and keeping transactions short.
Practice
Solution
Step 1: Understand transaction locking
Transactions acquire locks on resources to maintain data integrity.Step 2: Define deadlock
A deadlock occurs when transactions wait on each other in a cycle, causing indefinite waiting.Final Answer:
A situation where two or more transactions wait indefinitely for each other to release locks. -> Option DQuick Check:
Deadlock = cyclic waiting [OK]
- Confusing deadlock with syntax errors
- Thinking deadlock improves performance
- Mixing deadlock with backup locking
Solution
Step 1: Understand lock acquisition order
Acquiring locks in a consistent order prevents circular waiting.Step 2: Identify correct practice
All transactions should acquire locks on resources in the same order to avoid deadlocks.Final Answer:
Acquire locks on resources in the same order in all transactions. -> Option BQuick Check:
Consistent lock order = no deadlock [OK]
- Locking resources randomly
- Not locking resources at all
- Locking after commit
-- Transaction 1
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;
-- waits here
-- Transaction 2
BEGIN;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
-- waits hereWhat will PostgreSQL do when both transactions wait for each other?
Solution
Step 1: Identify deadlock scenario
Both transactions hold locks and wait for the other's lock, creating a cycle.Step 2: PostgreSQL deadlock detection
PostgreSQL automatically detects deadlocks and aborts one transaction to break the cycle.Final Answer:
PostgreSQL will detect the deadlock and abort one transaction automatically. -> Option CQuick Check:
Deadlock detected = abort one transaction [OK]
- Assuming infinite waiting without abort
- Thinking transactions merge automatically
- Believing both succeed without conflict
BEGIN;
LOCK TABLE orders IN ACCESS EXCLUSIVE MODE;
UPDATE customers SET name = 'Alice' WHERE id = 1;
-- Transaction 2 starts here
BEGIN;
LOCK TABLE customers IN ACCESS EXCLUSIVE MODE;
UPDATE orders SET status = 'shipped' WHERE id = 10;
What is the main issue causing the deadlock?
Solution
Step 1: Analyze lock order
Transaction 1 locks orders first, then updates customers; Transaction 2 locks customers first, then updates orders.Step 2: Identify circular wait
Each transaction waits for the other's locked table, causing deadlock due to different lock order.Final Answer:
Transactions lock tables in different orders causing circular wait. -> Option AQuick Check:
Different lock order = deadlock risk [OK]
- Blaming lock mode instead of order
- Thinking updating different tables causes deadlock
- Ignoring missing COMMIT as cause
Solution
Step 1: Understand deadlock prevention
Keeping transactions short reduces lock time; consistent lock order prevents cycles.Step 2: Apply best practice
Always lock inventory first, then sales, in all transactions to avoid deadlocks.Final Answer:
Keep transactions short and acquire locks on inventory then sales in all transactions. -> Option AQuick Check:
Short transactions + consistent lock order = deadlock prevention [OK]
- Locking in inconsistent order
- Avoiding transactions entirely
- Using long transactions increasing lock time
