Skip to content

The transactional outbox: a write and a message as one step

A service that places an order does two things: it saves the order in its database, and it publishes an OrderPlaced event so that the other services find out. The saga needs it at every step. The two things go to two different systems, and there is no transaction that covers both. Either order of the two writes loses.

  • Save, then publish. If the service crashes between them, the order exists and no event does. Nobody else will ever hear of the order. Richardson’s pattern page puts it plainly: if a service sends a message after committing the transaction, there is no guarantee that it will not crash before sending it.
  • Publish, then save. If the save then fails, the event announces an order that does not exist, and other services act on it. The same page: if a message is sent in the middle of a transaction, there is no guarantee that the transaction will commit.

This is the dual-write problem. The way out in theory is two-phase commit between the database and the broker, and the pattern page explains why it is not used: the database or the broker may not support it, and it couples the service to both. Delivery semantics are the subject of the messaging module, which first showed this problem. This lesson is the full pattern.

Mental model. Post a letter and note it in your diary. If you do the two things separately, you can forget one. If the letter is put in the diary’s tray, and a clerk who reads the tray posts it, then writing in the diary and handing over the letter are a single action. The clerk may post a letter twice after a lunch break, but cannot forget one.

The transactional outbox removes the second write from the service’s own transaction. The service writes the event as a row in an outbox table in its own database, in the same local transaction as the business data. A separate process, the message relay, reads the outbox and publishes the messages to the broker. In SQL, the service does:

BEGIN;
INSERT INTO orders (id, status) VALUES (42, 'placed');
INSERT INTO outbox (id, type, payload, sent) VALUES (7, 'OrderPlaced', '{"orderId": 42}', false);
COMMIT;

and the relay repeats this loop:

SELECT id, type, payload FROM outbox WHERE sent = false ORDER BY id LIMIT 100;
-- publish each row to the broker, in order, and wait for the broker's acknowledgement
UPDATE outbox SET sent = true WHERE id = 7;

The order and its event are in one transaction, so they commit together or not at all. Richardson’s page states the guarantee: the messages are sent if and only if the database transaction commits, and they are sent in the order they were written. In a NoSQL database with no multi-document transaction, the outbox can be a property of each record.

There are two ways to build the relay. The polling publisher queries the table, as above. Transaction log tailing reads the database’s own log of changes instead; a change-data-capture connector, such as Debezium’s with its outbox event router, captures the changes made to the outbox table and publishes them. The polling relay is the simplest to build. The log reader avoids the poll interval and the repeated queries, at the price of a connector and a dependence on the database’s log.

The flow shows the outbox in four runs. Step through No failure first, then the other three.

The transactional outbox when the relay crashes

4 ms
20 ms
20 ms
500 ms
5 s
Compare

The service commits the order and the outbox row in one local transaction. The relay reads the unsent row, publishes it, marks it as sent, and the consumer gets the message once. This is the baseline.

542 ms
  1. One transaction writes the order and the message2 ms
    One local transaction: INSERT order 42 and INSERT outbox row 7 (OrderPlaced), COMMIT
    Order service to Order database (orders and outbox): One local transaction: INSERT order 42 and INSERT outbox row 7 (OrderPlaced), COMMIT. Arrives at 2 ms.
  2. 4 ms
    Committed: the order and its message exist together, or neither does
    Order database (orders and outbox) to Order service: Committed: the order and its message exist together, or neither does. Arrives at 4 ms.Processing: 500 ms
  3. The relay publishes506 ms
    Relay polls: SELECT unsent outbox rows
    Outbox relay to Order database (orders and outbox): Relay polls: SELECT unsent outbox rows. Arrives at 506 ms.
  4. 508 ms
    Row 7: OrderPlaced(order 42), not yet sent
    Order database (orders and outbox) to Outbox relay: Row 7: OrderPlaced(order 42), not yet sent. Arrives at 508 ms.
  5. 518 ms
    Publish OrderPlaced(msg-7)
    Outbox relay to Broker: Publish OrderPlaced(msg-7). Arrives at 518 ms.
  6. 528 ms
    Broker acknowledges
    Broker to Outbox relay: Broker acknowledges. Arrives at 528 ms.
  7. The relay marks the row as sent530 ms
    UPDATE outbox SET sent = true WHERE id = 7
    Outbox relay to Order database (orders and outbox): UPDATE outbox SET sent = true WHERE id = 7. Arrives at 530 ms.
  8. 532 ms
    Row 7 marked as sent
    Order database (orders and outbox) to Outbox relay: Row 7 marked as sent. Arrives at 532 ms.
  9. The consumer receives the message542 ms
    Deliver msg-7: the consumer applies the effect once
    Broker to Consumer: Deliver msg-7: the consumer applies the effect once. Arrives at 542 ms.Processing: 20 ms

Time until the consumer has handled the message and the row is marked as sent: 542 ms500 ms of processing

Model notes

