Search for a command to run...

A customer places an order on your store. Your API saves the order, then publishes an OrderPlaced event so the warehouse can pick it and the customer gets a confirmation email. The API returns 200. The customer sees "Order confirmed". Then nothing happens — no email, no pick list. The order sits in the database, invisible to everything downstream.
Nobody threw an exception. Nothing logged an error. The save succeeded and the publish failed — or the publish succeeded and the save failed, and now the warehouse is picking an order that does not exist. This is the dual-write problem, and it is the single most common reliability bug in systems that write to a database and a message broker in the same request.
The Outbox pattern fixes it with a deliberately boring idea: don't write to two systems. Write to one — the database — and let a background process move the message to the broker. One transaction, one write. Everything else is plumbing.
A typical checkout handler looks like this: save the order, then publish the event. Two writes, two systems, no shared transaction. There is a crash window between them, and it is not theoretical — a process recycle, a network blip, or a broker restart at the wrong millisecond is all it takes.
If the process dies after write 1 and before write 2, the order exists but no one ever hears about it. If you reverse the order — publish first, save second — the event can announce an order that was never saved. Either way, two systems that were supposed to agree now disagree, and nothing in your logs tells you, because each write succeeded on its own.
The textbook answer is a distributed transaction — two-phase commit across the database and the broker. In practice, that answer is dead: XA transactions are not available across PostgreSQL and RabbitMQ or Kafka in any .NET stack you would actually run, and even where they exist, they trade a rare inconsistency for a permanent availability and latency cost. You do not need atomicity across two systems. You need to stop writing to two systems.
Add an OutboxMessages table to the same database that holds your orders. When the handler saves the order, it inserts the event into the outbox table in the same transaction. The order row and the message row commit together or not at all — the database guarantees it, no distributed anything required.
A separate background process — the relay — reads unpublished rows from the outbox, publishes them to the broker, and marks them processed. If the relay crashes mid-publish, the row stays unpublished and gets retried. The message is eventually delivered, and the order and the event can never disagree about whether the order exists.
There is one honest trade-off, and the whole pattern is built around it: delivery is at-least-once, not exactly-once. The relay can publish a message and crash before marking it processed, so a consumer may receive the same event twice. That is a constraint you design for, not a bug you can eliminate — and it is a far cheaper problem than a lost event.
The outbox table is small and boring, which is exactly the point. One row per message, with enough metadata to retry, inspect, and eventually give up:
Keep the payload as plain JSON text. Do not store a serialized .NET object graph with type names baked in — the relay that reads this row six months from now should not need the exact assembly version that wrote it. The Type string is the contract; the payload is the data.
The handler changes by one line. The order and the message are added to the same DbContext, and a single SaveChangesAsync commits both. If the save fails, neither exists. If it succeeds, both exist:
Notice what disappeared: the broker call left the request path entirely. The API no longer depends on the broker being up to accept an order. If RabbitMQ is down for maintenance, checkouts keep working — events pile up in the outbox and drain when the broker returns. That decoupling is a real availability win, not a side effect.
The relay is a BackgroundService that polls the table, publishes a batch, and marks the batch processed. Polling every couple of seconds is fine for almost every store — order confirmation emails do not need sub-second latency, and polling is simple, observable, and easy to reason about. If you genuinely need lower latency later, replace polling with logical replication or a change-data-capture tool; the outbox table does not change.
Two details matter here. First, the mark-as-processed and the retry-count update commit in one SaveChangesAsync, so the relay's bookkeeping is itself transactional. Second, the batch size and the delay are the only tuning knobs, and the defaults above are a sane starting point — do not over-engineer this before you have measured it.
On PostgreSQL, take the batch with FOR UPDATE SKIP LOCKED if you ever run more than one relay instance, so two relays never pick up the same row. On SQL Server, the equivalent is WITH (ROWLOCK, READPAST). One relay is enough for most systems; add the locking hint when you scale out, not before.
This is the part people skip, and it is the part that decides whether the pattern actually works. The relay can publish a message and crash before marking it processed. The next poll publishes it again. Your consumer will see OrderPlaced twice, and it must handle that gracefully.
The fix is the inbox pattern on the consumer side: a table of processed message IDs, checked inside the same transaction as the consumer's own work. If the ID is already there, the message is a duplicate — acknowledge it and move on. Alternatively, design the consumer's work to be naturally idempotent: an email sender that upserts by order ID, a stock decrement that keys on the event ID, a warehouse pick list that ignores an order it already holds.
This pairs directly with idempotency keys on the write side. An idempotency key protects the API from a client retrying the same request; the outbox protects the system from losing the event after the request succeeded. Same idea at two different boundaries: never apply the same effect twice.
Three operational questions come up with every outbox, and each has a boring answer:
Ordering. Process rows in CreatedAt order and you get global order for free at low volume. At high volume, order per aggregate instead — all events for one order, in order — and design consumers to tolerate out-of-order events across different aggregates. Most consumers do not need global order; they need per-order order.
Retries. A transient broker failure should retry with a delay, not immediately and not forever. The RetryCount cap above (5) moves a poison message out of the hot path; the Error column tells you why. A dead-lettered message is a row you can inspect and republish by hand — far better than an event that vanished into a log file.
Cleanup. Processed rows are history. Archive or delete rows older than a retention window (30 days is a common default) with a nightly job. Do not let the table grow forever — the relay's query stays fast only if the table stays small.
Not every message needs an outbox. If the producer and the consumer live in the same process and share the same database, in-process domain events dispatched after SaveChangesAsync are simpler and sufficient. If you need sub-100ms delivery, polling adds latency you will feel — reach for change-data-capture instead of a polling relay, or accept the latency and measure it first. And if your broker already participates in a transaction with your database — SQL Server Service Broker, or PostgreSQL LISTEN/NOTIFY for lightweight cases — use the mechanism you already have.
The pattern earns its place exactly where most e-commerce systems live: a relational database, a separate broker, and a business rule that says the order and the event must agree. Checkout, payment confirmation, stock reservation, shipment notification — every one of these is an outbox-shaped problem.
One transaction, one write. If your handler writes to the database and publishes to a broker in the same request, you already have the dual-write bug — you just haven't met the crash window yet.
The Outbox pattern does not add a framework, a new service, or a distributed transaction coordinator. It adds one table, one background loop, and one discipline on the consumer side. In exchange, the class of bug where an order exists but nobody knows about it stops being possible. That is a trade worth making in any system where the order matters — and in an e-commerce checkout, the order always matters.
A list of orders in memory, rows streaming out of a database, pages from an API - from the consumer's side they are the same question: give me the next item, and tell me when there are no more. The Iterator pattern is that question answered as an interface pair, and in .NET it is the shape of foreach and LINQ themselves: hand-built enumerators, yield return, deferred execution, and the async twin IAsyncEnumerable<T> - including the costs, and when a List is the honest answer.
An order is placed, and five parts of the system need to know. The Observer pattern flips who knows about whom: the publisher announces one fact, subscribers come and go, and the publisher never changes. From hand-built subjects to C# events, IObservable<T>, and MediatR notifications - with the push and pull models demonstrated in code - including the costs, and when a direct call is the honest answer.
A price is not a decimal, a phone number is not a string, and an email is not a string either. Primitive obsession is the habit of modelling domain concepts with the language's built-in types — and value objects are the small, boring, enormously effective fix.