Course contents

11. Microservices Lesson 8 of 10

Transactional Outbox

See why committing to a database and publishing to a broker cannot be atomic, and how an outbox table, a relay and idempotent consumers fix it.

16 minAdvanced11 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Writing to a database and then to a broker is a dual write: a failure or crash in between leaves them disagreeing.
  • The outbox writes the business change and the event in one local transaction, so both exist or neither does.
  • A relay (polling or CDC) publishes outbox rows and retries until the broker accepts them; outages delay events instead of losing them.
  • Publishing is at-least-once: relay crashes and broker redeliveries cause duplicates, so consumers must be idempotent.
  • Keep per-aggregate order with a partition key and a single publisher per partition.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

The transactional outbox is a pattern for publishing an event reliably whenever a service changes its data. Instead of writing to its database and then to a message broker, the service writes the change and the event, as a row in an outbox table, in one local database transaction. A separate relay reads new outbox rows and publishes them to the broker, retrying until it succeeds.

Why it exists

Services that own their data still need to tell others what happened: an order was placed, a payment captured. The obvious code saves the order, then publishes OrderPlaced. That is a dual write to two systems that do not share a transaction:

  • If the publish fails (broker down, network error) after the commit, the order exists but no one hears about it.
  • If the process crashes between the two steps, same result.
  • Publishing first is no better: a failed or rolled-back commit leaves an event for an order that does not exist.

Distributed transactions (two-phase commit/XA) across the database and broker could fix this in theory, but most brokers do not support them, and they couple the availability and latency of both systems. The outbox gets the same safety with only a local transaction.

How it works

  1. Write. In one transaction the service inserts or updates its business rows and inserts an outbox row: an event id, the aggregate type and id (e.g. order, 42), the event type, the payload, and a created timestamp.
  2. Relay. A relay finds unpublished rows and publishes them. A polling publisher runs something like SELECT … FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 100 every few hundred milliseconds (using FOR UPDATE SKIP LOCKED or a single active instance so relays do not fight over rows). A CDC relay such as Debezium tails the database's commit log (WAL, binlog) and publishes outbox inserts as they commit.
  3. Mark or delete. After the broker confirms, the relay marks the row as published or deletes it. A cleanup job removes old published rows.
  4. Consume idempotently. Because the relay can publish a row, crash before marking it, and publish it again, and because brokers redeliver unacknowledged messages, consumers deduplicate by event id, typically by inserting the id into a processed_events (inbox) table with a unique key in the same transaction as their side effect.

The result is at-least-once publishing: every committed change produces its event, possibly more than once. Together with idempotent consumers, processing is effectively once.

When to use it

  • A service must change its own data and notify other services, and losing or inventing an event would be a bug: orders, payments, inventory, account changes.
  • Choreographed sagas, where each step's event triggers the next service.
  • Feeding read models, search indexes or caches from a service's changes when a few hundred milliseconds of delay are acceptable.

When not to

  • When the event is a best-effort notification whose loss is harmless (analytics pings, cache hints).
  • When the database itself is the event log you share (event sourcing, where the appended events already are the source of truth and can be published from the store).
  • When the caller needs the downstream effect before it answers: a synchronous call, with its own failure handling, may be the honest design.

Trade-offs

Choice You gain You pay
Outbox instead of a dual write Change and event are atomic; broker outages do not fail writes Extra table and relay; events arrive slightly later
Polling relay Simple, works with any database Polling load and latency; must avoid concurrent relays publishing the same rows
CDC relay (log tailing) Low latency, no polling queries, no marking writes More infrastructure (connectors, log retention), tied to database internals
One publisher per partition Per-aggregate ordering Less publishing parallelism; a stuck row can block later ones

Alternatives

  • Two-phase commit (XA) across database and broker: atomic in theory, rarely supported, slow and fragile in practice.
  • Listen to yourself: publish the event first, and have the same service consume it to update its database. Works when the service can tolerate acting on its own event asynchronously.
  • Event sourcing: the event store is the database, so there is nothing to keep in sync.
  • CDC on the business tables directly (without an outbox table): no extra writes, but your internal schema becomes the public contract.
  • Broker transactions (e.g. Kafka transactions) cover writes inside the broker, not your database.

Failure modes

  • Relay down or slow: events pile up in the outbox. Nothing is lost, but consumers fall behind. Alert on the age of the oldest unpublished row.
  • Broker down: the relay's publishes fail and are retried; writes keep working. When the broker returns, a backlog burst hits consumers.
  • Duplicate publishes: crash between publish and mark, concurrent relays, or broker redelivery. Consumers must be idempotent.
  • Reordering: parallel relays, retries or multiple partitions can deliver an older event after a newer one. Key by aggregate id, keep one publisher per partition, and carry versions so consumers can ignore stale events.
  • Outbox growth: without cleanup the table grows forever and polling slows down.
  • Poison rows: a payload the broker rejects can block a strictly ordered relay; move it aside after a few attempts.

