P50 28s Analyze →
↩ All field notes
Querk · Field notes

Postgres as a Queue: The Locking Hotspot Pattern

Published November 24, 2026 · Querk — Postgres review pipeline

Why SELECT … FOR UPDATE Becomes a Hotspot

PostgreSQL implements row‑level locking by marking tuples as “locked for update” when a transaction executes `SELECT … FOR UPDATE`. Each worker that pulls a job from a queue table must acquire this lock before it can mark the row as claimed. Under low throughput the lock acquisition time is negligible, but once the arrival rate exceeds the service rate the lock manager becomes a serialization point. The lock queue grows, and every new worker spends an increasing fraction of its latency waiting for the previous transaction to release the row.

How Row‑Level Lock Contention Escalates

When many sessions contend for the same hot rows, PostgreSQL’s lock manager must maintain a wait‑for graph for each blocked transaction. The graph is traversed on every lock request to detect deadlocks, and the deadlock detector runs at a fixed interval. As the number of concurrent waiters rises, the detector’s work grows quadratically, adding CPU overhead that further slows lock release. In practice this manifests as a sharp latency inflection around a few hundred jobs per second, after which throughput plateaus and tail latency spikes dramatically.

Mitigation Strategies

1. Batch claiming – Instead of locking a single row per worker, claim a small batch (e.g., `LIMIT 10`) in a single `SELECT … FOR UPDATE SKIP LOCKED`. This reduces the number of lock acquisitions by an order of magnitude.

2. Partition the queue – Split the logical queue into multiple physical tables or hash‑partitioned partitions. Workers target a specific partition, turning a single hotspot into many independent lock domains.

3. Advisory locks – Use `pg_try_advisory_xact_lock` on a job identifier rather than row locks. Advisory locks are lighter weight because they do not involve tuple visibility checks.

4. Observe lock wait graphs – Tools such as Querk can surface the wait‑for graph in real time, helping teams pinpoint the exact statements that dominate lock time.

When to Move Beyond a Table‑Based Queue

If the workload consistently exceeds the throughput ceiling of a partitioned, batch‑claimed design, the architectural cost of maintaining a relational queue outweighs its simplicity. At that point a dedicated message broker (e.g., Kafka, RabbitMQ, or a cloud‑native queue service) provides horizontal scalability, built‑in back‑pressure, and richer delivery semantics without the lock‑contention ceiling inherent to a single‑writer table. The migration path typically involves dual‑writing during a cut‑over window, then retiring the queue table once the new pipeline proves stable.

Paste your slowest query — 3 free reviews, no signup. Index DDL, rewrites, write-path impact, and a verification command back in ~30 seconds. Analyze a query →