Assumptions

  • Each message takes half the round-trip time of the link it crosses. Messages are never lost, never queue and never overlap, and each leaves when the one before it has arrived, once its receiver has finished any processing.
  • The order and its message are written in one local transaction of one database, as the outbox pattern requires. The relay is a separate process that reads unsent rows, publishes them and then marks them as sent; it keeps no state of its own.
  • The consumer’s inbox is a table of processed message ids in the consumer’s own database. It is written in the same local transaction as the effect, so the id and the effect are stored together or not at all.

Simplifications

  • Messages are drawn one after another. In a real system the broker delivers to the consumer as soon as it has the message, while the relay is still marking the row; the delivery is drawn last in the normal case to keep the flow in one line.
  • The consumer’s own database and its acknowledgement to the broker are not drawn: the time the consumer takes covers its local transaction. The wait for the relay’s next poll is drawn after the commit reply, as processing time.
  • Only a crash of the relay is drawn. A crash of the service before it commits leaves neither the order nor the row, and a consumer that fails is retried by the broker. Reading the outbox by polling is one way to do it; reading the database’s change log is another.

Parameter values are illustrative. They are not benchmarks of any real product.

With the defaults, No failure takes 542 ms and nine messages: the service’s transaction, the relay’s poll and its publish, the mark, and the delivery to the consumer. Only 42 ms of that is messages. The other 500 ms is Wait until the relay’s next poll, the default, which the flow draws after the commit reply. The polling relay turns “the event is safe” into “the event is published” after up to a full poll interval. Set the wait to 50 ms and the same run takes 92 ms. It is a trade: at 500 ms the relay queries the table twice a second, whether or not anything is waiting, and at 50 ms twenty times a second. Log tailing avoids both the wait and the queries, at the price of reading the database’s log.

The relay crashes before publishing takes 5,542 ms, which is 542 plus the 5,000 ms default of Time to restart the crashed relay. The relay read the row and died. After the restart the row is still unsent, so it is published then. The message is late by the restart time, and it is neither lost nor duplicated. This is the property that the dual write lacks.

The relay crashes after publishing, no inbox takes 5,616 ms and fourteen messages. The relay publishes row 7, receives the broker’s acknowledgement, and crashes before it marks the row as sent. After the restart it polls again, finds row 7 still unsent, and publishes it a second time. The consumer receives msg-7 twice and, with no inbox, applies the effect twice. The outbox gives at-least-once publishing, not exactly-once. Richardson’s page says so: the relay might publish a message more than once, for example by crashing after publishing and before recording the fact, so a consumer must be idempotent, perhaps by tracking the ids of the messages it has processed.

The relay crashes after publishing, with an inbox has the same crash and the same second message, and also takes 5,616 ms. The consumer records the message id in an inbox table in the same transaction as its effect, finds msg-7 already there on the second copy, and skips it. The effect happens once. The next lesson is about that inbox. For it to work, the id must be the same on every publication, and the outbox row’s id is what makes it so: an id drawn by the consumer, or by the relay at each publish, would be different each time and would deduplicate nothing.

The C# example runs the same story with a fake broker: first the dual write that loses an event, then the outbox, then the relay that crashes and reruns, and finally a consumer that remembers what it has handled.

C# exampleDual write against transactional outbox, with a duplicate-tolerant consumer
transactional-outbox.cs
// The transactional outbox: write the business row and the event in the same transaction,
// then let a relay publish the events. A crash can delay an event, but it cannot lose one.
using ShardCraft.Playground;
// 1. Dual write: save the order, then publish. A crash between the two loses the event.
var db = new OrderDb();
var bus = new MessageBus();
try
{
db.SaveOrder(1);
throw new InvalidOperationException("crash before publish");
}
catch (InvalidOperationException) { }
Console.WriteLine($"dual write orders={db.Orders.Count} published={bus.Pending} (order 1 saved, its event is lost)");
// 2. Outbox: the order and its event are saved atomically.
db = new OrderDb();
bus = new MessageBus(duplicateEvery: 2);
db.SaveOrderWithEvent(1);
db.SaveOrderWithEvent(2);
Console.WriteLine($"outbox orders={db.Orders.Count} outbox={db.Outbox.Count} published={bus.Pending}");
// The relay publishes unsent rows. It crashes after publishing event 1 but before marking it sent,
// so event 1 is published again on the next run: at-least-once.
var first = db.Outbox.First(o => !o.Sent);
bus.Publish(first.Body);
Console.WriteLine($"relay crash published={bus.Pending} sent={db.Outbox.Count(o => o.Sent)}");
foreach (var row in db.Outbox.Where(o => !o.Sent).ToList())
{
bus.Publish(row.Body);
row.Sent = true;
}
Console.WriteLine($"relay rerun published={bus.Pending} sent={db.Outbox.Count(o => o.Sent)}");
// The consumer sees duplicates, so it remembers the ids it has handled.
var handled = new HashSet<string>();
var effects = 0;
var deliveries = 0;
while (bus.TryReceive(out var m))
{
deliveries++;
if (handled.Add(m.Body)) effects++;
}
Console.WriteLine($"consumer deliveries={deliveries} effects={effects} (every order handled once)");
class OutboxRow(string body) { public string Body { get; } = body; public bool Sent { get; set; } }
class OrderDb
{
public List<int> Orders { get; } = [];
public List<OutboxRow> Outbox { get; } = [];
public void SaveOrder(int id) => Orders.Add(id);
// Both writes belong to one transaction: here, one method that cannot stop halfway.
public void SaveOrderWithEvent(int id)
{
Orders.Add(id);
Outbox.Add(new OutboxRow($"order-created:{id}"));
}
}
// In a real database the two inserts share one BEGIN/COMMIT, and the relay polls the outbox table or reads the log.
Output
dual write orders=1 published=0 (order 1 saved, its event is lost)
outbox orders=2 outbox=2 published=0
relay crash published=1 sent=0
relay rerun published=4 sent=2
consumer deliveries=4 effects=2 (every order handled once)

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