In production

Index the outbox on the unpublished predicate, publish in batches, and delete or archive published rows on a schedule. Run one active relay per partition (leader election or row locking) or use a CDC connector. Monitor outbox lag (oldest unpublished row), publish error rate and consumer duplicates. Include an event id, aggregate id and version in every event, and document that delivery is at-least-once so every consumer team builds idempotency in from the start.

Common misconceptions

  • "The outbox gives exactly-once delivery." It gives at-least-once publishing; exactly-once effects need idempotent consumers.
  • "Just publish after the commit and retry on failure." The retry lives in the memory of a process that can crash; the outbox puts the retry state in the database, in the same transaction as the change.
  • "Publish first, then commit, so nothing is lost." Then a failed commit leaves an event about something that never happened.
  • "Events will arrive in order." Only per partition, and only if the relay preserves order for each aggregate.

Interview angle

When a design has "save to the database and publish an event", interviewers expect you to spot the dual write and propose the outbox (or CDC) without being asked. Explain the single transaction, the relay, at-least-once publishing and idempotent consumers, then discuss ordering per aggregate, relay failure, outbox cleanup and how you would monitor lag. Mentioning why 2PC is avoided and when CDC beats polling shows depth.

Model assumptions

Parts of this lesson are simulated and parts are scripted. Simulated by the queueing engine: shoppers placing 20 orders per second (random arrivals, all writes), the Orders API (16 workers, 10 ms) writing to the database (8 ms writes), the naive design's publish to the broker and its failure while the broker is down, the relay publishing to the broker and retrying with backoff (up to 12 attempts, 250 ms doubling to 1 s), and Shipping consuming with acknowledgements, a visibility timeout and redelivery (duplicates are counted, not hidden). The relay is modelled as a steady publisher at the order rate; it is not driven by actual outbox rows, and the engine does not model transactions, the outbox table or row marking. A real relay keeps retrying indefinitely. Scripted (hand-placed packets): the API crash between commit and publish, the relay crash that republishes event #42, the idempotent consumer's deduplication (the engine does not model idempotency), the polling queries and the CDC log records. Numbers show behaviour and orders of magnitude, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Save the order, then publish the event

    When a shopper places an order, the Orders API commits it to its database and then publishes an OrderPlaced event to the broker, so Shipping can pack it. Two writes to two different systems: a *dual write*.

    While everything is healthy this looks fine. Every order is saved, every order produces exactly one event and Shipping processes all of them.

    Scene: Shoppers send orders to the Orders API, which writes each one to the Orders DB and then publishes an event to the Broker; Shipping consumes the events. Everything succeeds.

    Key idea: A dual write updates two systems in two separate steps. Nothing makes them succeed or fail together.

  2. 2. The broker goes down after the commit

    One second in, the broker goes down. Each order is still committed to the database, then the publish fails and the API returns an error.

    Now the systems disagree: the shopper sees “something went wrong”, the order exists in the database, and Shipping never hears about it. If the shopper retries, there may be two orders. Rolling back is not possible any more: the commit already happened.

    Scene: The broker goes offline. Orders are still written to the database, but publishing fails, so shoppers get errors for orders that were saved and Shipping receives no events for them.

    Key idea: Commit first, publish second: a failed publish leaves a committed order with no event.

  3. 3. Even a healthy broker is not enough

    The broker is back. This time the Orders API process crashes a few milliseconds after the database confirms the commit and before it publishes (a deploy, an out-of-memory kill, a lost network connection).

    Same result: a saved order, no event. Publishing first does not help either: then a crash or a failed commit leaves an event for an order that does not exist. Without a transaction that spans both systems, there is always a moment where one write has happened and the other has not.

    Scene: A single order: the API writes it to the database and receives the commit confirmation, then crashes before publishing. Nothing reaches the broker.

    Key idea: There is no ordering of two independent writes that survives a crash in between.

  4. 4. Write the event into the same transaction

    The fix is to stop writing to two systems. The API inserts the order and an OrderPlaced row into an outbox table in the same database, in one transaction. Either both rows are committed or neither is.

    The API no longer talks to the broker at all, so a broker outage cannot fail an order. Orders are fast and none fail. But for now the events just sit in the outbox: nothing publishes them yet.

    Scene: The API writes each order and its event to the Orders DB in one transaction and no longer calls the broker. Orders succeed; the broker receives nothing.

    Key idea: One local transaction writes the business change and the event together: they can no longer disagree.

  5. 5. A relay publishes from the outbox

    A separate outbox relay polls the table every few hundred milliseconds (SELECT … WHERE published_at IS NULL ORDER BY id), publishes each event to the broker and, once the broker confirms, marks the row as published.

    Events now flow again, a little later than before: the delay is the polling interval plus the publish. Orders and events can no longer disagree, because the event exists exactly when the order does.

    Scene: The Outbox Relay polls the Orders DB for unpublished events and publishes them to the Broker; Shipping consumes them. Orders and events flow at the same rate.

    Key idea: The relay turns “committed in the database” into “published to the broker”, retrying until it succeeds.

  6. 6. The broker goes down again

    One second in, the broker fails again, this time for two and a half seconds. Orders do not notice: they only touch the database, and no order fails.

    The relay’s publishes fail (the red packets) and it retries with backoff; the events wait safely in the outbox. When the broker returns, the relay catches up and the backlog flows to Shipping in a burst. An outage now delays events instead of losing them. A relay outage works the same way: rows wait until it is back.

    Scene: The broker is offline for 2.5 seconds. Orders keep succeeding; the relay’s publishes fail and are retried, and after the broker recovers all events are published and Shipping catches up.

    Key idea: With an outbox, a broker or relay outage only delays events. Monitor the age of the oldest unpublished row.

  7. 7. Published twice

    The relay has the same problem one level down: publishing and marking the row are two steps. Here it publishes event #42, the broker confirms, and the relay crashes before marking the row.

    After the restart it polls again, finds #42 still unpublished and publishes it a second time. Shipping receives the same event twice. This is not a bug in the relay; it is the guarantee: the outbox gives at-least-once publishing. Nothing is lost, but duplicates are possible.

    Scene: The relay reads event 42, publishes it and gets the broker’s confirmation, then crashes before marking the row. After restarting it reads event 42 again and publishes it a second time; Shipping receives it twice.

    Key idea: The outbox never loses an event, but it may publish one more than once.

  8. 8. The broker redelivers too

    Duplicates also come from the other side. The broker delivers each event to Shipping and waits for an acknowledgement. Shipping’s carrier API has become erratic: most calls take about 300 ms, a few take seconds, longer than the 1-second visibility timeout.

    The broker assumes Shipping died and delivers those events again, while the first attempt is still running. Both attempts finish: the same order is processed twice. Every hop in the chain is at-least-once.

    Scene: Some Shipping calls take longer than the 1-second visibility timeout, so the broker redelivers those events and Shipping processes them twice.

    Key idea: Assume every event can arrive more than once, from the relay or from the broker.

  9. 9. Make the consumer idempotent

    Shipping cannot prevent duplicates, so it makes them harmless. Every event carries a unique id (the outbox row id). In the same transaction as its own work, Shipping inserts that id into a processed_events table with a unique key.

    The first delivery of #42 inserts the id and creates the shipment. The duplicate hits the unique key, so Shipping skips the work and simply acknowledges the message. At-least-once delivery plus an idempotent consumer gives *effectively-once* processing.

    Scene: Event 42 arrives at Shipping, which records its id and creates the shipment in one transaction, then acknowledges. The duplicate of event 42 hits the unique key, so Shipping skips the work and acknowledges it anyway.

    Key idea: Deduplicate on the consumer: record processed event ids in the same transaction as the side effect.

  10. 10. Ordering, and tailing the log instead

    The relay publishes rows in id order, but retries and several relay instances can reorder events. If Shipping must see OrderPlaced before OrderCancelled, publish with the order id as the partition key so one order’s events stay in sequence, run one publisher per partition, and let consumers ignore events older than the version they have.

    Polling is not the only relay. Change data capture (CDC, e.g. Debezium) tails the database’s commit log and publishes new outbox rows as they are committed: lower latency and no polling queries, but another piece of infrastructure. It is still at-least-once.

    Scene: A CDC connector reads new outbox rows from the database’s commit log and publishes them to the broker, keyed by order id; orders and events keep flowing.

    Key idea: Keep per-aggregate order with a partition key; CDC is an alternative relay with the same at-least-once guarantee.

  11. 11. What the outbox gives you

    The outbox replaces an unsafe dual write with one local transaction plus a reliable, retrying publisher. Orders never depend on the broker being up, and every committed change eventually produces its event.

    In exchange: events arrive a little later, the outbox table needs cleaning up, the relay is one more thing to run and monitor, and delivery is at-least-once, so every consumer must be idempotent and ordering must be designed per aggregate.

    Scene: Shoppers write orders and outbox rows to the Orders DB; the CDC connector publishes the events to the Broker; Shipping consumes them and records processed event ids in its own database.

    Key idea: Outbox = atomic “change + event” locally, at-least-once publishing, idempotent consumers.