microservice.guru
← All posts

The Dual-Write Problem and the Transactional Outbox

· Architecture · Microservices · Messaging · Reliability

By Alain Cyr, Founder, Koesion

microservice.guru — The dual-write problem and the outbox. Two separate writes with a crash in between, versus two inserts in one transaction.

Here are two lines that exist in almost every event-driven service:

await db.claims.insert(claim)
await broker.publish('ClaimRegistered', claim)

They pass review and they pass every test. Then one day the process is killed between the first line and the second. A deploy, an out-of-memory kill, a broker that takes too long to answer. It does not matter which.

Sequence: Claims inserts claim 4711 and the database commits; the process is killed; the publish never reaches the broker; Reserving never hears about the claim

No exception, no error log, no alert. Just a claim with no reserve.

The claim is in the database. The event was never sent. Reserving does not know the claim exists, and nothing anywhere records that something went wrong. Somebody in finance finds it at month-end, along with thirty-six others.

This is the dual-write problem: one piece of code, two systems to update, and no transaction that covers both.

Reordering does not help

The usual first reaction is to shuffle the lines.

Table of four orderings: save then publish, publish then save, publish inside the transaction, and two-phase commit, each with the way it fails

Each row is a fix somebody has proposed in a design review.

Publish first, and you will sooner or later announce a claim whose insert then fails on a constraint. Other services now act on a claim that does not exist, which is worse than the original bug.

Publish inside the database transaction, and you have the same phantom event whenever the commit fails after the publish. You are also holding a database transaction open across a network call, and your connection pool will have something to say about that.

Two-phase commit across the database and the broker does solve it on paper. In practice most brokers you would pick today do not take part in one, and the operational cost has kept nearly everybody away.

The underlying fact is plain. You cannot write to two systems atomically, so stop trying and write to one.

The outbox

In the same local transaction that inserts the claim, insert a second row into a table called outbox, describing the event you want to send.

BEGIN;
INSERT INTO claim (id, policy_id, status) VALUES ('4711', 'P-88', 'REGISTERED');
INSERT INTO outbox (id, aggregate_id, type, payload)
VALUES (gen_random_uuid(), '4711', 'ClaimRegistered', '{"claimId":"4711"}');
COMMIT;

Both rows are written or neither is. That is an ordinary database transaction, the thing databases do best. A separate piece, the relay, reads new outbox rows, publishes them to the broker and marks them as sent.

The Claims service writes the claim row and the outbox row in one local transaction; a relay reads new outbox rows, publishes them to the broker and marks them sent

The service never talks to the broker. It only ever writes to its own database.

Now look at what happens when things die. If the service crashes before the commit, there is no claim and no event. If it crashes after, both are there, and the relay will get to the event when it next runs. If the broker is down for an hour, rows wait in the table and go out when it returns.

One failure is left. The relay publishes a row and crashes before marking it. On restart it publishes the row again. So the outbox guarantees that every event is delivered at least once, and sometimes twice. You have swapped lost events for duplicate events, and that is the right trade, because duplicates can be handled by the consumer and lost events cannot be handled by anybody.

Running the relay

There are two ways to build it.

Comparison of a polling relay and log tailing: how each works, delay, extra infrastructure, load on the database, and when to start with it

Polling is not the unsophisticated option. It is the one with fewer parts.

A polling relay is a loop that selects unsent rows every few hundred milliseconds, with FOR UPDATE SKIP LOCKED so that two instances do not grab the same ones. It is twenty lines of code and I would start there.

Log tailing reads the database’s own change log, typically with Debezium, and turns outbox inserts into messages. It is faster and puts no query load on the database. It is also a new component for somebody to run and upgrade.

Whichever you pick, a few details decide whether it works in production:

The same problem in other clothes

Once you have seen the dual write, you find it elsewhere. “Update my state, then call the payment API” is the same shape, and the outbox works there too: the row holds a command, and the relay makes the call.

The mirror image sits on the consuming side. “Process the message, then acknowledge it” is two steps as well, which is why a message can be processed twice. The answer there is an idempotent consumer, and it is the subject of the next post.

Write to one place, in one transaction. Let something else carry it to the second place, and expect it to arrive twice.

Where to go next

References