The dual write leaves orders=1 published=0: the order is saved and its event lost. The outbox saves both orders and both outbox rows with nothing yet published. The relay crashes after publishing the first event, leaving published=1 sent=0. On the rerun it publishes the first row again and then the second, and the fake broker duplicates every second message on purpose, as a lost acknowledgement would, so the broker holds published=4. The consumer sees 4 deliveries and, because it remembers what it has handled, produces 2 effects, one for each order. The code in the page is never run in the browser: the output was produced by a CI run of the same file.

What happens if the relay crashes after publishing?

Section titled “What happens if the relay crashes after publishing?”

This is the case the flow shows, and it follows from the order of the relay’s two steps. Publish first and mark second, and a crash between them gives a duplicate. Mark first and publish second, and a crash between them gives a lost message, which is the problem you started with. A message that is published twice can be dealt with, and one that is never published cannot be recovered, so the relay publishes first. The cost is that the duplicate becomes the consumer’s problem, and it is why the pattern has two halves: the outbox on the sending side, the inbox on the receiving side.

A second question is what happens to the table. Sent rows pile up. A real system deletes them after a while, or archives them, because a table that grows without limit makes every poll slower. How long to keep them is a decision about how much of a history to keep for support, and not about correctness.

Step of the framework For the transactional outbox
Decision Write the event to an outbox table in the same transaction as the data, and publish it with a relay.
Why A write to a database and a publish to a broker cannot be made atomic with a local transaction.
Benefits The event exists if and only if the data change committed. No two-phase commit, and the service is not coupled to the broker’s availability when it commits.
Costs An extra table and a relay to run and monitor. Events reach the broker after a delay. Every consumer must cope with duplicates.
Failure modes A relay that is down: events pile up in the table, late but safe. A relay that crashes between publish and mark: a duplicate. A relay that never runs: nothing is published, silently.
Scaling limits Polling costs a query per interval, however few messages wait. A single relay publishing in order is a throughput limit, and the table grows if sent rows are not deleted.
Alternative Read the database’s change log instead of polling, or store the state as events (event sourcing, which module 26 covers).

Monitor the age of the oldest unsent row. It is the number that says whether the relay is alive, and it grows even when nothing else looks wrong.

Check your understanding: the transactional outbox

This quiz needs JavaScript to check your answers.

Question 1 of 3

A service saves an order in its database and then publishes OrderPlaced to a broker. It crashes between the two.

What is the state after the restart?

Choose one answer.

Question 2 of 3

In the outbox flow with no failure, the database round trip is 4 ms, the network round trip is 20 ms, the relay polls every 500 ms, and the consumer takes 20 ms. The flow's total, 542 ms, is 42 ms of messages plus the wait for the poll.

The poll wait is set to 50 ms and nothing else changes. What is the flow's total now?

Enter a number and choose its unit.

Question 3 of 3

The relay publishes row 7 to the broker, receives the acknowledgement, and crashes before it marks the row as sent.

What does the consumer see after the relay restarts?

Choose one answer.

  • Saving data and publishing an event are two writes to two systems. Whichever goes first, a crash loses: an event with no order, or an order with no event.
  • The outbox stores the event in a table in the same transaction as the data. A relay reads the table and publishes. The event exists if and only if the data change committed.
  • With no failure the flow takes 542 ms, of which 500 ms is the poll wait; with a 50 ms poll it takes 92 ms. A relay that crashes before publishing makes the message late (5,542 ms) but not duplicated.
  • A relay that crashes after publishing and before marking the row publishes it twice (5,616 ms, 14 messages): the outbox is at-least-once, and the consumer must absorb the duplicate.
  • The alternative to polling is reading the database’s change log, which removes the wait and the repeated queries.

Next: the inbox, which makes the consumer safe against the duplicates the outbox can send.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.