An order lands at 14:07. The database commits. The customer sees a confirmation page and an email arrives within seconds. Somewhere downstream, a warehouse management system never receives the pick instruction, because the publish call to the event broker timed out and the retry sat inside a request handler that had already returned. Nobody notices for eleven hours, until a customer writes in to ask where their parcel is.
That gap is not exotic. It exists in almost every service that saves a record and then tells another system about it, and it stays invisible until the day the broker is slow, the network hiccups, or the process is killed between the two operations. The fix is old and boring: put the event in the database, in the same transaction as the record, and let a separate process move it out. The pattern is called the transactional outbox, and it is the piece most order systems are missing.
Two writes, one lie
Saving an order and publishing order.created are two writes against two systems that know nothing about each other. The database cannot enlist Kafka in its transaction. Kafka cannot roll back a committed row. So the operation has four possible endings, and only two of them are correct.
- Both writes succeed. The order exists and the warehouse gets the instruction. Correct.
- Both writes fail. No order, no event, the customer retries. Correct.
- The commit succeeds and the publish fails. The order exists in your database and in the customer's inbox, but the warehouse, the ERP, the loyalty ledger and the analytics pipeline never hear about it.
- The publish succeeds and the commit rolls back. A warehouse starts picking an item nobody bought, or a receipt goes out for an order that does not exist.
The third case is the one that hurts, because it is silent. Nothing throws. The API returns 201. Logs show a warning at most. The only evidence is a customer asking a question eleven hours later, and by then the reconciliation work is manual.
Retries in the request handler do not fix this. They shrink the window rather than close it, and they add a new failure: a retry that succeeds twice, which produces duplicate events that the downstream consumer has to survive anyway.
Two-phase commit is not the answer
The textbook answer is a distributed transaction. In practice, XA and two-phase commit have been losing ground for a decade for good reasons. The message broker has to support it, most hosted brokers and queues do not. A prepared transaction holds locks across a network round trip, so latency climbs and a coordinator failure leaves rows stuck in a prepared state. And the pattern does not reach outside your own infrastructure at all, which matters when the destination is a tax engine, a payment provider or a partner's webhook endpoint.
There is also a simpler objection. Most teams do not need a guarantee that the event is published. They need a guarantee that the event is not lost, and that it is eventually published once. Those are different problems, and the second one is solvable with an ordinary local transaction.
The outbox is a table, not a framework
An outbox row is written by the same transaction that writes the business record. That is the entire trick. If the commit succeeds, the event row exists. If the transaction rolls back, the event row does not. There is no third state.
The table can stay narrow. A monotonically increasing id, an aggregate id, an event type, the payload as JSON, a created timestamp, and a nullable published timestamp. If you use Postgres, add a partial index on published_at IS NULL so the relay only scans live rows, and keep the payload under a few kilobytes by storing ids and the fields consumers actually need rather than a full object graph.
The write path becomes three statements inside one transaction: insert the order, insert the outbox row, commit. The publish moves somewhere else entirely, out of the request path, which is a second benefit most teams notice first. Checkout stops waiting on a broker round trip.
Moving rows out: polling or log tailing
Two relay designs cover nearly every case.
A polling relay selects a batch of unpublished rows with FOR UPDATE SKIP LOCKED, publishes them, marks them published, and repeats. SKIP LOCKED matters because it lets several relay workers run at once without fighting over the same rows, which is how you scale the relay without sharding it yourself. The cost is a query every few hundred milliseconds, and that cost is real on a busy database: constant index scans, plus write amplification from the update that marks each row published.
Log-based capture, usually Debezium reading the Postgres write-ahead log with wal_level=logical, removes the polling cost entirely. Nothing in the application changes, the database does not do extra scans, and throughput scales with the log rather than with your query budget. You pay in operational surface: a connector to run, monitor and upgrade, plus a coupling between your table schema and the event stream, since every column you add becomes something the connector ships.
Start with polling. A relay that keeps up with a few hundred thousand events a day is a few hundred lines of code and one cron loop. Move to log capture when the scan cost appears in your slow query log, not before, because the connector is another system whose failure modes you now own.
Duplicates are part of the contract
No relay gives you exactly-once delivery, and a design document that claims otherwise is worth reading twice. The relay can crash after the broker accepts the event and before the published flag is set. On restart it republishes. The event arrives twice, and the system is behaving correctly.
That means the consumer owns deduplication. The usual shape is an inbox table: a unique constraint on the event id, an insert that does nothing on conflict, and the side effect performed in the same transaction as that insert. If the event arrives again, the insert hits the constraint and the work is skipped. For destinations outside your database, use the provider's own idempotency key, which most payment and email APIs expose for exactly this reason, and make the key derive from the event id rather than from a random value generated at send time.
The failure to watch for is a consumer that dedupes on a field it controls. A dedupe key built from order id plus timestamp breaks the moment a legitimate second event shares that timestamp. Key on the event id that the outbox generated, and never regenerate it downstream.
Ordering holds per key, not per system
Ordering is the part teams assume and then discover is narrower than they thought. If you publish to Kafka and partition by aggregate id, all events for one order land on one partition and arrive in order. Events for different orders interleave, which is fine until a consumer builds a state machine that assumes the whole stream is sequential.
So choose the partition key deliberately, and treat any consumer reading from multiple partitions as concurrent by default. The other cost is head-of-line blocking: a slow message holds up everything behind it in that partition, so one poison event for one order can stall unrelated orders for as long as the retries run. That is why the dead-letter path has to exist before launch rather than after the first incident.
The chores nobody budgets for
The happy path takes a day to build. The rest is operational, and skipping it is how an outbox earns its reputation for being heavier than it is.
Retention is the one that bites. Published rows are dead weight, and an outbox that never trims becomes the largest table in the database within a year. Partition by day and drop old partitions, or delete in bounded batches so autovacuum can keep up. A single unbounded DELETE over six months of rows will bloat the table and hold locks long enough to be felt.
Monitoring needs the right number, which is not queue depth. It is the age of the oldest unpublished row. Depth looks healthy when consumers are slow and the relay is fine; age catches the case where the relay has silently stopped. Alert on p95 lag crossing a minute, and alert separately on lag existing at all for more than a few minutes, because the second alert fires before the first one ever will.
Payloads have a way of growing. Teams paste whole objects into events, and then a schema change in one service breaks a consumer in another. Keep the event minimal and treat it as a record of what happened. If a consumer needs current state, it should fetch current state and accept that it is reading now rather than then. Mixing the two produces events that mean something different depending on when they are replayed.
The last piece is the poison path. An event a consumer can never process will retry forever, and forever means it occupies a worker slot and a partition position. Cap attempts, write the raw payload to a dead-letter table with the failure reason, and put the count on a dashboard. Without that, the first malformed event quietly becomes a backlog.
When an outbox is overkill
If one service owns one database and the only consumer is a scheduled job in the same codebase, a plain job table with the same transaction boundary gives you the durability without the broker, the relay and the dedupe contract. The idea is the same. The infrastructure is a table and a loop.
If the destination can be rebuilt from the source of truth in twenty minutes, a periodic full rebuild is often cheaper than an event pipeline. A product index that rebuilds nightly does not need per-change events until the rebuild time stops fitting in the window, or until someone needs the index to be correct within minutes rather than hours.
And if your platform already provides transactional publishing, where the broker is genuinely inside the database's commit boundary, use it and skip this article. That is the case the pattern exists to work around.
A rollout that does not need a rewrite
The migration is incremental, and it should be, because the risky part is changing consumer behaviour rather than adding a table.
Start with the paths where a lost event costs money: order placement, payment capture, refunds and inventory decrement. Add the outbox table and write to it inside the existing transaction, but leave the direct publish in place and behind a flag, so nothing about production behaviour changes on day one.
Then run the relay in shadow mode. It publishes from the outbox to the same topics the direct path uses, and for a week you compare counts and ids between the two paths. Mismatches are free information: they show you exactly which code paths commit without announcing themselves, which is usually more than anyone expected.
Move consumers to deduplication before you switch anything off. This is the step teams skip, and it is the step that decides whether the cutover is a non-event. Once every consumer tolerates a duplicate, turn off the direct publish for one path, watch the lag for a day, then continue. The flag stays in the codebase long enough to be dull, and then it gets deleted.
Questions worth asking about your own system
Most teams can answer the first one and struggle with the rest, which is a fair summary of where the industry is with this problem.
- If the process dies between the commit and the publish, what reconciles the difference, and how long does it take?
- Can every consumer survive the same event twice without double-shipping, double-charging or double-crediting?
- What is the age of the oldest unpublished outbox row right now, and who gets paged when it crosses a minute?
- Can you reconstruct the event history for order 8471 from last Tuesday, and would it match what the downstream systems received?
An outbox will never appear in a product demo. It appears in the incident review you do not have, because the order that committed and never announced itself does not happen. That is the return: one narrow table, one relay, one dedupe rule on the consumer, and the window between two writes closes for good.