Mitigating Deadlocks in high concurrency environments
Concurrent 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.
Related posts
- Debugging deadlocks in Postgres
incident.io mediumAdeptPostgres 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.
- We replaced Redis with MySQL for inventory reservations—and it scaled
Shopify Engineering mediumAdeptShopify moved checkout inventory reservations from Redis to MySQL by modeling one row per sellable unit and using SELECT ... FOR UPDATE SKIP LOCKED, so concurrent checkouts grab different rows without contention while reservations and the inventory ledger share ACID transactions. Key fixes included a bounded pool of 1,000 rows per item/location with locked inline replenishment, a composite primary key that halved row locks, READ COMMITTED to avoid gap/supremum locks, consistent lock ordering to prevent deadlocks, and UNION ALL batching. The real throughput ceiling turned out to be database connection exhaustion from other checkout code, found by tagging SQL with caller comments and measuring hold time in ProxySQL; cleanup cut 50% of reads and 33% of transactions, and raising InnoDB thread concurrency removed the limit. Cutover used dual-write shadow mode with a kill switch and gradual pod-by-pod rollout.
- 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.
- One, Two, Skip a Few...
incident.io mediumAdeptPostgres sequences pre-log 32 values to the WAL (SEQ_LOG_VALS), so replicas see sequence state as it would be after a primary crash. When incident.io promoted a follower during a database upgrade, every per-organisation incident ID sequence jumped forward by up to 32, producing gaps like #INC-7 to #INC-39. Sequences guarantee monotonic values but not gap-free ones, and rollbacks can also skip numbers. The fix replaced them with a BEFORE INSERT trigger computing MAX(external_id)+1 per organisation, backed by an index, and the post recommends keeping external IDs separate from internal primary keys.
- 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.