TL;DR
- The transactional outbox writes the business change and an event record in one PostgreSQL transaction. A separate publisher delivers that committed event to a broker or integration.
- Polling is usually simpler to operate at modest volume. Claim pending rows in short transactions, publish outside the transaction, and mark success with a fencing token. A crash after publish can still cause a duplicate.
- Logical decoding streams committed row changes from PostgreSQL’s write-ahead log (WAL). Debezium can route outbox changes to Kafka, but adds connectors, replication slots, schema and offset operations.
- Both approaches are commonly at-least-once at the consumer boundary. Use stable event IDs, idempotent consumers, bounded retries, and reconciliation.
- Replication slots can retain WAL and catalog rows while a consumer is disconnected. Monitor slot lag and disk before the database reaches its safety limit.
The dual-write failure the outbox addresses
An order service updates PostgreSQL and then publishes OrderCreated to a broker. If it commits the database row and crashes before publishing, the order exists but downstream services never hear about it. Reversing the order does not solve the problem: publishing first and then rolling back the database can announce an order that was never committed.
These are two writes to independent systems with no shared transaction. A network call inside the database transaction still does not make the broker participate in PostgreSQL’s commit. Holding locks while waiting on a broker also lengthens transactions and couples database availability to network latency.
The transactional outbox changes the second write. The application inserts an event row in the same local PostgreSQL transaction as the business mutation. A separate publisher later reads that durable row and sends it to the broker. If the transaction rolls back, both the business change and its event intent disappear. If it commits, both persist together.
The outbox guarantees atomic intent inside one database. It does not guarantee a broker is available, that delivery is exactly once, or that a consumer’s side effect is atomic with acknowledgement. Those boundaries still need retries, deduplication, and operations. Debezium describes the outbox pattern as a way to avoid inconsistency between a service’s database state and events consumed by other services. Debezium Outbox Event Router
Design a durable outbox contract
Store immutable event facts rather than a pointer to mutable state that consumers must immediately read. Include a stable event ID, event type, aggregate type and ID, aggregate version or sequence where ordering matters, schema version, creation time, and payload. Keep sensitive data out of the event unless the consumer genuinely needs it. Define payload evolution and retention before events become long-lived integration contracts.
A compact PostgreSQL schema could look like this:
CREATE TABLE outbox_event (
id uuid PRIMARY KEY,
aggregate_type text NOT NULL,
aggregate_id text NOT NULL,
aggregate_version bigint,
event_type text NOT NULL,
schema_version integer NOT NULL DEFAULT 1,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
claim_token uuid,
lease_until timestamptz,
published_at timestamptz,
attempt_count integer NOT NULL DEFAULT 0,
last_error_code text,
CHECK (attempt_count >= 0)
);
CREATE INDEX outbox_ready_idx
ON outbox_event (available_at, created_at, id)
WHERE published_at IS NULL;
A polling dispatcher can use claim and delivery columns on the row. A CDC design may use a simpler append-only event table and track progress in the replication slot and connector offsets instead. Keep those operational models distinct rather than adding polling fields that create confusing CDC updates.
Write the domain record and event in one transaction:
BEGIN;
UPDATE orders
SET status = 'created', version = version + 1
WHERE id = :order_id
RETURNING id, version;
INSERT INTO outbox_event (
id, aggregate_type, aggregate_id, aggregate_version,
event_type, payload
)
VALUES (
:event_id, 'order', :order_id, :version,
'OrderCreated', :payload::jsonb
);
COMMIT;
Use a uniqueness rule for the logical mutation or command if the API may retry after a timeout. An outbox event ID deduplicates delivery of one event, but it does not prevent a caller from creating two distinct orders because it retried an ambiguous request with a new ID. See our guide to idempotent payment requests for the related request boundary.
Pattern A: poll and claim rows with short transactions
Polling uses normal SQL and a worker fleet. Each worker claims a bounded batch with FOR UPDATE SKIP LOCKED, sets a lease or claim token, and commits. It sends events after releasing the database transaction, then marks successful deliveries. PostgreSQL documents that SKIP LOCKED gives an inconsistent view that is unsuitable for general-purpose queries but useful for queue-like consumers competing for rows. PostgreSQL SELECT locking clauses
BEGIN;
WITH picked AS (
SELECT id
FROM outbox_event
WHERE published_at IS NULL
AND available_at <= clock_timestamp()
AND (lease_until IS NULL OR lease_until < clock_timestamp())
ORDER BY available_at, created_at, id
LIMIT 100
FOR UPDATE SKIP LOCKED
)
UPDATE outbox_event AS e
SET claim_token = :claim_token,
lease_until = clock_timestamp() + interval '45 seconds',
attempt_count = attempt_count + 1
FROM picked
WHERE e.id = picked.id
RETURNING e.id, e.event_type, e.aggregate_id, e.aggregate_version,
e.payload, e.attempt_count;
COMMIT;
The worker publishes the returned rows outside the transaction. After the broker confirms a message, it marks that event published only if the claim token still matches:
UPDATE outbox_event
SET published_at = clock_timestamp(),
claim_token = NULL,
lease_until = NULL,
last_error_code = NULL
WHERE id = :event_id
AND claim_token = :claim_token
AND published_at IS NULL;
The token fences a worker whose lease expired and was reassigned. If the old worker wakes late, it cannot mark the replacement worker’s claim as complete. Lease duration should account for batch size, broker latency, and work deadlines. Renew or shrink batches when delivery can exceed the lease.
There is an unavoidable crash window: the broker accepts the event, then the worker dies before updating published_at. When the lease expires, the event is sent again. Acknowledge only after the broker confirms; this favors duplicates over silent loss. Consumers must deduplicate with the stable event ID, ideally in the same database transaction as their own business effect.
Polling is easy to inspect because pending rows live beside application data. It consumes query and update capacity, creates row churn, and needs indexes, vacuum planning, backoff, and lease recovery. A quiet poll interval increases delivery latency. Aggressive polling consumes connections and CPU when there is no work. Use a notification as a wake-up hint if desired, but always use the outbox rows as the durable source of truth.
Pattern B: stream outbox changes from WAL
PostgreSQL logical decoding reads changes from the write-ahead log and turns them into a logical stream through an output plugin. A replication slot records the consumer’s position so it can continue after disconnect. The standard pgoutput plugin is used by PostgreSQL logical replication. Debezium’s PostgreSQL connector can snapshot and then stream committed row changes, while its Outbox Event Router transforms outbox records into broker messages. PostgreSQL logical decoding and replication slots · Debezium PostgreSQL connector · Debezium outbox transformation
A simplified connector configuration uses the PostgreSQL connector, a unique slot name, an output plugin supported by the exact Debezium release, and the outbox router transform:
connector.class=io.debezium.connector.postgresql.PostgresConnector
plugin.name=pgoutput
slot.name=orders_outbox_v1
publication.autocreate.mode=filtered
table.include.list=public.outbox_event
tombstones.on.delete=false
transforms=outbox
transforms.outbox.type=io.debezium.transforms.outbox.EventRouter
transforms.outbox.table.field.event.id=id
transforms.outbox.route.by.field=aggregate_type
transforms.outbox.table.field.event.key=aggregate_id
transforms.outbox.table.field.event.payload=payload
Configuration names and plugin behavior can change between releases. Start from the connector reference for the exact Debezium and Kafka Connect versions you deploy, configure a least-privilege replication user, and test snapshot, restart, and schema evolution. The example is a starting point rather than a drop-in production connector file.
CDC avoids a polling query for each dispatch interval and can lower event latency by streaming committed changes. It adds a long-running connector, replication credentials, publication and slot lifecycle, Kafka Connect or another Debezium runtime, offset storage, connector upgrades, and a second operational plane. If downstream systems need a different broker, they still need a bridge or another connector stage.
Logical decoding has operational effects in the primary database. A replication slot can retain WAL and catalog rows while its consumer is disconnected. PostgreSQL warns that abandoned slots can consume storage and, in extreme conditions, contribute to database shutdown or transaction-ID safety problems. Monitor slot state, retained WAL bytes, connector lag, and free disk, and drop slots that are no longer needed. PostgreSQL pg_replication_slots view · Replication slot resource retention warnings
Compare the operational boundary
| Question | Polling | Logical decoding and CDC |
|---|---|---|
| What reads the event? | Application worker selects rows from the outbox table. | Connector consumes decoded committed changes from a replication slot. |
| What must be operated? | Worker fleet, SQL indexes, leases, retries, and row cleanup. | Replication configuration, slot, connector runtime, offsets, transforms, and destination broker. |
| Where is lag visible? | Oldest ready row and expired lease age. | Connector source lag, slot LSN positions, retained WAL, and destination lag. |
| How is replay handled? | Reset delivery state or republish selected event IDs. | Restore connector offsets or replay from a retained broker topic, subject to slot and connector recovery behavior. |
| What tends to make sense? | Modest event volume, low infrastructure appetite, straightforward retries. | Existing CDC platform, many tables or consumers, lower polling load, and a team ready to operate replication. |
There is no traffic threshold that universally separates these patterns. Query cost depends on event rate, batch size, indexes, row width, and the database’s existing load. CDC cost depends on WAL volume, transaction size, connector throughput, retention, and the number of downstream stages. Measure under representative writes and failure behavior.
A hybrid design is possible: poll a small operational outbox while using CDC for analytics or cross-service event distribution. This introduces two delivery paths and requires clear ownership for each event type. Avoid sending the same event through both systems to the same consumer unless it deduplicates.
Preserve ordering and handle event evolution
PostgreSQL commit order and the order in which parallel pollers publish messages are not automatically the same thing. If events for one aggregate must be applied sequentially, store an aggregate version and enforce ordering at the consumer. Route the aggregate ID as the broker key so related records reach the same ordered partition where the broker supports that model. Concurrent transactions updating one aggregate must serialize through a row lock or version check before creating events.
Keep an event schema version and define compatibility rules. Add optional fields before requiring them, keep consumers tolerant of unknown fields, and avoid reusing an event type with materially different meaning. Store immutable payloads; consumers should not have to query a live order row that may already have advanced.
For privacy, consider whether the payload needs personal data and how long the broker and outbox retain it. CDC pipelines can replicate row data beyond the application database, so include the connector, broker, backups, and downstream consumers in access and deletion reviews.
Retries, cleanup, and production monitoring
Classify broker errors into retryable and permanent categories. Use exponential backoff with jitter and cap attempts or event age before moving work to an operator-visible terminal state. A single poison record should not permanently block a high-volume queue. If preserving aggregate order is required, route the aggregate into a blocked state and alert rather than silently publishing later events out of sequence.
For polling, monitor outbox row count, oldest unpublished age, claim expirations, attempts per event, publish latency, and database write amplification. Delete published rows only after a retention period that covers operational replay and audit needs. Archive if a later rebuild depends on the event history.
For CDC, monitor connector status, source event lag, slot activity, WAL retained by each slot, disk headroom, transaction spill, and destination lag. A stalled slot can retain WAL even when no consumer is currently connected. Configure thresholds and a recovery runbook before enabling a production slot. Do not drop a slot casually: if required WAL is removed, the connector may need a new snapshot or controlled resynchronization.
Test the uncertainty windows. Kill a poller after broker acknowledgement but before marking the row published. Restart the connector after consuming a transaction but before checkpointing offsets. Pause the destination broker while database writes continue. Rebuild a consumer from retained events and verify idempotency. Durable messaging is an operational process, not a single SQL statement.
Frequently asked questions
When should I replace polling with logical decoding?
Consider CDC when polling load or delivery latency is a measured problem, or your platform already operates a CDC stack. Keep polling when its query volume and delay fit the product and a worker is simpler for the team to support. Compare failure recovery and database impact, not only steady-state throughput.
Does a transactional outbox guarantee exactly-once delivery?
No. It atomically commits business state and event intent inside PostgreSQL. A publisher can send successfully and crash before recording progress, so delivery can repeat. Use a stable event ID and make consumer effects idempotent or deduplicated in the consumer’s transaction.
Why can an inactive PostgreSQL replication slot cause disk pressure?
A slot retains WAL and possibly catalog rows required for its consumer to resume. If the consumer stops advancing, those resources can accumulate. Monitor slot LSN positions and retained WAL, alert on disk headroom, and retire unused slots deliberately.
Can multiple pollers publish events in aggregate order?
Not automatically. Concurrent workers can claim and publish adjacent events in a different order. If order matters, store an aggregate version and serialize publication or enforce version checks at the consumer. Partition by aggregate ID when using a broker with keyed ordering.
Choose the least complex reliable publisher
The outbox closes the database-to-event-intent gap in both designs. Polling is a practical first choice when its measured workload fits and a worker is easier to operate than replication infrastructure. Logical decoding with Debezium fits teams that already have CDC operations or have a proven need to stream database changes without repeated polling. Neither removes duplicate delivery or consumer recovery work.
Start with event IDs, immutable payloads, consumer idempotency, retention, and a failure drill. Then measure the oldest event age, database impact, slot lag, and recovery time in the deployment you plan to run. For broader choices around asynchronous processing, see our Kafka and Redis Streams sizing guide and our durable workflow guide. If your team is defining reliable cross-service events, talk to our engineering team about the transaction and recovery boundaries.
