Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Postgres performance optimization and best practices guide maintained by Supabase
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/lock-deadlock-prevention.md
1---2title: Prevent Deadlocks with Consistent Lock Ordering3impact: MEDIUM-HIGH4impactDescription: Eliminate deadlock errors, improve reliability5tags: deadlocks, locking, transactions, ordering6---78## Prevent Deadlocks with Consistent Lock Ordering910Deadlocks occur when transactions lock resources in different orders. Always11acquire locks in a consistent order.1213**Incorrect (inconsistent lock ordering):**1415```sql16-- Transaction A -- Transaction B17begin; begin;18update accounts update accounts19set balance = balance - 100 set balance = balance - 5020where id = 1; where id = 2; -- B locks row 22122update accounts update accounts23set balance = balance + 100 set balance = balance + 5024where id = 2; -- A waits for B where id = 1; -- B waits for A2526-- DEADLOCK! Both waiting for each other27```2829**Correct (lock rows in consistent order first):**3031```sql32-- Explicitly acquire locks in ID order before updating33begin;34select * from accounts where id in (1, 2) order by id for update;3536-- Now perform updates in any order - locks already held37update accounts set balance = balance - 100 where id = 1;38update accounts set balance = balance + 100 where id = 2;39commit;40```4142Alternative: use a single statement to update atomically:4344```sql45-- Single statement acquires all locks atomically46begin;47update accounts48set balance = balance + case id49when 1 then -10050when 2 then 10051end52where id in (1, 2);53commit;54```5556Detect deadlocks in logs:5758```sql59-- Check for recent deadlocks60select * from pg_stat_database where deadlocks > 0;6162-- Enable deadlock logging63set log_lock_waits = on;64set deadlock_timeout = '1s';65```6667Reference:68[Deadlocks](https://www.postgresql.org/docs/current/explicit-locking.html#LOCKING-DEADLOCKS)69