
Save Then Publish Is Not Atomic: The Dual-Write Problem and the Outbox
- كاتب موثّق
محتويات المقال
The common misconception
What actually happens
Two writes, no shared transaction
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.
Why not a distributed transaction
Write once, derive the second
The relay: polling or the transaction log
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
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); }}using System.Text.Json;public sealed class PlaceOrder(ShopDb db){ public async Task HandleAsync(Order order, CancellationToken ct) { var evt = new OrderPlaced(order.Id, order.Total); db.Orders.Add(order); db.Outbox.Add(new OutboxMessage { Id = Guid.NewGuid(), // the message id consumers dedupe on Type = nameof(OrderPlaced), Payload = JsonSerializer.Serialize(evt), }); await db.SaveChangesAsync(ct); // one transaction: both rows or neither }}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); } }}How to apply it in your project
Find the dual writes Search for broker publishes, emails, cache updates and HTTP calls that run right after SaveChangesAsyncor inside a transaction.Add an outbox table Store an id, a type, a payload and a sequence number in the same database as the business data. Write in one transaction, relay separately Insert the message with the business change in a single SaveChangesAsync, and run one relay that publishes pending rows in order.Make consumers idempotent Use 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.
📚 المصادر
Pattern: Transactional outbox — Chris Richardson, microservices.io Pattern: Polling publisher — Chris Richardson, microservices.io Reliable Microservices Data Exchange With the Outbox Pattern — Gunnar Morling, Debezium blog (2019) Implement the Transactional Outbox pattern by using Azure Cosmos DB — Azure Architecture Center, Microsoft Learn Subscribing to events — .NET Microservices e-book, Microsoft Learn
التعليقات (0)