Outbox Pattern: Publish Events Without Losing Data
The transactional outbox pattern explained: how it fixes the dual-write problem, how the relay works with Kafka, and how to handle duplicates, ordering and retries.

The outbox pattern lets a service save a business change and the event announcing it in one database transaction, then publish that event separately. Nothing is announced that never happened, and nothing that happened goes unannounced. If your system updates a database and also has to tell a queue, a broker or another service, this is the standard way to stop the two from drifting apart. Done well, it is a small amount of code. Done badly, it produces duplicate invoices, missed orders and silent gaps that surface months later.
TL;DR
- The outbox pattern solves the dual-write problem: a database update and a message publish are two separate writes, and one can fail while the other succeeds.
- You write the business record and an outbox row in the same transaction. A separate relay then reads committed rows and publishes them to the broker.
- Delivery is at least once, so consumers must tolerate duplicates. Plan idempotency, ordering, retries and a dead-letter path from day one.
- The relay can poll the table or use change data capture (CDC). Kafka setups often use a connector for this.
- Use it when a database update must trigger an event. For a business transaction spanning several services, AWS points to saga orchestration instead.
Table of Contents
- The problem: two writes that cannot be made atomic
- How the outbox pattern works
- Polling or change data capture: choosing the relay
- Outbox pattern with Kafka
- What the pattern guarantees, and what it does not
- Relay coordination and batching
- When to use the outbox, and when not to
- What this means for your business
- Building it properly with LogicBranch
- Our perspective
- FAQ
- Sources
The problem: two writes that cannot be made atomic
Picture an order service. A customer pays, you save the order, and you publish an OrderCreated event so billing, stock and email services react. That is two operations against two systems: your database and your broker.
There are two ways it breaks. The database commit succeeds but the publish fails, so the order exists and nobody else hears about it. Or the event goes out first and the database transaction then rolls back, so other services act on an order that was never saved. AWS Prescriptive Guidance describes this as the dual-write problem, and the transactional outbox as the fix: update the service's database and record the message to be sent atomically, instead of writing to the database and the broker independently.
The tempting shortcuts do not hold. Publishing inside the transaction block still leaves a window between publish and commit. Publishing right after the commit leaves a window where the process can crash. Retrying in memory is lost the moment the process restarts. Only a durable record, written in the same transaction as the data, closes the gap.
How the outbox pattern works
The pattern has three moving parts: an outbox table, the transaction that fills it, and a relay that empties it.
- Write both in one transaction. Insert or update your business record and insert an event row into an outbox table. They commit together or roll back together.
- Relay after commit. A separate worker reads unprocessed outbox rows and publishes them to the broker.
- Mark as processed. Once the broker confirms, the worker marks the row processed or deletes it.
Microsoft's Azure guide shows exactly this flow: an order and an OrderCreated event are inserted in the same transaction, then a background worker publishes the event and marks the outbox entry processed.
What an outbox table looks like
In a relational database the outbox is simply a table. The FOLIO project's technical design gives a PostgreSQL example where the event log table holds an event ID, a date, an entity type, an action and a JSONB payload. A practical version for your own service might look like this:
| Column | Purpose |
|---|---|
| event_id | Unique ID, also used by consumers to detect duplicates |
| aggregate_id | The entity the event belongs to, such as the order ID |
| event_type | For example OrderCreated |
| payload | The event body, often JSON |
| created_at | Used to keep events in order |
| processed_at | Empty until the relay has published the row |
The example in AWS's guidance follows the same shape: a Flight entity and its event are saved in separate tables within one transaction, and an event processor later reads the outbox and sends the event to the broker.
If you use a NoSQL store, the outbox is not a table but an embedded or companion record. The Azure guide uses Cosmos DB's change feed for automatic event processing and describes time to live (TTL) as a way to simplify the implementation. On AWS, DynamoDB Streams captures time-ordered item changes in near real time, and EventBridge Pipes forwards them to an event bus, with a dead-letter queue available for failed events.
Polling or change data capture: choosing the relay
The relay is where most of the engineering effort goes. You have two broad options.
Polling. A scheduled process queries the outbox for new rows, publishes them and marks them done. It is simple, needs no extra infrastructure and is easy to reason about. The cost is latency (events wait for the next poll) and steady query load on the database.
Change data capture. Instead of querying the table, a CDC tool reads the database's transaction log and streams new outbox rows to the broker. Latency is lower and the table is not hammered by polling. The cost is another component to run, secure and monitor. Our own guide to change data capture, its patterns and architecture, covers how log-based capture works in more depth.

