GuideAdvanced1 min read
Transactional Outbox with PostgreSQL: Closing the Dual-Write Gap
Commit domain data and event intent together, build a relay, and design consumers for unavoidable duplicate delivery.
- Author
- Pradeep Gajendra
- Published
- Updated
Scope of this article
- Environment
- Schema fragments are illustrative; relay mechanics depend on broker and database schema.
The classic dual-write bug is short: write an order to PostgreSQL, then publish an event. Crash between those actions and the order exists with no event. Reverse them and consumers may see an event for an order that never committed. A transactional outbox stores the intent in the same transaction as the business change.
The two-commit trap#
Commit state and event together#
begin;
insert into orders (id, customer_id, status)
values ($1, $2, 'CONFIRMED');
insert into outbox_events (id, aggregate_id, event_type, payload, created_at)
values ($3, $1, 'OrderCreated', $4::jsonb, now());
commit;An independent relay reads committed outbox rows, publishes them, and marks them delivered. That closes the lost-event gap between the order write and recorded publish intent [1]. It does not promise exactly-once external delivery.
The remaining duplicate window#
If the relay publishes successfully and dies before marking the outbox row delivered, it will publish again. Every consumer therefore needs an inbox/deduplication key or an idempotent state transition. Keys should represent event identity, not transport attempt ID.
create table processed_events (
consumer_name text not null,
event_id uuid not null,
processed_at timestamptz not null default now(),
primary key (consumer_name, event_id)
);
-- In a single transaction: insert processed_events with ON CONFLICT
-- DO NOTHING, apply domain changes only if one row was inserted.Operational obligations#
Publish in a stable order when business semantics require it, usually per aggregate key; global ordering is expensive.
Monitor oldest unpublished event age, relay failure rate, duplicate rate, and consumer lag.
Retain an audit trail and decide when delivered rows can be archived.
Use event schema versions and compatibility tests; database migrations and event deployments are separate concerns.
Plan recovery for a broker outage without making the web request wait on the broker.
Sources
- [1]Transactional Outbox Pattern
Microservices.io · publication date unknown · retrieved 2026-11-02
Spotted an error? Use “Suggest a correction” in the discussion, or read our corrections policy.
Discussion
Sign in to join the discussion. Reading is always open.
Loading discussion…