← Blog

November 17, 2026 ·

Postgres Is Your Job Queue Until It Isn't

For seed-stage teams running long LLM and geospatial jobs, Postgres is the right queue. Lease locking, heartbeats, and idempotent handlers let the database coordinate work without adding a broker to operate. A dedicated broker becomes the right choice when production evidence shows that throughput, fan-out, payloads, or failure isolation require a different design.

Why a Postgres-backed queue is the right default at seed stage, not a fallback

Transactional enqueue is the strongest reason to start here. A queue built on SELECT ... FOR UPDATE SKIP LOCKED can share a transaction with the business writes that create its work. The business record and its job commit together. That prevents both a record without a job and a job for a record that never committed. An external queue cannot share that database transaction, so it needs compensating reconciliation to close the dual-write gap.

Each additional broker must also be paid for, kept current, backed up, monitored, and understood by whoever is on call. That work continues after the initial integration is done, and a small team has less time to handle it. Managed Postgres lets that team use the infrastructure it already needs for its business records.

Teams shipping on managed Postgres can spend engineering time on the product while others build infrastructure their workloads do not yet require. Long-running inference and geospatial processing strengthen this case because executing the work usually costs more than dispatching it. The architecture deserves to be judged against that workload, rather than against an assumed future need for a broker.

How the mechanism actually works — lease locking, claim tokens, and the reaper

SKIP LOCKED lets a claim query pass over rows another transaction has already locked. It deliberately presents an inconsistent view of the table. That is appropriate for distributing available jobs, but not for reports or balances that need a complete view. The concurrency guarantee applies to the claim transaction, which must mark its rows and commit immediately.

After that commit releases the database lock, the worker holds a lease. The row asserts that the job belongs to that worker until lease_expiry. This distinction is essential for long-running inference calls and tile-rendering jobs, where a short claim transaction and a generous lease avoid holding a transaction open throughout the work. A connection failure releases a held lock. A lease remains in the table so that a later sweep can recover it.

The worker ID alone does not establish ownership safely. Every claim needs a fresh UUID token identifying that particular claim, so a stale worker cannot overwrite a newer claim when it returns. Heartbeats keep the lease alive while legitimate work goes on. The token distinguishes the current claim from an earlier attempt by the same worker, rather than treating worker identity as proof that its result is still authoritative.

Recovery requires a scheduled reaper that returns expired leases to the ready state and applies exponential backoff. Attempts must increase when a job is claimed, because a worker that has crashed cannot record its own failure. Even with those protections, a worker can finish its work and crash before marking the job done. Delivery can therefore repeat, just as it can with SQS and BullMQ. Idempotent handlers are a correctness requirement.

The schema and index decisions that make the claim query fast in production

Before deployment, the technical owner should audit whether the schema describes an operable workflow. It needs stable IDs, a type and schema version, bounded payloads or payload references, status, schedule, priority, attempt policy, lease fields, an idempotency key, and timestamps. A JSON blob and a processed boolean are insufficient. They leave the system without the explicit state needed to schedule, recover, and inspect jobs reliably.

A partial index on run_at where status = 'queued', or the equivalent ready state, limits the indexed working set as historical jobs accumulate. The eligible status, ordering by run time and priority, and stable tie-breaker must align with the hot path. SKIP LOCKED changes how contention is handled without fixing an unbounded sequential scan.

Lease settings need to be checked as closely as indexing. A useful production heuristic is roughly three times the p99 processing time, with enough room for the slowest legitimate task. That interval should belong to the task class. A fast HTTP fetch, a browser-rendered tile, and a long LLM completion need different windows, and a global lease makes unrelated workloads depend on one timing assumption.

Priority also belongs in an explicit column. Changing it is an UPDATE, which allows a breaking-news source or a high-priority geospatial job to move ahead of a batch without introducing a separate coordination system. That flexibility is a practical benefit of keeping workflow state in the database. These decisions are inexpensive before launch and much harder to repair while workers compete for a growing backlog.

The three failure modes that surface only under production load

Table bloat is the first failure mode. A queue with only a few hundred pending jobs can contain hundreds of thousands of dead row versions, so a short queue can still be slow to claim. The query has to pass over dead index entries and dead heap tuples to get to live pending rows. The Postgres-native remedy is aggressive autovacuum tuning for the jobs table, a retention window that moves completed jobs into an archive, and monitoring dead tuple counts.

Vacuum cannot solve every accumulation of dead tuples by itself. Under MVCC, it cannot remove a tuple that remains visible to an open transaction. A single long analytics query can therefore pin the horizon while a seemingly unrelated queue degrades. The two workloads share a database constraint. Routing long-running reads to a replica, or enforcing a statement timeout on the primary, prevents analytics from indefinitely obstructing that cleanup.

