SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • The Problem with Distributed Transactions
  • Two-Phase Commit (2PC)
  • Three-Phase Commit (3PC)
  • SAGA Pattern
  • Try-Confirm-Cancel (TCC)
  • Compensating Transactions
  • Outbox Pattern
  • Exactly-Once Processing
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed Transactions

Outbox Pattern

Save the change and the event in one local transaction, then publish the event safely.

⏱ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

The outbox pattern makes sure a service saves its data and sends its event together, or does neither. It does this by writing the event into an outbox table in the same database transaction as the data. A separate process then reads the outbox and sends the events.

  • The problem: saving to a database and publishing to a message broker are two separate systems. A crash between them loses the event or sends one for data that was never saved.
  • The fix: one local transaction writes both the business row and an event row. That is atomic.
  • A relay sends the saved events later. This gives at-least-once delivery, so consumers must handle duplicates.

02Concept: What is it?

A service often needs to do two things: change its database (save an order) and tell others (publish an OrderCreated event). This is called a dual write. The trouble is that a database and a broker cannot share one transaction. Whatever order you pick, a crash in the middle leaves a mess.

  • Save, then publish: if the app dies between them, the order exists but nobody is told. The event is lost.
  • Publish, then save: if the save fails, others were told about an order that does not exist.

The outbox pattern turns the dual write into a single write. In one database transaction the service inserts the order and also inserts a row in an outbox table that describes the event. Both commit or both roll back. A relay (also called a message relay or publisher) then reads new rows from the outbox, publishes them to the broker, and marks them as sent.

Dual write and outbox
Dual write (risky)
⚙️Service
↓1. save
↓2. publish
🗄️Database
📨Broker
Outbox (safe)
⚙️Service
↓1. one transaction
🗄️Orders + Outbox tables
↓2. relay reads
🔁Relay
→↓3. publish
📨Broker
With an outbox, the only thing that must be atomic is a write inside one database.
🧠At-least-once, not exactly-once
If the relay publishes an event and then crashes before marking it as sent, it will send the event again after a restart. So the outbox gives at-least-once delivery. The consumers must be idempotent.

03Real-Life Example

🍵The Outgoing Mail Tray
An office clerk finishes a form and must also post a copy to another department. If the clerk files the form and then walks to the post box, a phone call or a fire alarm can stop them in the middle: the form is filed but the copy is never posted. Instead the clerk follows a rule: put the form in the cabinet and the copy in the "outgoing" tray in one move. A mail person comes by regularly, collects everything in the tray, posts it, and ticks it off. If the mail person is interrupted after posting but before ticking, they may post the same letter twice, so the receiving department checks whether it has already seen that letter number.
Office
Outbox pattern
Filing the form
Saving the business data
The outgoing tray
The outbox table
Doing both in one move
One local database transaction
The mail person
The relay / message publisher
Ticking a letter as posted
Marking the outbox row as sent
Posting the same letter twice by mistake
A duplicate event (at-least-once)
Letter numbers the other office checks
Event IDs for idempotent consumers
One order, step by step
📝Save order + eventone transaction
→↓
🔁Relay readsnew outbox rows
→↓
📨Publishto the broker
→↓
✅Mark sentor delete the row

04Why Do We Need It?

🧱Atomic
The data and its event are saved together. You cannot have one without the other.
🛡️Survives crashes
If the app or the broker is down, events wait safely in the database.
🧩No special tech
It needs only a normal local transaction. No distributed transaction or 2PC.
📏Keeps order
Events from one record can be sent in the order they were written.
🔌Decouples
The business code does not wait for the broker. It just writes a row.
🔍Easy to audit
The outbox table is a record of what was meant to be sent.
If a change and its announcement must go together, write both in one local transaction, and send the announcement later.

05Where Do We Use It?

