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-short-transactions.md
1---2title: Keep Transactions Short to Reduce Lock Contention3impact: MEDIUM-HIGH4impactDescription: 3-5x throughput improvement, fewer deadlocks5tags: transactions, locking, contention, performance6---78## Keep Transactions Short to Reduce Lock Contention910Long-running transactions hold locks that block other queries. Keep transactions as short as possible.1112**Incorrect (long transaction with external calls):**1314```sql15begin;16select * from orders where id = 1 for update; -- Lock acquired1718-- Application makes HTTP call to payment API (2-5 seconds)19-- Other queries on this row are blocked!2021update orders set status = 'paid' where id = 1;22commit; -- Lock held for entire duration23```2425**Correct (minimal transaction scope):**2627```sql28-- Validate data and call APIs outside transaction29-- Application: response = await paymentAPI.charge(...)3031-- Only hold lock for the actual update32begin;33update orders34set status = 'paid', payment_id = $135where id = $2 and status = 'pending'36returning *;37commit; -- Lock held for milliseconds38```3940Use `statement_timeout` to prevent runaway transactions:4142```sql43-- Abort queries running longer than 30 seconds44set statement_timeout = '30s';4546-- Or per-session47set local statement_timeout = '5s';48```4950Reference: [Transaction Management](https://www.postgresql.org/docs/current/tutorial-transactions.html)51