Should a PostgreSQL job queue replace a separate broker?
A team that needs background jobs and already runs PostgreSQL can often start with a database-backed queue. FOR UPDATE SKIP LOCKED lets several workers claim different rows without waiting on each other, and LISTEN/NOTIFY can wake idle workers instead of having them poll on a fixed timer. Whether that is enough depends on job volume, ordering requirements, how long finished jobs must be kept, and what happens when a worker fails mid-job. Those four answers should drive the decision, not the fact that a broker is an extra system to run.
The strongest argument for a PostgreSQL queue is transactional enqueueing. A job inserted in the same transaction as the business write it belongs to commits or rolls back with that write, so the application never records an order without its fulfilment job or the reverse. Reaching the same guarantee with a separate broker usually means an outbox table, a relay process and an idempotent consumer. Note that the job table still needs the same backup, monitoring and upgrade care as the rest of the database, so the operational saving is smaller than it first looks.
SKIP LOCKED needs a careful reading. PostgreSQL's SELECT documentation states that it gives an inconsistent view of the data, so it suits a queue-like table that workers claim from and update, and it is not a general-purpose locking tool for application queries. Confirm with your own design that no job depends on a consistent snapshot across several rows, and test the claim query under concurrent workers before committing to the design.
Which queue design fits which workload
This design keeps every job as a row in one table with a status column such as queued, running, done or failed. Workers claim a job with a short transaction that selects a queued row using FOR UPDATE SKIP LOCKED, sets its status to running and records a lease or attempt count. It suits teams that want job history, easy retries and simple queries against finished work, and it works well when job volume stays moderate. Each job produces several row updates over its life, so the table accumulates dead tuples that autovacuum must clear.
- Write pattern: every claim and completion is an UPDATE, so each job creates multiple dead row versions.
- Vacuum behavior: autovacuum has to keep pace with the update rate, and a partial index on queued rows helps the claim query stay small.
- Retention: finished rows need a scheduled delete or archive step, otherwise the table grows and the claim index gets slower.
- Lease handling: a crashed worker leaves a row in running state, so you need a timeout that returns stale jobs to the queue.
- Confirm in testing: measure dead tuple counts and autovacuum runs under your peak job rate, and check claim latency after a week of retained history.
Before committing to this design, load-test it with your real job mix and confirm that autovacuum settings for the queue table keep up.
In this design a worker claims a job by deleting it from the queue table with DELETE ... RETURNING, usually combined with SKIP LOCKED in a subquery. The job row leaves the table as soon as it is taken, so the queue holds only pending work. It suits high-throughput, fire-and-forget tasks where job history lives elsewhere, such as in application logs. The trade-off is that a failed job is gone unless the worker writes it to another table in the same transaction.
- Write pattern: one DELETE per job, with no separate completion update, which produces fewer dead tuples than a status column.
- Vacuum behavior: deleted rows still leave dead tuples, so vacuum work scales with job volume, but the live table stays small and the claim index stays compact.
- Failure handling: a worker that crashes after the delete but before its side effects complete loses the job, so the work itself must be idempotent or the claim must share a transaction with the effect.
- Retries: retries need an explicit reinsert into the queue, which you should design and test.
- Confirm in testing: kill workers mid-job and confirm that no job is lost or executed twice in ways your business logic cannot tolerate.
This design is only safe when you have verified what happens to a job if the worker fails at each step.
This design splits the queue into partitions, for example by day, hour or a hash of the queue name, so that old jobs can be removed by dropping or detaching a partition rather than deleting rows. Workers still claim with SKIP LOCKED, but the active partition is the only one that receives writes and updates. It suits workloads with large job volume and a fixed retention window, where bulk deletes would otherwise create heavy vacuum load. The design adds operational work: someone must create future partitions and drop old ones on schedule.
- Write pattern: writes concentrate in the current partition, and older partitions become read-only and stable.
- Vacuum behavior: vacuum works on smaller tables, and dropping an expired partition removes its dead tuples without a per-row delete.
- Partition management: a scheduled job must create upcoming partitions before they are needed and handle late-arriving jobs.
- Key constraints: unique or primary keys must include the partition key, which affects how you identify jobs.
- Confirm in testing: verify that claim queries prune to the active partitions, and test what happens when the partition job falls behind.
Review the partition plan with your DBA before adopting it, because a missed partition creation can stall the whole queue.
LISTEN/NOTIFY is not a storage design. It lets a producer send a signal to idle workers so they stop polling and claim work sooner. Workers still read jobs from one of the table designs above, so the signal layers on top of polling rather than replacing it. Notifications are delivered only to sessions connected at the time, and the payload must stay under 8000 bytes in the default configuration, so it should carry a job identifier, not the job itself. It suits queues where latency matters and the team can accept that polling remains the safety net.
- Write pattern: each NOTIFY is a small in-memory event, but it is sent inside the transaction and consumes connection resources.
- Vacuum behavior: NOTIFY adds no table bloat by itself, so the vacuum profile is that of whichever table design you chose.
- Missed signals: a worker that is disconnected misses notifications, so a periodic poll must still run.
- Connection pooling: LISTEN needs a session that stays attached, which conflicts with transaction-mode pooling, so confirm how your pooler handles it.
- Confirm in testing: drop a listener connection during load and confirm that jobs still run within your polling interval.
Treat the notification as a hint and keep polling as the source of truth.
Using LISTEN/NOTIFY for wake-ups without trusting it for delivery
LISTEN/NOTIFY should wake workers up, not carry the work. NOTIFY gives simple interprocess communication between sessions connected to the same database, so a producer can tell a waiting worker that a row has arrived. The notification is a hint. The job itself lives in the queue table, and the worker must query that table after it wakes. A design that treats the notification as the message will lose jobs whenever a worker is disconnected, restarting or busy at the moment the signal is sent. Plan for a periodic poll as the safety net, and let the notification shorten the wait between polls.
Keep the payload small. In the default configuration the payload must be shorter than 8000 bytes, so the producer should send a job identifier such as the primary key, not the job body. The worker then reads the row with a SELECT ... FOR UPDATE SKIP LOCKED statement, which is where claiming happens. Decide the payload format now, because changing it later touches every producer and consumer. Confirm the exact limit against your PostgreSQL version and build, and test with a payload close to the limit so that an oversized message fails in staging rather than in production.
Pooled connections change how this behaves. A LISTEN only applies to the session that issued it, and a transaction-mode pooler can hand a different server connection to the next transaction, so a listener may silently stop receiving signals. Notifications are also not delivered to a session that is not listening when they are sent. Before relying on this pattern, check with the pooler in use (for example, PgBouncer) how it handles LISTEN in each pooling mode, and whether listeners need a dedicated direct connection. Test that a worker wakes after a pooler restart and after a database failover, and keep the polling interval as the backstop either way.
How queue tables create vacuum pressure and how to contain it
A job queue table churns through rows faster than most application tables: every job is inserted, claimed, updated and deleted. The cards below cover the mechanisms that turn that churn into bloat and the containment steps that keep cleanup ahead of the workload.
Dead tuples from deletes and status updates
Each claim is typically a status update, and each completion is a delete, so a busy queue leaves dead row versions behind on every pass. Inserts alone create no dead tuples, which is why the churn grows with throughput rather than with table size. Check how many rows change state per minute and compare the dead tuple count against the live row count over time. A table where dead rows keep climbing between autovacuum runs needs attention before the queue slows.
SELECT docsAutovacuum tuned per queue table
Autovacuum settings can be set per table, so a hot queue table does not have to wait for thresholds sized for a quiet reference table. Lower the scale factor on the queue table and review how often it actually runs under peak load. Test the settings on a copy of production traffic first, because more frequent vacuum work also consumes I/O that the workers need. Record the chosen values in version-controlled migration files so they survive a rebuild.
- Major version support
- 5 years
Long transactions blocking cleanup
Vacuum can only remove dead rows that no open transaction can still see. A single long-running reader, an idle transaction left open by a worker, or a stuck consumer holding a snapshot can stop cleanup on the queue table for the whole cluster. Watch for sessions in the idle in transaction state and set idle transaction timeouts where your application allows it. Make sure worker code commits promptly after each claim rather than holding a transaction while the job runs.
Index bloat on the claim index
Queries that claim the next job usually depend on a partial or composite index over status and run time. Every status update writes a new index entry, so the claim index can grow faster than the table and slow the FOR UPDATE SKIP LOCKED lookup as it fills with dead entries. Compare index size with the live row count and rebuild the index during a quiet window when it balloons. Keep the index narrow so updates are more likely to be heap-only.
Partitioning to drop old rows
Completed and failed jobs are usually kept for a short period for audit or debugging, then deleted in bulk. Range partitioning by creation time or list partitioning by final state lets you detach or drop whole partitions instead of deleting millions of rows, which avoids creating dead tuples at all. Confirm that the partition key appears in every unique constraint and that the claim query still touches only the active partition. Decide the retention period with the team that owns the job records.
High availability docsMonitoring dead tuples and transaction age
Track dead tuple counts, the time of the last autovacuum on each queue table, and the age of the oldest open transaction in the cluster. Alert when autovacuum falls behind on the queue tables or when the oldest transaction stops advancing. Set thresholds from your own baseline during load tests, not from values copied from other systems. Review these metrics after every deployment that changes job volume or worker concurrency.
Building the queue in PostgreSQL step by step
This sequence takes a team from an empty database to a job queue that workers can claim from safely, wake up promptly, retry on failure and keep healthy under load.
Define the jobs table and claim index
The application team defines a jobs table with an ID, a queue name, a status, a payload, a run-at timestamp, an attempt counter and timestamps. Add a partial index on the columns the claim query filters and orders by, covering only rows that are waiting to run. Keep the payload small and store large inputs in other tables or object storage, so rows stay compact and vacuum has less work. Done when the schema migrates cleanly in a non-production environment and EXPLAIN on a sample claim query shows the index being used once the table holds realistic row counts.
Write the claim query with SKIP LOCKED
Write the claim as a single statement that selects waiting rows with FOR UPDATE SKIP LOCKED, applies a bounded LIMIT and updates the claimed rows to a running state in the same transaction. Workers that find rows locked by another worker skip them rather than wait. PostgreSQL's documentation notes that SKIP LOCKED gives an inconsistent view of the data, so use it only for queue-like access and do not reuse the query for general reporting. Done when two or more concurrent test workers claim disjoint sets of jobs with no duplicates across repeated runs.
Add retry and lease columns
Add a lease expiry column that records when a claimed job becomes eligible again, and a rule that a crashed worker's job is reclaimed once its lease passes. Add a maximum attempt count and move jobs that exceed it to a failed state or a dead-letter table for review. Set the next run time with backoff logic in the application, so retries do not flood the queue. Done when a test that kills a worker mid-job shows the job reappearing after its lease and stopping at the attempt limit.
Add the NOTIFY trigger with an ID-only payload
Add an AFTER INSERT trigger or an application-side call to pg_notify that sends the job ID or queue name, never the full payload. NOTIFY's default payload limit is 8000 bytes, and a larger payload fails, so keep the message to an identifier and have workers read the row. Workers LISTEN on the channel and still poll on an interval, because notifications are a wake-up signal and can be missed while a session is disconnected. Done when inserting a job wakes a listening worker within the test window and stopping that worker's connection still leads to the job being picked up by polling.
Configure per-table autovacuum
Queue tables churn heavily because every job is inserted, updated and deleted or archived, so set autovacuum thresholds for the jobs table individually rather than relying on the global defaults. Lower the scale factor for that table so vacuum runs more often in smaller passes, and consider a separate archive table for completed jobs so the hot table stays small. Ask your DBA to review the settings against the instance's I/O capacity. Done when table statistics show vacuum completing regularly and dead tuple counts staying bounded during a sustained test run.
Load-test claim throughput and vacuum behavior
Run a load test with the expected number of producers and workers, sustained for long enough to exercise vacuum cycles, and measure claim latency, queue depth, dead tuple growth and lock waits. Include a test where the queue is backlogged and a test where workers are added and removed. Record the results against the throughput your team needs, and agree the pass criteria before the test starts. Done when the results are written down, any bottleneck has a documented fix, and the team has decided in writing whether PostgreSQL meets the requirement or a message broker should be considered.
How producers, workers and the broker decision path fit together
The diagram starts with a producer that inserts a job row in the same transaction as its business write, so the job exists only if that write commits. A NOTIFY is sent on commit to wake listening workers, which then claim rows with FOR UPDATE SKIP LOCKED so that competing consumers never take the same job. The lower branch asks whether ordering, throughput, retention or fan-out needs have outgrown the table, and if so, the design moves toward a message broker such as Apache Kafka. Check the branch questions against real load before choosing a path.
Producer, wake-up, claim and the decision to move to a broker.
Security and operational risks of a database-backed queue
A queue in PostgreSQL puts job payloads, worker credentials and queue throughput in the same database that serves the application. The cards below cover the risks that tend to surface after launch, and each one names a decision to make before workers go live.
Sensitive payloads and table grants
Job rows often carry customer identifiers, email addresses, tokens or document references, so the queue table holds data with the same sensitivity as the application tables it feeds. Check who can SELECT, INSERT and UPDATE the table, and whether dead rows left by completed jobs keep that data on disk until vacuum removes them. Store references to sensitive records instead of the records themselves where the design allows it.
Least-privilege worker roles
A worker needs to claim a row, update its status and write results, and nothing else. Create a dedicated role for workers with grants limited to the queue table and the tables their handlers write, and keep schema change rights with a separate migration role. Confirm which authentication method each worker role uses and how credentials are rotated, using the PostgreSQL authentication methods as the starting reference.
Authentication methodsBackup and restore of in-flight jobs
A point-in-time restore returns the queue to an earlier state, so jobs claimed or completed after the recovery target may run twice or be lost from the application's point of view. Decide whether handlers are idempotent, and document how operators reconcile jobs that were in progress at the restore point. Test this with a restore drill on a copy of production, since the replay behavior only shows up when the queue is restored.
Continuous archiving docsConnection limits shared with the application
Workers that hold connections open while they poll or process jobs compete with the web application for the server's connection limit. A pool of many workers can exhaust connections and stall user requests. Size the worker pool against the server's connection budget, consider PgBouncer for the application side, and keep long-running job transactions short so they do not hold row locks or block vacuum.
PgBouncer sitePoison jobs and retry handling
A job that always fails will be claimed, fail and be claimed again, consuming worker capacity and filling logs. Define a maximum attempt count, a backoff rule and a dead-letter state where failed jobs wait for review. Record the last error and attempt number on the row so operators can filter failures without reading application logs.
Audit of enqueue and alteration
Anyone who can insert or update a job row can trigger work the application did not intend, so enqueue rights are a control point. Decide which roles may enqueue, which may cancel or edit pending jobs, and whether those changes are logged. Use PostgreSQL's own logging or a trigger that writes to an audit table, and confirm that the audit records themselves are protected from the roles they track.
When a message broker like Kafka becomes the better choice
Move a queue to a message broker when the workload needs something a table cannot provide cheaply: a durable, replayable event log, many independent consumer groups that each read the full stream at their own pace, very high sustained throughput, or replication across sites. A FOR UPDATE SKIP LOCKED queue deletes or marks a job once it is handled, so a new team that wants yesterday's events has to be served from a different store. If several downstream systems need the same events, or you expect to add consumers later, a log-based broker is the more natural fit. Apache Kafka is the usual example. It is an Apache Software Foundation project released under the Apache License 2.0, and the project itself offers no paid edition, so the license cost is zero while staffing and hosting are not.
Plan the version and security baseline before you commit. The Kafka downloads page lists 4.3.1, 4.2.2 and 4.1.2 as supported releases. Kafka 4.x runs only in KRaft mode, so ZooKeeper-based clusters must migrate first, and brokers, Kafka Connect and tools require Java 17. Confirm the current list on the downloads page before you pick a release, because the supported set changes. For security, Kafka supports TLS for traffic between clients, brokers and tools, and SASL mechanisms including SCRAM-SHA-256, SCRAM-SHA-512, GSSAPI and OAUTHBEARER. Security is optional in Kafka, so verify that every listener you expose is secured and that ACLs cover each topic.
Treat the move as a new platform, not a configuration change. Kafka brings its own work: broker sizing, partition and retention planning, KRaft controller management, upgrades (the upgrade notes call for care when moving between releases), certificate and SASL credential lifecycles, monitoring of consumer lag, and tested backup or disaster recovery for topics. Ask whether your team can run that on call. If the honest answer is that a queue table works and no one wants another stateful cluster, keeping PostgreSQL for jobs and adding a broker only for the event streams that need one is often the cheaper design.
Questions teams ask before building a PostgreSQL queue
What does building a PostgreSQL job queue cost in effort, and what drives it?
The main cost is engineering time, and it is mostly one-time: designing the queue table, the claim and retry logic, idempotent handlers, dead-letter handling, monitoring and runbooks. Effort rises with the number of job types, the delivery guarantees the business needs, how many worker fleets consume the queue, and how much of the existing application code must change. Recurring cost is operational: someone owns vacuum tuning, queue table growth, alerting and on-call response. Ask any partner for a quote that separates the one-time build from the ongoing support, and that lists which job types, consumers and failure cases are in scope.
How long does a PostgreSQL queue take to build, and what sets the duration?
Duration depends on how much of the queue is new work versus reuse of patterns your team already runs. The biggest factors are the number of job types and their side effects on external systems, the retry and failure semantics your business accepts, whether you need scheduled or delayed jobs, and how far the load test must go before go-live. Organizations with an existing worker framework and clear idempotency rules usually move faster than those designing both the queue and the handlers at once. Ask for a written scope with milestones so the timeline is tied to named deliverables.
What must our team provide before a queue build can start?
The build needs four inputs from your side. First, schema and database access: a staging instance with the production PostgreSQL version, the existing application code paths that enqueue and process work, and the ability to run load tests against them. Second, a load profile: expected job volume, peak rates, payload sizes, latency targets and retry expectations. Third, named on-call owners who will receive alerts for queue depth, oldest job age and worker failures after go-live. Fourth, decision makers who can state which jobs may run twice, which must not, and how long failed jobs are kept.
Can an in-house team build a PostgreSQL queue without outside help?
Yes, a team with strong PostgreSQL and application experience can build a queue in-house, and many do. The questions to answer honestly are whether the team has reviewed FOR UPDATE SKIP LOCKED behavior under concurrent workers, has tested vacuum and autovacuum settings on a high-churn table, and can run the database under load without a broker to fall back on. If any of those are thin, an implementation partner can take the design review, load testing and runbook work while your team keeps ownership. Either way, the team that runs the queue after launch must be the team that understands it.
How do we know when to move a PostgreSQL queue to a message broker?
Move when the queue stops being a database workload and becomes a streaming or fan-out system. Common signals include many independent consumer groups that each need the same events, a need to replay history over long retention windows, throughput that drives constant row churn on the queue table, or cross-system event flows that need partitioned ordering guarantees. If you reach that point, a broker such as Apache Kafka is a candidate; its project documentation describes security and KRaft-based operation, and you should confirm fit against your own throughput and ordering needs. Plan the migration path early so the handler idempotency work carries over.
How does a PostgreSQL queue interact with backups and replication?
A queue table is ordinary data, so it is included in base backups and point-in-time recovery, and a restore brings jobs back to the recovery point. That has two consequences. Jobs already processed may be replayed after a restore, so handlers must be idempotent. Queue churn also produces a large volume of write-ahead log, which affects archive size and replica lag. On a streaming replica, long-running claim transactions and vacuum activity need monitoring. Test a restore with the queue in place and confirm how your recovery time and recovery point targets treat in-flight jobs. Check the PostgreSQL continuous archiving documentation for the recovery mechanics your team will rely on.
How DeployOpen scopes and delivers a PostgreSQL queue
DeployOpen plans, builds, tests and hands over PostgreSQL job queues inside infrastructure you control. We start by deciding whether the queue belongs in PostgreSQL at all, then design the worker, wake-up and vacuum model around your job volumes and failure tolerance.
How we scope
- Written scope names the job types, worker counts, latency expectations and retry rules the queue must handle.
- Scope records which tables hold jobs, how completed rows are archived or deleted, and who owns each table.
- Scope states whether LISTEN/NOTIFY is used only as a wake-up signal with polling as the fallback.
How we build
- We implement worker claim queries using FOR UPDATE SKIP LOCKED and test them under concurrent consumers.
- We set autovacuum thresholds for queue tables and measure dead tuple growth during a load test.
- We document the payload size limit and keep NOTIFY messages to identifiers that workers fetch from the table.
How we hand over
- You receive the worker code, schema, migration scripts, runbook and load test results in your repository.
- Handover covers monitoring for queue depth, oldest pending job age and vacuum activity on queue tables.
- We document the criteria and migration path for moving selected job types to a message broker later.
How we support
- Fixed-scope engagements are agreed in writing before work starts, and changes are priced through a written change request.
- Ongoing support, upgrades and continuous testing are available as a retainer after handover.
- Retainer work can include retesting queue behavior after PostgreSQL minor releases and planned major upgrades.

