
Domain Events Are Not Integration Events: Two Kinds of Events in a .NET App
- كاتب موثّق
- .NET 10
محتويات المقال
OrderPlaced when an order is placed, and a handler already reserves stock for it. Shipping needs to know too, so someone adds a second handler that publishes the same event to the message broker. It works in every demo, until a customer double-clicks "Place order", the second save fails on a unique order number, and Shipping receives a message for an order that doesn't exist. A week later, a restart between a commit and a publish loses a message, and an order that does exist never ships.
The common misconception
What actually happens
Same fact, two audiences
Domain events run before the commit; integration events must wait for it
SaveChanges, on purpose: handlers that use the same scoped DbContext add their changes to the same transaction, so the order and its side effects succeed or fail together. Integration events have the opposite rule. They should go out only if the entity was saved, otherwise it's as if the whole operation never happened.
OrderPlaced to a fake broker, then SaveChangesAsync failed with UNIQUE constraint failed: Orders.Number. The broker held one message, and the order wasn't in the database.
After the commit isn't enough on its own
SaveChangesAsync fixes that and opens the reverse gap: two writes, to the database and to the broker, with no transaction spanning both. The guide spells out the failure: if the service crashes after the database is updated but before the event is published, the system can become inconsistent. It advises against distributed transactions between the two and lists three ways out: full event sourcing, transaction log mining, or a table. In the test, a simulated crash between the commit and the publish left the order saved and the broker empty.
A domain event isn't a contract
OrderStartedDomainEvent holds the Order entity, which is fine in-process. Put it on the wire and the entity's shape becomes your public API. In the test, serializing an event that carried an order with a back-reference from its lines threw JsonException: A possible object cycle was detected. Even without a cycle, renaming a domain property would break every consumer. Integration events are plain data-holding classes, and the guide recommends defining them per service rather than in a library shared across services.
The fix: translate at the boundary, stage in an outbox
using Mediator;// Runs right before SaveChangesAsync, like every domain event handlerpublic sealed class PublishOrderPlaced(IMessageBus bus) : INotificationHandler<OrderPlaced>{ public async ValueTask Handle(OrderPlaced e, CancellationToken ct) { // The domain event itself becomes the public message, // and it leaves before the order is committed await bus.PublishAsync(e, ct); }}using Mediator;// The public contract: primitives only, versioned, owned by this servicepublic sealed record OrderPlacedV1( Guid OrderId, Guid CustomerId, decimal Total);// Same timing, but it only stages a row in the same transactionpublic sealed class StageOrderPlaced(ShopDb db) : INotificationHandler<OrderPlaced>{ public ValueTask Handle(OrderPlaced e, CancellationToken ct) { var message = new OrderPlacedV1(e.OrderId, e.CustomerId, e.Total); db.Outbox.Add(OutboxMessage.From(message)); // commits with the order return ValueTask.CompletedTask; }}SaveChangesAsync as the order. In the test, a failing save left no outbox row behind, and a successful one stored the order and its message together. A background service then publishes what's pending:
using Microsoft.EntityFrameworkCore;public sealed class OutboxRelay(IServiceScopeFactory scopes, IMessageBus bus) : BackgroundService{ protected override async Task ExecuteAsync(CancellationToken stop) { while (!stop.IsCancellationRequested) { using var scope = scopes.CreateScope(); var db = scope.ServiceProvider.GetRequiredService<ShopDb>(); var pending = await db.Outbox.Where(x => x.PublishedAt == null) .OrderBy(x => x.Id).Take(50).ToListAsync(stop); foreach (var m in pending) { // A crash between these lines sends it again next time await bus.PublishAsync(m.Type, m.Payload, stop); m.PublishedAt = DateTime.UtcNow; await db.SaveChangesAsync(stop); } await Task.Delay(TimeSpan.FromSeconds(1), stop); } }}How to apply it in your project
Find publishes in domain event handlers Search for broker, email and HTTP calls in code that runs before SaveChangesAsync, includingSaveChangesoverrides and interceptors.Define integration events as contracts Create separate records with primitive fields and a version in the name, owned by the publishing service, and map domain events to them in explicit code. Stage them in an outbox Add an outbox table and insert integration events in the same SaveChangesAsyncas the business change.Relay, then make consumers idempotent Publish pending rows from a background service, and have every consumer detect duplicates or apply changes that are safe to repeat.
Key takeaways
Domain and integration events describe the same kind of fact for different audiences, so they're implemented differently. Domain events usually run before the commit, in the same transaction; integration events must leave only after it. Publishing from a domain event handler can announce data that was rolled back, and publishing after the commit can lose the message. An outbox row saved with the business change closes that gap, at the price of at-least-once delivery. Treat integration events as versioned public contracts and make every consumer idempotent.
📚 المصادر
Domain events: design and implementation — .NET Architecture Guides, Microsoft Learn Implementing event-based communication between microservices (integration events) — .NET Architecture Guides, Microsoft Learn Subscribing to events: atomicity, outbox and idempotency — .NET Architecture Guides, Microsoft Learn Domain Event — Martin Fowler
التعليقات (0)