If your code saves a row and then publishes an event, you are already losing events. Here's the fix, and it's about forty lines

By The Coding Gopher

Published: 2026-10-10

URL: https://thecodinggopher.substack.com/p/the-transactional-outbox-pattern


Almost every service that publishes events has the same bug in it, and most teams haven’t noticed.

The shape is this: you save something to your database, then you publish an event saying you saved it.

def place_order(order):
db.save(order)                          # 1
broker.publish("OrderPlaced", order)    # 2

No transaction spans those two lines, because none can — your database and your broker share no commit protocol. So there are two ways it breaks.

Line 1 succeeds, line 2 fails. The order is in your database. Nobody downstream hears about it. No shipment, no confirmation email, no analytics row. The customer paid and nothing happened.

Line 2 succeeds, line 1 rolls back. An OrderPlaced event is in flight for an order that doesn’t exist. Downstream services create a shipment for nothing.

This is the dual write problem. It fires on every deploy, every broker hiccup, every network blip — and most teams find it months later when two systems disagree about how many orders there were.

Retrying the publish narrows the window but doesn’t close it: if the process dies between the lines, there’s nothing left to do the retrying.The outbox pattern solves the dual-write problem in microservices and distributed systems. It prevents data drift and state mismatches when an application must update a local database and publish an event to a message broker (like Kafka or RabbitMQ) as part of a single business operation, according to guidance on the Transactional outbox pattern.

Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.Guarantee both to happen or don’t

The pattern

In one line

Write the event into your own database, in the same transaction as the data, and let a separate process deliver it.

Why it works

You can’t atomically write to two systems. So write to one. Your database already gives you atomicity — put both writes inside it.

def place_order(order):
with db.transaction():
db.save(order)
db.save(OutboxEntry(
type="OrderPlaced",
payload=serialize(order),
))
# both rows commit, or neither does

The event is now a row in an outbox table, committed by the same transaction as the order. A relay process reads that table and publishes.

The table itself is deliberately boring:

CREATE TABLE outbox (
id            BIGSERIAL PRIMARY KEY,
aggregate_id  TEXT      NOT NULL,   -- e.g. order 42
type          TEXT      NOT NULL,   -- "OrderPlaced"
payload       JSONB     NOT NULL,
created_at    TIMESTAMP NOT NULL DEFAULT now(),
published_at  TIMESTAMP              -- NULL until sent
);

aggregate_id is the one field people leave out and regret. It’s what lets you partition by entity later so that all events for order 42 stay in order.

TRANSACTION
+----------------------------------------+
|   orders table       outbox table      |
|   +-----------+      +--------------+  |
|   | id   42   |      | id    1001   |  |
|   | total 99  |      | type  Order..|  |
|   +-----------+      | payload {..} |  |
|                      +--------------+  |
+----------------------------------------+
both commit, or neither does
|
v
+------------------+
|  Relay process   |
+------------------+
|
v
Message broker

The failure case it fixes

The process is killed one millisecond after commit. The event is still sitting in the outbox table. The relay picks it up on its next pass and publishes. Nothing lost, nothing phantom.Must-Know Message Broker Patterns - ByteByteGo NewsletterThe Transactional Outbox Pattern solves the "dual-write problem" in distributed systems. It ensures that a service can update its database and publish a corresponding event to a message broker (like Kafka or RabbitMQ) atomically, without needing a slow or fragile distributed transaction.


Getting events out

Two ways for the relay to read the outbox.

Polling

A worker queries for unpublished rows, publishes them, marks them sent.

SELECT * FROM outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED;

SKIP LOCKED is what stops two workers grabbing the same rows. Poll every 500 ms and median delivery lands around a quarter second.

Trade-off: trivial to build, no new infrastructure, works on any database. Costs constant polling load and latency bounded by your interval.Polling and Streaming - Concept & Scenarios - GeeksforGeeksPolling is the process where a computer program or a central device repeatedly checks an external device, a process, or a data source at regular intervals to see if it needs attention or has new information.

Log tailing (CDC)

Read the database’s own replication log — the WAL in Postgres, the binlog in MySQL — and emit an event whenever a row lands in the outbox. Debezium is the standard tool and ships a router built for this exact table shape.

Trade-off: no polling, millisecond latency, ordering inherited from the log. Costs real infrastructure — usually Kafka Connect — plus replication slot management.

Polling until it hurts, then CDC. Starting with Debezium for a service emitting twelve events a minute is a lot of operations for very little gain.

Either way, schedule a cleanup job on day one. The outbox receives every event your service emits and never shrinks on its own. Left alone it becomes your largest table and starts slowing down the transactions that write to it.Pattern: Transaction log tailingLog tailing is the act of watching the end of a log file in real-time as a system or application writes new data to it. It gets its name from the classic Unix command line tool tail -f, which prints the last lines of a file and keeps updating the screen as new lines appear.

Build Redis, Git, Docker & Claude Code From Scratch

Want to become a better software engineer?

Trusted by engineers at Google, NVIDIA, and Anthropic, CodeCrafters helps you rebuild technologies like Redis, Git, Docker, and Claude Code from scratch so you can deeply understand how real systems work.

We’ve partnered with CodeCrafters to give all readers an exclusive 40% lifetime discount.

💡 Engineers may expense platforms like this through their team’s learning budget.

Start Building & Unlock 40% Off

Implementing the Outbox PatternThe outbox pattern works by writing an event or message to a dedicated "outbox" table inside the exact same local database transaction used to update core business data. A separate background component, such as a poller or change data capture tool, then reads these stored records and publishes them to an external message broker.

Two things you have to design for