🔗Sagas
Each saga step saves its change and the next command or event together.
📣Event-driven systems
Publishing domain events like OrderCreated or UserRegistered reliably.
📚CQRS read models
Updating a read store or search index only after the write really committed.
🗂️Event sourcing
Publishing stored events to other services.
🔔Notifications
Emails and push messages that must be sent once the order exists.
🔄Data sync
Keeping a cache, a search engine or another service in step with the database.

06Types / Parts / How It Works

Two ways to get events out of the outbox

Polling publisher and log tailing (CDC)
Polling publisher
🗄️Outbox table
↑SELECT unsent every second
🔁Relayasks again and again
↓publish
📨Broker
Log tailing (CDC)
🗄️Outbox table
↓database change log
🔁CDC toole.g. Debezium
↓publish
📨Broker
Simple, adds some delay Fast, needs a CDC tool
Both read the same outbox. They differ in how they notice new rows.
Polling publisherLog tailing (CDC)
How it worksA loop selects unsent rows on a timerA tool reads the database transaction log and streams new rows
DelayUp to the polling intervalNear real time
Load on the databaseRepeated queries, even when idleLow, reads the log
Set-upA small piece of codeA CDC connector and database settings
Best forSmall to medium systems, simple set-upHigh volume and low delay

What an outbox row holds

ColumnExampleWhy
id7c1e... (unique)Lets consumers spot duplicates
aggregate / keyorder-1042Same key goes to the same partition, so order is kept
typeOrderCreatedTells consumers what happened
payload{ "orderId": 1042, ... }The event data, often JSON
created_at / sent_attimestampsOrder of sending and cleaning up
VisualizerDual write vs outbox: what does a crash do?Start with a dual write and make the app crash after the commit, to see a lost event. Switch to the outbox. Then crash the relay and toggle the idempotent consumer.
How does the service announce a new order?
What crashes?
Is the consumer idempotent?
OrderWhat happenedIn brokerConsumer acted
#1 ✅saved and announced✉️1×
#2 ✅app died after the DB commit, before publishing: event LOSTnone0×
#3 ✅saved and announced✉️1×
#4 ✅saved and announced✉️1×
Orders saved
4
in the database
Events in broker
3
expected 4
Lost events
1
order saved, no event
Duplicate effects
0
e.g. repeat emails
Consumer actions
3
total
1 order(s) are saved, but no event was ever sent. Email, stock and search never hear about them, and nothing will fix it. A dual write cannot be atomic: two systems, two separate commits.

A simplified model. The crash hits the 2nd order (or the 1st if there is only one). Real relays poll the outbox table or read the database log (CDC).

07How to Use It / Steps / Implementation

Building an outbox

  1. 1
    Create the outbox table
    Put it in the same database as your business tables. Add id, key, type, payload, created time and a sent flag or time.
  2. 2
    Write both in one transaction
    BEGIN, insert or update the business row, insert the outbox row, COMMIT. Never publish to the broker inside this code.
  3. 3
    Run a relay
    A separate process (or a CDC tool) reads unsent rows in order, publishes them, and then marks them as sent.
  4. 4
    Keep the order
    Use the aggregate ID as the broker key, so events about one record stay in order.
  5. 5
    Make consumers idempotent
    Store the IDs of handled events, or make the action safe to repeat, so a duplicate does no harm.
  6. 6
    Clean up
    Delete or archive sent rows after a while, so the table does not grow forever.
  7. 7
    Watch it
    Track the number and age of unsent rows. A growing backlog means the relay or the broker has a problem.
💡Several relays
If you run more than one relay for safety, make sure two of them do not publish the same row at once. Use row locks such as SELECT ... FOR UPDATE SKIP LOCKED, or let a single leader run the relay.
⚠️The inbox is the other half
The outbox protects the sender. For the receiver, an inbox table stores the IDs of messages already processed. A duplicate then finds its ID and is skipped.

08Key Terms to Know