The third failure mode occurs when tasks take a different amount of time but the lease stays the same. Adding an LLM completion step to a pipeline previously limited to an HTTP fetch can make healthy workers outlive their assigned window. The reaper then reclaims work that is still progressing. Duplicate execution, higher attempt counts, and what look like endless retries can follow even while workers finish the work successfully in parallel. Task-specific lease intervals remove that coupling between fast and slow paths.

None of these symptoms alone establishes the need for a broker. Each points to a particular operational or configuration defect with a remedy inside the Postgres design. That distinction is important when diagnosing rising claim times or retry counts. Replacing the queue before finding the cause can turn a small repair into a larger infrastructure project while leaving it unclear why the original system slowed.

The specific production signals that make a dedicated broker the right next move

Sustained growth in lock acquisition latency is the leading throughput signal. When claim times rise under continued load, the queue may be approaching its practical concurrency limit for simple jobs. That limit is not the same worker count for every queue. For LLM and geospatial work, execution is usually the bottleneck, so rising claim latency before worker saturation should first prompt investigation of bloat and MVCC horizon pinning. A persistent claim bottleneck after those causes are ruled out is evidence for a dedicated broker.

Fan-out presents a different boundary, independent of raw throughput. SKIP LOCKED assigns a claim to one worker rather than broadcasting an event to independent consumers. If a webhook delivery system or multi-tenant notification pipeline needs the same event delivered to several consumers, the requirement has become streaming or pub-sub. A work-claim table is the wrong model for that requirement.

Payload pressure can also justify a change. Large payloads in the jobs table compound bloat and slow the claim scan, so the interim remedy is to store references and retrieve payloads separately. If large, numerous payloads are intrinsic to the workload, a broker with native blob handling can remove structural pressure from the database. The distinction is between correcting payload placement and supporting a workload whose normal operation continually creates that pressure.

A poison job that repeatedly crashes workers still consumes claim cycles and bloat budget until it reaches its dead-letter state. Native DLQ routing and per-queue isolation can remove that coupling when isolation becomes a firm requirement. Before implementation review, the decision record should answer four questions covering observed volume and latency, transactional enqueue, payload size, and required failure isolation. Those answers provide a defensible architectural boundary rather than a vague declaration that the system is getting complex.

What LISTEN/NOTIFY is actually good for — and what it is not

LISTEN/NOTIFY reduces wake-up latency for idle workers. It does not replace the jobs table. Notifications disappear while a listener is disconnected, so a restart during a burst can lose every notification sent during the interruption. Commits that issue NOTIFY also take a global lock that serializes those notification-bearing commits, adding contention to a high-write enqueue path. Commits without NOTIFY are not subject to that serialization.

PgBouncer does not support LISTEN in transaction pooling mode, which makes that common production configuration another constraint on the notification layer. The correct architecture keeps jobs in the table, claims them with SKIP LOCKED, and uses NOTIFY only to tell an idle worker to check before its next polling interval. Polling still picks up work when wake-ups are missed.

Running this in production — the operational checklist a technical owner should own

For a fractional CTO or technical lead inheriting this design, the operational checklist starts with the claim path. Use EXPLAIN before the first production deployment to check that the partial index fits the eligible status, run time, priority, and a stable tie-breaker. Document the reasoning for each task class’s lease interval in the schema migration. Include an idempotency key on the jobs table to catch duplicate producer submissions before they reach workers. Producer deduplication does not replace idempotent handlers.

Cleanup needs an explicit owner and schedule. Tune autovacuum for the jobs table rather than assuming defaults suit its insert and update churn. Compare dead tuple counts with pending queue length, because a dead tuple count that rises while the queue stays the same size is an early sign of bloat. Use a retention policy to decide when to archive or delete completed and dead-lettered jobs. Indefinite accumulation is not an operational policy.

Observability should treat queue depth, claim latency, lease expirations, and dead-letter rate as first-class metrics. Plain SQL against the jobs table can show those workflow states without a separate reporting system. Alert on backlog and an upward claim-latency trend. Depth shows how much work is waiting, while claim latency can show that dispatch is slowing down before users feel it.

Run the reaper on a schedule, rather than triggering it only when workers are functioning. Maintain a reconciliation query for jobs still running past their maximum lease age, including those hidden by excessively generous lease settings. These checks make recovery an owned process rather than an assumption embedded in the worker code.

An engineer-CTO such as Steve Johnson, whose work includes taking fast-built products onto managed infrastructure without a default rewrite, is one option for owning that review. The technical owner’s responsibility is to maintain the claim path, cleanup, observability, and recovery, and to recognize when measured requirements justify a different system. That accountability separates infrastructure built to run from infrastructure built to demo.