A rule of thumb: start with polling for modest event volumes and a small team, and move to CDC when latency requirements tighten or polling load becomes visible in your database metrics. Because the outbox table is the contract between your service and the relay, switching later does not change the application code that writes events.
Outbox pattern with Kafka
With Kafka the shape is the same. The application commits business data and an outbox row atomically. A separate process, a CDC system or a Kafka connector then monitors the outbox and delivers events to Kafka.
A hand-built relay is also workable. The FOLIO design takes a database lock, reads events, builds Kafka events, sends them, deletes the processed records in a batch and commits. It runs on a timer and uses a SELECT FOR UPDATE lock so concurrent workers do not send the same rows, which also preserves event order in that design.
Two Kafka-specific habits help. Use the aggregate ID as the message key so all events for one order land in the same partition and keep their order. And put the event ID in a message header so consumers can deduplicate.
What the pattern guarantees, and what it does not
The outbox gives you one strong guarantee: a business-state change cannot commit without its event record. It does not make publishing instant, and it does not make it exactly once. Publishing stays asynchronous and can be delayed.
Duplicates and idempotent consumers
The relay can publish a row, crash before marking it processed, and publish it again after restart. A timeout can cause the same thing. Confluent identifies at-least-once delivery as the practical guarantee, so downstream consumers should deduplicate or be idempotent. AWS gives the same advice: idempotent consumers that track processed messages.
An idempotent consumer is one where handling the same message twice has the same effect as handling it once. A worked example: a billing service receives OrderCreated with event_id 8f2a. Before creating the invoice, it inserts 8f2a into a processed_messages table in the same transaction as the invoice. If 8f2a arrives again, the insert fails on the unique key, the transaction is skipped and no second invoice appears. NestJS documentation recommends an inbox of processed message IDs to suppress duplicates, which is this same idea.
Ordering
AWS advises preserving the order of database updates and not sending notifications for rolled-back transactions. In practice that means the relay reads rows in creation order, a single relay instance (or a locking strategy) handles a given aggregate, and the broker partitions by aggregate ID. If you use SQS, note that standard queues may deliver duplicates; AWS describes FIFO queues for cases that need exactly-once processing with ordering.
Retries and dead letters
Backoff handles transient failures such as a broker restart. Persistent failures, such as a payload the broker rejects, need somewhere to go. In the NestJS design, the relay retries with backoff and moves messages that keep failing to a dead-letter table. That table makes the failure visible and recoverable instead of blocking the whole queue behind one bad row. Alert on its row count.
Relay coordination and batching
Once you run more than one relay instance, or event volume climbs, two questions decide whether the pattern stays healthy: who owns which rows, and how many rows move per cycle.
Locking is the usual answer to the first. The FOLIO team's approach, noted above, is that concurrent workers need a locking strategy, and events are processed and deleted in batches. Batching matters because Confluent notes that outbox writes and frequent deletes can increase database resource use and contention. Deleting one row at a time is the costly way to clean up. Batch deletes, or partition the table by date and drop old partitions, are cheaper.
A related integration problem shows the same trap: a nightly bulk export that pushes everything at once and hides failures until morning. This write-up on batch processing and ERP integration pitfalls shows why small, frequent, well-tracked batches beat one big job. The outbox relay applies that lesson at event level.

