الانتقال إلى المحتوى
Software ArchitectureMicroservices· 8 دقائق للقراءة

Save Then Publish Is Not Atomic: The Dual-Write Problem and the Outbox

No transaction covers your database and your broker, so a failure between the two writes loses events silently. Commit the event with the data and relay it.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

A customer asks support why her paid order never shipped. The Orders database has the order, Payments charged the card, and Shipping has never heard of it. The only clue is timing: the Orders instance that saved it was shut down during a deploy a moment later. No log line mentions a lost event, because the line of code that would have published it, or failed loudly, never ran.

The common misconception

The belief: saving to the database and then publishing an event is reliable enough, because both calls almost always succeed. If the broker were down, someone would notice the errors.

It's what most first versions look like, and it passes every test. The gap between the two calls is tiny, and in development nothing crashes inside it. Microsoft's own microservices guide shows this shape first, with a fair warning that it's "a simplified example that does not take atomicity into account." And a broker outage does produce exceptions. The trouble is when: after the commit, an exception only tells a user that an order which was actually placed has failed.

What actually happens

Two writes, no shared transaction

Gunnar Morling's Debezium post names the root cause: "we cannot have one shared transaction that would span the service’s database as well as Apache Kafka, as the latter doesn’t support to be enlisted in distributed (XA) transactions." That's a , and every ordering of it has a failure mode:

  • Save, then publish: a crash, a deploy or a broker outage in between loses the event. Microsoft's outbox guide lists network errors, message service outages and host failures, and warns that "Lost events can cause data inconsistencies across the application."
  • Publish, then save, or publish inside the transaction: as Chris Richardson puts it, "There’s no guarantee that the transaction will commit." Consumers then act on an order that doesn't exist. The article on domain events and integration events shows this one in detail.
  • Publish, and the acknowledgment gets lost: the broker has the message, the caller sees an error and retries, and now there are two.

"Almost always" misses the point. The gap is open on every request, and when it bites, the result is silent and permanent: no retry happens, because nothing remembers that an event was owed.

Why not a distributed transaction

Richardson's pattern rules it out in one line: "The database and/or the message broker might not support 2PC. Also, it’s often undesirable to couple the service to both the database and the message broker." Kafka, as above, doesn't support it at all. Microsoft's guide advises against it too, "for the reasons described by the CAP theorem": a commit that needs both systems up fails whenever either one is down.

Write once, derive the second

Morling's answer: "only modify one of the two resources (the database or Apache Kafka) and drive the update of the second one based on that, in an eventually consistent manner." You can write only to the broker and have the service consume its own events, but then it loses "read your own write" semantics for its own data. You can adopt full event sourcing, which Microsoft's guide notes requires rearchitecting most of the system. Or you can write only to the database, with a : store the message "in the database as part of the transaction that updates the business entities. A separate process then sends the messages to the message broker." The result, in Richardson's words: "Messages are guaranteed to be sent if and only if the database transaction commits".

The relay: polling or the transaction log

The separate process, the relay, comes in two styles. A polling publisher queries the outbox for unpublished rows: it "Works with any SQL database", but it's "Tricky to publish events in order". Log-based change data capture, as Debezium does it, reads the database's transaction log instead; Morling notes that "As opposed to any polling-based approach, event capture happens with a very low overhead in near-realtime." Either way, order matters: Microsoft's outbox guide stresses that an OrderCreated event must go out before OrderUpdated, and Debezium keys messages by the aggregate's id so all events of one order land in one partition, in order.

The fix: one transaction, then a relay

C# PlaceOrder.cs
public sealed class PlaceOrder(ShopDb db, IMessageBus bus){    public async Task HandleAsync(Order order, CancellationToken ct)    {        db.Orders.Add(order);        await db.SaveChangesAsync(ct); // committed        // A crash, deploy or broker outage here: the order exists,        // and no other service will ever hear about it        await bus.PublishAsync(new OrderPlaced(order.Id, order.Total), ct);    }}

The order and its message now commit together or not at all. Publishing is the relay's job:

C# OutboxRelay.cs
using Microsoft.EntityFrameworkCore;public sealed class OutboxRelay(ShopDb db, IMessageBus bus){    public async Task PublishPendingAsync(CancellationToken ct)    {        var pending = await db.Outbox.Where(m => m.PublishedAt == null)            .OrderBy(m => m.Sequence) // the order they were written in            .Take(100).ToListAsync(ct);        foreach (var m in pending)        {            await bus.PublishAsync(m.Id, m.Type, m.Payload, ct);            // A crash here publishes this row again on the next run            m.PublishedAt = DateTime.UtcNow;            await db.SaveChangesAsync(ct);        }    }}

That comment is the deal you accept. Richardson: the relay "might, for example, crash after publishing a message but before recording the fact that it has done so. When it restarts, it will then publish the message again." Delivery becomes at least once, which is why each message carries the outbox row's id: consumers record it and skip repeats, as the previous article on idempotent consumers shows. The domain events article shows the .NET wiring around it.

ApproachWhat can go wrong
Save, then publishA crash in between loses the event, silently
Publish, then saveThe save fails and consumers act on data that doesn't exist
Distributed transactionOften unsupported, couples both systems, fails when either is down
Outbox with a polling relayDuplicates, so consumers dedupe; order needs care; adds a little latency
Outbox with log-based captureDuplicates too, plus database-specific tooling to run

How to apply it in your project

  1. Find the dual writesSearch for broker publishes, emails, cache updates and HTTP calls that run right after SaveChangesAsync or inside a transaction.
  2. Add an outbox tableStore an id, a type, a payload and a sequence number in the same database as the business data.
  3. Write in one transaction, relay separatelyInsert the message with the business change in a single SaveChangesAsync, and run one relay that publishes pending rows in order.
  4. Make consumers idempotentUse the outbox row's id as the message id, and have every consumer record the ids it has processed.

Key takeaways

  • Saving and then publishing is a dual write: no transaction covers both, so a failure between them goes unnoticed.
  • Every ordering fails somewhere: lost events, events about rolled-back data, or duplicates.
  • Distributed transactions are usually unavailable or undesirable; write once and derive the second write.
  • An outbox row committed with the business change guarantees the message is published if and only if the change commits.
  • The relay delivers at least once, so consumers must dedupe on the message id.

📚 المصادر

  1. Pattern: Transactional outbox — Chris Richardson, microservices.io
  2. Pattern: Polling publisher — Chris Richardson, microservices.io
  3. Reliable Microservices Data Exchange With the Outbox Pattern — Gunnar Morling, Debezium blog (2019)
  4. Implement the Transactional Outbox pattern by using Azure Cosmos DB — Azure Architecture Center, Microsoft Learn
  5. Subscribing to events — .NET Microservices e-book, Microsoft Learn

التعليقات (0)