Debugging deadlocks in Postgres
Postgres deadlocks come from transactions acquiring locks in inconsistent orders, and the main fix is to restructure transactions so they always lock resources in the same sequence. Explicit FOR UPDATE or advisory locks, narrower FOR NO KEY UPDATE locks, and jittered retries also work, but they all reduce parallelism. In a real case at incident.io, two seemingly identical bulk upserts in a Catalog sync deadlocked. Postgres acquires row locks one at a time during a multi-row INSERT ... ON CONFLICT, and the rows were randomly ordered after passing through a Go map, so sorting the rows before upserting eliminated the deadlock.
Related posts
- When upserts don’t update but still write: Debugging Postgres performance at scale
Datadog Engineering mediumAdeptA Postgres `INSERT ... ON CONFLICT DO UPDATE ... WHERE` upsert still locks the conflicting row even when the WHERE clause blocks the update. That lock assigns a transaction ID and writes a Heap LOCK record plus a COMMIT to the WAL, forcing a WAL sync per query. Datadog's host last-seen tracker hit this: at 500 upserts/s it doubled write IOPS against a gp3 disk limit of roughly 1,000 fsyncs/s, which made the planned 25,000/s impossible. Using pg_walinspect and an lldb backtrace to find the cause, the team switched to a CTE that does `INSERT ... ON CONFLICT DO NOTHING` followed by a conditional UPDATE, accepting a minor race condition in exchange for zero WAL writes on no-op calls and HOT updates otherwise.
- Mitigating Deadlocks in high concurrency environments
Shopify Engineering mediumAdeptConcurrent batch upserts into an InnoDB table keyed by a sequential id can deadlock even when processes touch different rows, because the gap locks taken on unique-key collisions span neighbouring index entries that other processes also need. Shopify mitigated this by changing the primary key to a composite (account, id), so rows are physically clustered per account and each per-account ETL process's gap locks stay within its own range. An extra unique index on id preserves existing joins with no application changes. The fix let them remove artificial delays added to avoid deadlocks and significantly increased import job throughput.
- PostgreSQL Stories: A simple query with a big problem
Render mediumAdept
A seemingly simple indexed join with LIMIT 1 ran for over four hours on Render's staging PostgreSQL, holding a lock that blocked CREATE OR REPLACE VIEW migrations and stalled deploys. The team traced it by watching oldest-transaction age, querying pg_stat_activity for long-running active queries, and using pg_blocking_pids() to map which backends blocked which migrations. The culprit was an engineer's ad-hoc psql query: pressing Ctrl+C in psql stopped reading results but left the server-side query running. Killing the backend fixed it immediately. Key lessons are to keep transactions short, because they block locks, autovacuum and risk XID wraparound, and to set application_name and inspect usename so queries can be traced to their source.
- How savepoints quietly throttled our Postgres queue
incident.io hardMasterUsing a SAVEPOINT per tick in a Postgres-backed job queue made every locked row carry a MultiXact ID in xmax. FOR UPDATE SKIP LOCKED scans then contended on the LWLock-guarded pg_multixact cache, so adding workers made acquisition slower. incident.io fixed it by moving the queue to a slim escalation_jobs table, replacing subtransactions with a claimed_until lease (one transaction per tick), keeping claimed_until unindexed with fillfactor 85 to allow HOT updates, and running one dispatcher goroutine per pod that feeds workers over a channel. Together these raised peak escalation capacity 3.5x, at the cost of up to 10 seconds of delay if a pod dies mid-claim.
- Navigating PostgreSQL Locks with Neon and Atlas
Neon mediumAdept
Adding a UNIQUE constraint or setting a column NOT NULL in Postgres triggers a full table scan under an ACCESS EXCLUSIVE lock, which blocks all reads and writes and can take down an API on large tables. The safer sequences are CREATE UNIQUE INDEX CONCURRENTLY followed by ADD UNIQUE USING INDEX, and a NOT VALID CHECK constraint followed by VALIDATE before SET NOT NULL. To catch such migrations automatically, a GitHub Actions pipeline runs Atlas's migrate lint (check PG105) on pull requests. It then applies the migration to a Neon branch cloned from production, with a 10s statement_timeout hook, so long-locking migrations fail the build before deployment.