When to use the outbox, and when not to
Use it when a database update must trigger an event notification in an event-driven application. That covers most cases: order placed, document signed, stock level changed, customer record updated.
It is the wrong tool when a single business transaction must update data stores in several services and roll back everywhere if one step fails. For that, AWS recommends saga orchestration. The two often work together: each saga step uses an outbox to publish its own result reliably.
What this means for your business
You do not need a hundred microservices to hit the dual-write problem. Any system that saves data and then calls something else can hit it.
- E-commerce: an order saved but never sent to the warehouse system, or a stock update that never reaches your storefront. An AI customer service agent that reads order events needs those events to be complete.
- Professional services and enterprise: a document marked signed in one system but never reflected in the matter or case system. Audit requirements make a lost event more than a nuisance, because the record has to be complete.
- Startups and scale-ups: an MVP that works with one service often starts to lose events the first time you split out billing or notifications. Adding an outbox early is cheap. Retrofitting it after data has diverged is not.
- Agencies and consultancies: if you white-label agentic features into client products, the agents' actions need to be published reliably to whatever the client already runs.
- SMBs: an internal tool that updates your job system and then emails or syncs to accounting needs the same discipline, just at smaller volume. A polling relay is usually enough.
Building it properly with LogicBranch
Reliable event flow is an architecture decision as much as a code one: where the service boundaries sit, how the relay is deployed and secured, and how events are monitored. We build custom SaaS platforms, microservices architectures, system integrations and AI agent solutions for enterprises, SMBs, startups, agencies, e-commerce businesses and professional services firms, and we work with modular, domain-driven designs and zero-trust security. Our own product ksign.co brings AI into e-signature and document workflows, where complete, ordered records matter.
If you are designing or repairing event flow between systems, see our custom software and AI development services.

Our perspective
We treat the outbox as a default, not an optimisation. Any time a service changes state and tells someone about it, the two should be one decision. Teams that skip it usually do so because everything works in testing, and testing rarely kills a process between a commit and a publish.
What we care about most is what happens after the pattern is in place. An outbox without idempotent consumers just moves the bug downstream. A relay without a dead-letter path turns one malformed event into an outage. We would rather ship a plain polling relay with good monitoring than a clever CDC pipeline nobody can operate.
That is how we approach software generally: strict engineering standards, modular domain-driven boundaries, and no complexity for its own sake. Reliable messaging is a good example of technology that should be boring and correct. Build the simple version properly, measure it, and scale the relay when the numbers say so.
Josh
FAQ
What is the outbox pattern?
It is a way to publish events reliably from a service that owns a database. The service writes the business change and an event record in one transaction, and a separate relay publishes the event afterwards. This removes the window where the database and the broker disagree.
Does the outbox pattern guarantee exactly-once delivery?
No. The relay delivers at least once, because a crash or timeout between publishing and marking the row processed leads to a retry. Make consumers idempotent, for example by recording processed event IDs, so a repeated message has no second effect.
Should I use polling or CDC for the relay?
Polling is simpler and fits modest volumes and small teams. CDC reads the database log and gives lower latency with less query load, but adds infrastructure to run and monitor. Because the outbox table stays the same either way, you can start with polling and move later.
Is the outbox pattern the same as a saga?
No. The outbox makes one service's database update and event publication reliable. A saga coordinates a business transaction across several services. AWS recommends saga orchestration for transactions that span services, and the two are often combined.
Sources
- Transactional outbox pattern, AWS Prescriptive Guidance
- Implement the Transactional Outbox Pattern by Using Azure Cosmos DB, Microsoft Learn
- Implementing the Transactional Outbox pattern, FOLIO technical design
- The Transactional Outbox Pattern, Confluent Developer
- Transactional outbox, NestJS documentation
- Implementing the transactional outbox pattern with Amazon EventBridge Pipes, AWS Compute Blog
- Batch processing and ERP integration pitfalls
Recommended

API-First Design: What It Is and How to Apply It
API-first design means agreeing the API contract before building anything. See how it works, when it beats code-first, and how Australian businesses can use it.

Tokenization vs Encryption: How to Choose for Your Data
Tokenization and encryption protect data in different ways. Learn how each works, how they compare with masking and hashing, and which fits your Australian business.