Domain events versus integration events in a .NET 10 architecture: scope, contracts, dispatch timing around EF Core SaveChanges, translating one into the other, and using the outbox for reliable cross-service publishing.
A domain event records something meaningful that happened inside one bounded context, such as OrderPlaced. It is raised by an aggregate, handled in-process by other parts of the same model, and uses domain types freely. An integration event is a published contract for other services or modules: serialised, versioned and owned by the publisher.
SaveChanges), so their side effects commit or roll back together.The trade-off: domain events give you strong consistency in one context; integration events give you decoupling at the cost of eventual consistency and at-least-once delivery.
"Both are past-tense facts, but they live at different scales. A domain event is raised inside a bounded context, usually by an aggregate, to say something meaningful happened: an order was placed, a policy was renewed. Its handlers run in the same process and normally in the same unit of work, so they can use the rich domain types and they either all succeed with the original change or all roll back with it. An integration event is a message I publish for other services or other modules. It is a contract: a serialised, versioned schema that the publisher owns and must keep backward compatible, carrying only what consumers need, usually ids and a few facts, not my entities.
The timing is where people get burned. In .NET I collect domain events on the aggregate, then dispatch them from a
SaveChangesInterceptoror an overriddenSaveChangesAsyncbefore the transaction commits, so a handler that, say, reserves loyalty points writes in the same transaction. Integration events must never be sent to a broker before the commit, because if the commit fails I've told the world something that didn't happen. And if I send after the commit and the process dies, the event is lost. That's the dual-write problem, and the answer is the transactional outbox: a domain event handler mapsOrderPlacedto anOrderPlacedV1integration event and writes it as an outbox row in the same EF Core transaction, and a relay publishes it afterwards.The mistake I see is teams publishing their domain event classes straight onto Service Bus, so every internal rename becomes a breaking change for three other teams. Domain events are an implementation detail; integration events are an API."
| Domain event | Integration event | |
|---|---|---|
| Scope | One bounded context / module | Between services or modules |
| Transport | In-memory dispatch | Broker (Azure Service Bus, Kafka) or in-process bus with outbox |
| Types | Domain types, value objects | Primitive, serialisable DTO (record) |
| Versioning | Refactor freely | Versioned contract, backward compatible |
| Timing | Before commit, same transaction | After commit, via outbox |
| Failure | Handler failure rolls back the change | Consumer retries independently |
| Delivery | Exactly once (in-process) | At-least-once; consumers idempotent |
| Owner | The context's team | Publisher owns the schema |
| Option | Consistency | Risk |
|---|---|---|
Dispatch before SaveChanges, same transaction |
Atomic with the change | Handlers must be fast and local; a slow handler holds locks |
| Dispatch after commit, in-process | Eventually consistent inside the context | Process crash loses the side effect unless it is also outboxed |
| Outbox row in same transaction, relay publishes | Reliable cross-service | Extra table, relay, at-least-once duplicates |
| Failure point | What happens | What you do |
|---|---|---|
| Domain event handler throws (before commit) | The exception propagates out of SaveChangesAsync; EF Core never commits, so the aggregate change, other handlers' changes and the outbox row all roll back |
Return a domain error or 409/422 to the caller; the user retries. Don't catch and continue |
| Commit fails (deadlock, transient SQL error) | Nothing is saved, including the outbox row, so nothing is published | Retry the whole use case in an execution strategy; events are re-raised by re-running the behaviour |
| Relay can't reach Service Bus | Outbox rows stay unsent | Relay retries with backoff; alert on the age of the oldest unsent row |
| Relay sends, then crashes before marking sent | The message is sent again on restart | Consumers dedup with an inbox keyed on event id |
| Consumer throws | Service Bus redelivers up to MaxDeliveryCount, then dead-letters |
Fix and resubmit from the dead-letter queue; the publisher is unaffected |
This is the decoupling benefit in practice: the aggregate doesn't know who reacts to OrderPlaced, and the order service doesn't know or care that the warehouse consumer is down.
In an order service handling about 40 orders per second, events were published to Service Bus directly after SaveChangesAsync. A deployment restart lost roughly 0.1% of OrderPlaced messages, so warehouse picking never started for those orders. Moving to a domain event handler that wrote an outbox row in the same transaction took lost messages to zero, with the relay adding a median of 300 ms latency.
Checks that the candidate understands the scope and contract differences between domain and integration events, and handles dispatch timing and the dual-write problem correctly.
Green flags
Red flags
SaveChanges without an outboxAn event is an immutable record that something happened. The difference is who is allowed to depend on it.
+----------------------- Ordering context ------------------------+
| Order.Place() --raises--> OrderPlaced (domain event) |
| | |
| +----------------------+---------------------+ |
| v v |
| ReserveLoyaltyPoints handler MapToIntegrationEvent |
| (same DbContext, same tx) writes OutboxMessage |
+---------------------------------------------------------|-------+
| after commit
Outbox relay
v
Azure Service Bus topic: orders
| |
Warehouse svc Billing svc
(inbox, idempotent) (inbox, idempotent)
Without them, an aggregate method like Order.Place() either calls other services directly (coupling the model to infrastructure) or the application service grows a long list of follow-on steps. Domain events let the aggregate state the fact and let handlers react, keeping the aggregate pure and decoupled from its observers. Handlers inside the same context may modify other aggregates, but in DDD terms that's a deliberate choice to accept a larger transaction; many teams prefer to make cross-aggregate reactions eventually consistent too.
Two resources, SQL Server and the broker, cannot share a transaction (no distributed transactions with Azure Service Bus). Every ordering of "save" and "send" has a failure window:
send then save: send OK, save fails -> phantom event
save then send: save OK, crash -> lost event
outbox: save(order + outbox row) atomically; relay sends later; retry until acked
The outbox converts the problem into at-least-once delivery, which consumers handle with an inbox (dedup by message id).
Request scope Background relay (BackgroundService)
------------- -----------------------------------
BEGIN TRAN loop every 1-2 s:
INSERT Orders ... SELECT TOP (100) FROM Outbox
INSERT OutboxMessages (Id, Type, Payload) WITH (UPDLOCK, READPAST, ROWLOCK)
COMMIT WHERE SentAt IS NULL ORDER BY OccurredAt
send batch to Service Bus (MessageId = outbox Id)
UPDATE Outbox SET SentAt = now WHERE Id IN (...)
Key details:
DbContext, so EF Core's implicit transaction makes it atomic with the business change.UPDLOCK, READPAST lets several relay instances run without picking the same rows.ServiceBusMessage.MessageId to the outbox id lets Service Bus duplicate detection (if enabled on the entity, within its time window) drop resends; consumers still keep an inbox because duplicate detection is time-bounded.UPDATE fails, the batch is resent: that's the at-least-once guarantee.namespace Ordering.Infrastructure;
using Azure.Messaging.ServiceBus;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public sealed class OutboxRelay(IServiceScopeFactory scopes, ServiceBusSender sender, TimeProvider clock) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));
while (await timer.WaitForNextTickAsync(ct))
{
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OrderingDbContext>();
await using var tx = await db.Database.BeginTransactionAsync(ct);
var batch = await db.OutboxMessages
.FromSql($"SELECT TOP (100) * FROM dbo.OutboxMessages WITH (UPDLOCK, READPAST, ROWLOCK) WHERE SentAt IS NULL ORDER BY OccurredAt")
.ToListAsync(ct);
if (batch.Count == 0) continue;
var messages = batch.Select(m => new ServiceBusMessage(m.Payload) { MessageId = m.Id.ToString(), Subject = m.Type });
await sender.SendMessagesAsync(messages, ct); // if this throws, rows stay unsent and are retried
var now = clock.GetUtcNow();
batch.ForEach(m => m.SentAt = now);
await db.SaveChangesAsync(ct);
await tx.CommitAsync(ct);
}
}
}
Libraries such as Wolverine and MassTransit ship this relay for EF Core, with cleanup and metrics, so hand-rolling is only worth it when you want no messaging dependency.
Keep it small and stable: ids, the business facts consumers genuinely need, an event id, an occurred-at timestamp and a schema version. Avoid sending the entire order graph; consumers that need more call back or maintain their own projection. Many teams adopt a CloudEvents envelope (id, source, type, time) for consistency.
Azure Service Bus only guarantees FIFO within a session. Include an aggregate version or sequence number in each integration event so consumers can ignore stale updates. Idempotency means processing the same event twice has the same effect as once: the consumer records the event id in an inbox table with a unique key in the same transaction as its own change, so a redelivered message hits the unique key and is skipped.
DomainEvents list to an aggregate and dispatch it from a SaveChangesInterceptor; throw in a handler and confirm the original insert rolls back.SaveChangesAsync, kill the process between the two calls with a debugger, and observe the lost message.A domain event raised by the aggregate, translated into a separate integration contract and written to the outbox in the same transaction.
namespace Ordering.Domain;
public interface IDomainEvent { DateTimeOffset OccurredAt { get; } }
// Domain event: uses domain types, internal to the Ordering context.
public sealed record OrderPlaced(OrderId OrderId, CustomerId CustomerId, Money Total, DateTimeOffset OccurredAt) : IDomainEvent;
public readonly record struct OrderId(Guid Value);
public readonly record struct CustomerId(Guid Value);
public sealed record Money(decimal Amount, string Currency);
public abstract class AggregateRoot
{
private readonly List<IDomainEvent> _events = [];
public IReadOnlyList<IDomainEvent> DomainEvents => _events;
protected void Raise(IDomainEvent e) => _events.Add(e);
public void ClearDomainEvents() => _events.Clear();
}
namespace Ordering.Contracts;
// Integration event: a published, versioned contract. Primitives only, no domain types.
public sealed record OrderPlacedV1(Guid EventId, Guid OrderId, Guid CustomerId, decimal Total, string Currency, DateTimeOffset OccurredAt);
namespace Ordering.Application;
using System.Text.Json;
using Ordering.Contracts;
using Ordering.Domain;
// Runs inside the unit of work (before commit), so the outbox row commits with the order.
public sealed class PublishOrderPlaced(OrderingDbContext db) : IDomainEventHandler<OrderPlaced>
{
public Task HandleAsync(OrderPlaced e, CancellationToken ct)
{
var contract = new OrderPlacedV1(Guid.NewGuid(), e.OrderId.Value, e.CustomerId.Value,
e.Total.Amount, e.Total.Currency, e.OccurredAt);
db.OutboxMessages.Add(new OutboxMessage
{
Id = contract.EventId,
Type = "ordering.order-placed.v1",
Payload = JsonSerializer.Serialize(contract),
OccurredAt = e.OccurredAt
});
return Task.CompletedTask; // the relay publishes after commit
}
}
public interface IDomainEventHandler<in T> where T : IDomainEvent
{
Task HandleAsync(T domainEvent, CancellationToken ct);
}
SaveChanges. Why it is wrong: if the commit fails, consumers act on something that never happened. Instead: write an outbox row in the same transaction.SaveChanges and calling it reliable. Why it is wrong: a crash or broker outage between the two calls loses the event. Instead: outbox plus relay with retries.The senior framing is that domain events are a modelling tool and integration events are an API. I'm relaxed about changing domain events; I treat integration events with the same care as a public HTTP contract: version them, document them, and never remove a field without a deprecation period. Inside a modular monolith I still use integration events between modules, often through an in-process bus with an outbox, because that's what keeps module boundaries honest and makes later extraction cheap.
I also decide deliberately whether cross-aggregate reactions run in the same transaction. Same-transaction handlers are simpler and strongly consistent, but they grow the transaction and the lock footprint. For anything that touches another aggregate with its own invariants, I prefer an outbox-backed asynchronous handler and measure the outbox lag.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| In-transaction domain event handler | Local side effects that must commit together | Larger transaction | Remote calls, slow work |
| Post-commit in-process handler | Cheap, non-critical side effects (cache refresh) | Lost on crash | Anything that must happen |
| Outbox + integration event | Cross-module or cross-service reactions | Relay, lag, duplicates | Simple CRUD with no consumers |
I'd measure outbox lag (oldest unsent row age), relay throughput and consumer dedup hits in Application Insights.
The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.
The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.
A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.
With at-least-once delivery, duplicates are normal: outbox resends, peek-lock redelivery after a crash or lock expiry, and publisher retries. An idempotent consumer makes processing a message twice have the same effect as once.
The inbox is an InboxMessages table with a primary key on (MessageId, Consumer). For each message, in one EF Core transaction:
If the insert fails with SQL error 2627/2601, the message was already processed, so complete it. A concurrent duplicate blocks on the key lock until the first commits, then fails the insert. If the first rolls back, the duplicate goes ahead.
Purge old rows past the redelivery window. The trade-off is an extra write and table per consumer against correct exactly-once processing.
I give aggregates a base class with a private list of domain events, raised inside behaviour methods. A SaveChangesInterceptor overrides SavingChangesAsync: it collects events from ChangeTracker.Entries<AggregateRoot>(), clears them, and dispatches them to handlers resolved from the current DI scope. Because this runs before EF Core writes, any changes handlers make to the same DbContext are saved in the same SaveChanges call and transaction. I loop until no new events appear, with a depth limit.
Anything that must leave the process goes to an outbox row, not a broker call. The trade-off: in-transaction handlers give atomicity but make the save slower and the transaction bigger, so they must stay local and fast.
How to tell it (STAR)
**S:** Our order service published `OrderPlaced` to Service Bus right after `SaveChangesAsync`, and [warehouse] kept finding orders with no pick list. **T:** I [was asked to find the cause and make delivery reliable]. **A:** I lined up insert counts against Service Bus metrics, saw the gaps matched deployments, and reproduced it by killing the process between save and send. I proposed an outbox written in the same transaction, a relay, and an inbox on the consumer, wrote [an ADR], and added an alert on outbox age. **R:** Lost events went from [~30 a week] to zero over [the next quarter], with a median added latency of [~300 ms].
Last updated 23 Nov 2026.