TermMeaning in easy words
Dual writeWriting to two systems (database and broker) with no shared transaction
Outbox tableA table that holds events waiting to be sent, written in the same transaction as the data
Relay / publisherThe process that reads the outbox and sends events to the broker
Transactional outboxAnother name for the outbox pattern
Polling publisherA relay that checks the outbox on a timer
CDC (change data capture)Reading the database change log to stream row changes
At-least-once deliveryEvery event arrives, but some may arrive more than once
Idempotent consumerA receiver that handles a repeated message safely
Inbox tableA table on the receiving side that remembers which messages were handled
AtomicAll of it happens or none of it does
BacklogEvents saved in the outbox but not yet sent

09Pros, Cons and Trade-offs

✅ Pros
  • No lost events when the app crashes
  • No event for data that was never saved
  • Uses a normal local transaction
  • Works even when the broker is down for a while
  • Keeps the order of events per record
⚠️ Cons
  • Duplicates are possible, so consumers must be idempotent
  • Events are sent with a small delay
  • Extra table, relay process and clean-up job
  • The outbox adds write load on the main database
  • A CDC set-up needs extra tools and know-how

Trade-offs

ChoiceWe gainWe lose
Outbox instead of dual writeNo lost or phantom eventsAn extra table and process to run
Polling relaySimple to buildAdded delay and constant queries
CDC relayLow delay and low loadMore moving parts to operate
Short polling intervalFresher eventsMore load on the database
Delete rows after sendingA small, fast tableLess history for audits

10Common Problems and Mistakes

Common mistakes

  1. Publishing inside the transaction. The broker call is not part of the database transaction. If the commit fails, the event is already out.
  2. No idempotent consumer. A normal duplicate sends two emails or charges twice.
  3. Never cleaning the table. It grows until queries get slow.
  4. Losing the order. Using many relays without keys, so events about one record are published out of order.
  5. Two relays sending the same row. Without locks, duplicates multiply.
  6. Ignoring the backlog. No alert when unsent rows pile up.
  7. Different transaction. Writing the outbox row in another connection or database means it is no longer atomic.

Things to watch

📈Growing backlog
The relay is slow or the broker is down. Alert on the age of the oldest unsent row.
🔁Duplicates
Expected. Handle them in the consumer.
☠️Poison events
A row that always fails to publish blocks the line. Park it and alert.
🧮Schema changes
The payload is a contract. Version your events.

11Real-World Examples

🐘Debezium
An open-source CDC tool often used to stream an outbox table from PostgreSQL or MySQL into Kafka.
🧰Framework support
Libraries such as MassTransit, NServiceBus, Axon and Eventuate Tram include outbox features.
🛒Order systems
Save the order, then reliably tell stock, payment and email services.
🏦Banking
A transfer record and its notification event are written together.
🚕Ride apps
A trip state change and the events for pricing and notifications are stored together.
🔔Notifications
Welcome emails sent exactly because the sign-up really committed.
📝Note
Some databases and cloud services offer their own change streams. Check the documentation for your product before choosing a design.
Mini case: the app crashes right after the commit
📝Order + outbox rowcommitted
→↓crash
💥App down
→↓relay still runs
🔁Relay publishes
→↓
📨Event delivered

12Related Topics to Read Next

SAGA Pattern→

Each saga step uses an outbox to send the next message safely.

Idempotency→

Needed to handle the duplicates an outbox can create.

Delivery Semantics→

At-least-once, at-most-once and exactly-once explained.

Message Brokers→

Where the relay sends the events.

Event-Driven Architecture→

The style of system that needs reliable events.

ACID Transactions→

The local transaction that makes the outbox atomic.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Problem: database and broker cannot share one transaction (dual write).
  • ✔Fix: write the data and an outbox row in one local transaction.
  • ✔Relay: reads the outbox, publishes, marks sent. Polling or CDC (Debezium).
  • ✔Delivery: at-least-once. Duplicates happen.
  • ✔Consumers: must be idempotent. An inbox table helps.
  • ✔Order: key by aggregate ID.
  • ✔Operate: clean old rows and alert on the backlog.
  • ✔One line: “Save the event with the data, and send it later.”
← Previous
Compensating Transactions
Next →
Exactly-Once Processing