Quick revision
The short answer
I would approve PostgreSQL queues when throughput is moderate and the main benefit is transactional enqueue: the event or job is written in the same transaction as the business change, which is the outbox pattern. The approval comes with rules: SKIP LOCKED claiming, partial indexes, short claim transactions, leases for crash recovery, idempotent consumers, and retention by deletion or partitioning with bloat monitoring. Teams should prefer a library over custom code, and we agree in advance on the thresholds of rate, fan-out and ordering that trigger a move to a broker.
What to remember
In this answer, we saw that the strongest reason to use PostgreSQL as a queue is transactional enqueue, the outbox pattern, and that it fits moderate rates with one consumer per message. Approval comes with rules: SKIP LOCKED claims in short transactions, partial indexes, leases and reapers, idempotent consumers, bounded retries, and retention by batched deletes or dropped partitions with bloat monitoring. Written thresholds for rate, fan-out, replay and latency trigger a move to a broker, while the outbox remains and maintained libraries replace custom code.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
I would approve PostgreSQL queues when throughput is moderate and the main benefit is transactional enqueue: the event or job is written in the same transaction as the business change, which is the outbox pattern. The approval comes with rules: SKIP LOCKED claiming, partial indexes, short claim transactions, leases for crash recovery, idempotent consumers, and retention by deletion or partitioning with bloat monitoring. Teams should prefer a library over custom code, and we agree in advance on the thresholds of rate, fan-out and ordering that trigger a move to a broker.
Why this question is asked
Every architect eventually hears the question: do we really need Kafka for this? A database queue is cheaper to run and has one real superpower, but it also has failure modes that only appear months later. Interviewers ask it to see whether we can say yes with conditions rather than give a blanket answer. In this answer, we will look at what makes a table queue attractive, when to approve it, the design rules we would require, retention and monitoring, the thresholds for moving to a broker, and the libraries that save teams from writing it all themselves.
1The Real Advantage: Enqueue in the Same Transaction
The best argument for a table queue is consistency, not cost. When an order is placed, we often need to publish an OrderPlaced event. If we commit the order and then publish to a broker, a crash between the two loses the event; if we publish first and the commit fails, we announce an order that does not exist. This is the dual-write problem.
With an outbox table in the same database, the service inserts the event row in the same transaction as the order. Either both commit or neither does. A separate relay or worker then reads the outbox and delivers the event. Background jobs get the same benefit: a job to send the confirmation email exists if and only if the order exists.
2When I Would Approve It
I would approve it when the volume is moderate, for example up to a few hundred messages per second at peak with a small backlog, when each message is consumed by one kind of worker, and when ordering needs are simple. Most internal background work and outbox relays fit this easily, and PostgreSQL handles it well with the right design.
I would not approve it as a general event backbone. Many independent consumers that each need every event, long retention and replay, per-key ordering combined with parallel consumption, or sustained rates in the thousands per second are what brokers are built for. For those, a table queue becomes a source of bloat, lock contention and custom code.
- Must enqueue be atomic with a business change?Yesstrong reason for a table (outbox)Noa broker is equally good
- Peak under a few hundred per second, one consumer group?Yestable queue fitsNouse a broker
- Needs replay, long retention or wide fan-out?Yesrelay the outbox into a brokerNotable queue alone
- Apply the design rulesSKIP LOCKED, leases, idempotency, retention, monitoring
4 steps in order. Play them, or step through them one at a time.
3The Design Rules I Would Require
Claiming must use FOR UPDATE SKIP LOCKED, so workers never take the same message and never wait for each other, and the claim must be its own short transaction that commits before processing starts. Each queue needs a partial index on the claimable rows, for example (run_at) WHERE status = 'PENDING', so claims stay fast regardless of history.
Crash recovery uses leases: a claimed message has locked_until or locked_at, a worker extends it while alive, and a reaper returns expired claims to the queue. Because a message can therefore be delivered twice, consumers must be idempotent, either naturally or by recording processed message ids in the same transaction as their effect. Failed messages get a bounded number of attempts with backoff and then go to a dead-letter status that someone is alerted about.
4Retention, Bloat and Monitoring
Queue tables churn, and in PostgreSQL every update and delete leaves a dead tuple. So finished work must leave the hot table quickly: either delete processed rows in small batches every few minutes, or partition by time and drop old partitions, which leaves no dead tuples at all. Autovacuum needs per-table settings, a low or zero scale factor with a fixed threshold, and an idle_in_transaction_session_timeout prevents a forgotten session from blocking cleanup.
Monitoring is part of the approval: queue depth and age of the oldest pending message per queue, claim latency, dead tuples and last autovacuum time for each queue table, attempts and dead-letter counts. An alert on oldest-pending-age catches most problems, from stuck workers to bloat, before users notice.
5Thresholds That Trigger a Move, and Libraries
Approval should come with exit criteria written down, so the move to a broker is a planned step rather than an incident response. Examples: sustained peak above 500 messages per second, a third consumer type needing the same events, a requirement for replay, or claim latency above 50 milliseconds at p99 after tuning. When a threshold is crossed, the outbox stays, and a relay forwards events into Kafka, so the transactional benefit is kept.
Finally, teams should not hand-write queue code if a maintained library fits. db-scheduler and JobRunr provide database-backed job scheduling for Java, and Spring Modulith's event publication registry persists application events and republishes incomplete ones. Each has its own claiming and locking approach, some using SKIP LOCKED, some using optimistic updates or polling, so the review should check how it claims, recovers and cleans up, against the same rules.
6Follow-up questions
How would you relay outbox rows to Kafka without double publishing?
Strictly, we cannot guarantee exactly-once delivery across a database and Kafka, so we aim for at-least-once delivery with deduplication. The relay reads unpublished rows in order, sends them with an idempotent producer, waits for the acknowledgement, and then marks the rows published; a crash between send and mark resends them. Each event carries a unique id, and consumers skip ids they have already processed. Change data capture with Debezium reading the write-ahead log is the common alternative to a polling relay, with the same at-least-once property.
Can the outbox preserve order per aggregate?
Yes, if the relay publishes events for the same aggregate in their commit order and uses the aggregate id as the Kafka key, so they land in one partition. A single relay per outbox, or one relay per hash range of aggregate ids, keeps that order; parallel relays over the same rows without that split can reorder events.
Is LISTEN/NOTIFY a good way to wake up workers?
It can reduce polling latency, because a worker wakes as soon as a job is committed, but notifications are not stored and are lost if no listener is connected, and NOTIFY adds some contention under high write rates. Use it as a hint on top of periodic polling, never as the only delivery mechanism.
7Conclusion
In this answer, we saw that the strongest reason to use PostgreSQL as a queue is transactional enqueue, the outbox pattern, and that it fits moderate rates with one consumer per message. Approval comes with rules: SKIP LOCKED claims in short transactions, partial indexes, leases and reapers, idempotent consumers, bounded retries, and retention by batched deletes or dropped partitions with bloat monitoring. Written thresholds for rate, fan-out, replay and latency trigger a move to a broker, while the outbox remains and maintained libraries replace custom code.
Open with
I'd approve it for the cases where the database actually gives us something a broker can't, which is enqueueing in the same transaction as the business change. The outbox pattern removes the dual-write problem: the order and its event commit together or not at all.
Then, if they want more
It fits moderate throughput, say up to a few hundred messages a second with one consumer type.
My conditions would be: claims use FOR UPDATE SKIP LOCKED in a short transaction that commits before processing; every queue has a partial index on the claimable rows; claims are leases with a reaper for crashed workers; consumers are idempotent because redelivery will happen; retries are bounded with a dead-letter status.
Finished work leaves the hot table quickly, by batched deletes or by dropping time partitions, with per-table autovacuum settings and alerts on dead tuples and on the age of the oldest pending message.
We'd also agree upfront on thresholds, like rate, a new consumer needing the same events, or replay, that trigger moving the delivery side to Kafka while keeping the outbox. And I'd steer teams to db-scheduler, JobRunr or Spring Modulith's event publication instead of custom code, after checking how each claims and recovers.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Teams want to use PostgreSQL tables as queues for outbox events and background jobs...": https://scrivio-interview-library.netlify.app/databases/database-locking/a4244b772a/