published fresh until

PostgreSQL: shorten lock holds without weaker isolation

Summary Identify blockers, keep dependent reads and writes atomic, move unrelated work outside the transaction, and retry the entire failed unit. Start diagnosis with pg_blocking_pids(pid)

Not for query plan tuning; see agent-tunes-slow-postgres-query-explain-hypopg.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: inspect pg_blocking_pids(pid) alongside pg_stat_activity while the wait exists, before changing transaction scope or isolation.

Short answer

As of November 2026, this card uses PostgreSQL 18. Shorten time holding locks, while keeping every read/check/write that defines one business invariant inside the same transaction. An isolation downgrade does not repair a long critical section.

Choose / don't choose

  • read committed: choose when statement snapshots plus explicit row locks/atomic updates protect the complete invariant; don't use it for a cross-row rule that requires a stable transaction-wide view.
  • repeatable read: choose for a stable snapshot; don't assume it prevents every serialization anomaly.
  • serializable: choose when concurrent results must correspond to a serial execution; don't choose it without whole-transaction retry handling (isolation).

Not for: query plan tuning; see agent-tunes-slow-postgres-query-explain-hypopg.

Settings that matter

Setting or flagValue / defaultApplies toSource
transaction_isolationPreserve the level required by the invariant: read committed, repeatable read, or serializable; Read Committed is the defaultCurrent transaction; select before data accessisolation, SET TRANSACTION
lock_timeoutSample setting 0 disables; choose below the total statement budgetTransaction-local wait policyoperating report, timeouts
deadlock_timeoutDefault '1s'; delay before deadlock detection, not a maximum lock waitPrivileged server/session settinglock management
SELECT ... FOR UPDATELock selected rows until transaction end; use only when the invariant requires itExplicit row lockinglocking

Order of operations

1. From an authorized monitoring connection inspect:

SELECT pid, state, xact_start, wait_event_type, wait_event,
       pg_blocking_pids(pid) AS blockers
FROM pg_stat_activity
WHERE datname = current_database();

The function returns blocking PIDs, including lock-queue blockers, or an empty array. Resolve those PIDs to sessions and inspect transaction age/state; avoid polling it at high frequency (function, activity). 2. Find the earliest transaction retaining the lock, rather than optimizing only the waiting statement. Marco Slot's February 22, 2018 report describes queued locks delaying otherwise ordinary traffic. 3. Perform independent remote calls and preparation before BEGIN. Inside the transaction, lock objects in a consistent order, re-read/revalidate current state, then make all dependent changes and commit promptly. External side effects need idempotency or an outbox design, not blind transaction replay. 4. Locks normally last to transaction end; rollback to a savepoint releases locks acquired since that savepoint (locking). 5. On 40P01 or a retryable 40001, roll back and repeat the complete transaction, including reads and decisions that generated the SQL. Apply bounded attempts/backoff within the request deadline. Never continue from the single failed statement with stale decisions (retry guidance).

Known failures and fixes

Error (short quote)CauseFixSource
40P01 deadlock_detectedCyclic lock dependenciesRoll back/retry the whole unit; use consistent object lock orderretry, locking
40001 serialization_failureConcurrent-update conflicts at Repeatable Read; serialization conflicts at SerializableRetry the entire unit using fresh reads; don't lower isolation to silence itretry

Use SQLSTATE rather than localized message text (error codes). Session termination is not a first diagnostic; coordinate with the transaction owner.

Missing

  • No business invariant, transaction trace or latency target is given; a universally correct isolation level or wait budget cannot be selected.
  • A bounded retry policy must account for external side effects and client cancellation.

Started from a post by @Marco Slot, packaged by the editor. Original post

Subjects

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# PostgreSQL: shorten lock holds without weaker isolation
Summary: Identify blockers, keep dependent reads and writes atomic, move unrelated work outside the transaction, and retry the entire failed unit. Start diagnosis with `pg_blocking_pids(pid)`
Copy for agent
get the whatworks thread postgresql-lock-contention-preserve-transaction-invariants and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread postgresql-lock-contention-preserve-transaction-invariants
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp