Domain events vs integration events: where each belongs
Domain events vs integration events: one is a private fact inside a transaction, the other a public contract, and a one-field rename shows why they differ.
Here is a hypothetical bug report. It lands on a subscriptions team the morning after a routine refactor: another team's consumer has stopped processing messages, and nobody on that team deployed anything. Their logs show this:
System.Text.Json.JsonException: JSON deserialization for type 'SubscriptionCancelledMessage'
was missing required properties including: 'endsOn'.The cause is one line in a pull request that nobody thought twice about. A developer renamed EndsOn to
AccessEndsOn on a record in the domain model, because the new name described the rule better. That record
was also being serialized straight onto the broker, so a private refactor changed a public format. One type
was serving as both an internal fact and an external contract.
Microsoft's domain events guide says that semantically the two are the same thing, notifications about something that just happened, and that their implementation must differ. The differences follow from who is listening and when.
| Domain event | Integration event | |
|---|---|---|
| Audience | Handlers in the same module | Other services, modules or systems |
| When it fires | Before or just after commit | Only after commit |
| Transport | In-memory dispatch | Broker or queue, usually through an outbox |
| Failure handling | Exception rolls back, or retry locally | Retries, duplicates, dead letters |
| Shape | Domain types, free to refactor | Primitives under a versioned name |
| Changing it | A refactor | A compatibility problem |
Where each event lives relative to the commit
Domain event: same process, same transaction
Aggregate records
SubscriptionCancelled, in memory
In-process handlers
Release seats on the same DbContext
Translator
Writes subscriptions.cancelled.v1 to the outbox
COMMIT: state, seats and outbox row together
Integration event: later, across the network
Relay
Reads committed outbox rows and retries
Broker
Delivers at least once
Other services
Deduplicate, then update their own data
Publishing to the broker from inside the top box announces a fact that can still roll back.
A domain event lets one aggregate state what happened without knowing who cares. The aggregate records the fact and goes back to its rules. It does not call anything:
public interface IDomainEvent;
public sealed record SubscriptionCancelled(
Guid SubscriptionId, Guid AccountId, int Seats, DateOnly AccessEndsOn) : IDomainEvent;
public sealed class Subscription
{
private readonly List<IDomainEvent> _events = [];
public Guid Id { get; private set; }
public Guid AccountId { get; private set; }
public int Seats { get; private set; }
public DateOnly? AccessEndsOn { get; private set; }
public void Cancel(DateOnly periodEnd)
{
if (AccessEndsOn is not null) return;
AccessEndsOn = periodEnd;
_events.Add(new SubscriptionCancelled(Id, AccountId, Seats, periodEnd));
}
// TakeEvents() hands the recorded events to the unit of work below.
}Recording and dispatching are separate steps, and the moment you dispatch decides what a handler failure means. The Microsoft guide says dispatching right before commit includes side effects in the same transaction, and dispatching right after creates separate transactions you have to reconcile.
Here is the before-commit version. Handlers only add changes to the same DbContext, and
SaveChanges applies them in one transaction:
public sealed class UnitOfWork(AppDb db, IEnumerable<IDomainEventHandler> handlers)
{
public async Task CommitAsync(CancellationToken ct)
{
var raised = db.ChangeTracker.Entries<Subscription>()
.SelectMany(entry => entry.Entity.TakeEvents())
.ToList();
foreach (var domainEvent in raised)
foreach (var handler in handlers)
await handler.HandleAsync(domainEvent, ct);
await db.SaveChangesAsync(ct);
}
}EF Core on SQLite, cancelling a five-seat subscription, with a throwing handler in the two failing cases:
success: accessEndsOn=2026-11-30 seatsUsed=0 outboxRows=1
handler failed before commit: accessEndsOn=null seatsUsed=5 outboxRows=0
handler failed after commit: accessEndsOn=2026-11-30 seatsUsed=5 outboxRows=0The last line is the state you must plan for if you dispatch after commit: the subscription is cancelled and the seats were never released. That can be acceptable, and DDD authors disagree about it. The same guide cites Evans and Vernon favoring eventual consistency between aggregates and Bogard favoring one transaction for side effects of one command. Eventual consistency scales better and requires a way to detect and repair inconsistency. For one relational database, the guide calls the single transaction the simplest approach, and that is where to start.
In-transaction handlers come with a rule: they may only do work that can roll back. An HTTP call or an email sent from a handler has already left when a later handler fails, and no rollback will retract it. Slow handlers delay the commit; if you wrap dispatch in an explicit transaction, they also hold its locks. An aggregate that emails a customer before the save makes the same mistake one layer down, and that refactor is among the architecture exercises, with design rules checking dependency direction.
The handler that failed before commit left 0 outbox rows and 5 seats in use. The one that failed after commit left a cancelled subscription with its 5 seats still held.
An integration event propagates committed changes to other systems, so its readers are outside your repository and possibly outside your deployment schedule. Queued messages written by old code will still be around after new code ships. Everything about its shape follows from that.
The fix for the bug report is a second type and a translator. This handler runs in the same unit of work as the others, which is how the two event kinds connect:
// The published contract: primitives, a stable name, no domain types.
public sealed record SubscriptionCancelledV1(Guid SubscriptionId, Guid AccountId, string AccessEndsOn);
public sealed class PublishCancellation(AppDb db) : IDomainEventHandler
{
public Task HandleAsync(IDomainEvent domainEvent, CancellationToken ct)
{
if (domainEvent is not SubscriptionCancelled cancelled) return Task.CompletedTask;
var contract = new SubscriptionCancelledV1(
cancelled.SubscriptionId,
cancelled.AccountId,
cancelled.AccessEndsOn.ToString("O"));
db.Outbox.Add(new OutboxMessage
{
Id = Guid.NewGuid(),
Type = "subscriptions.cancelled.v1",
Payload = JsonSerializer.Serialize(contract, JsonSerializerOptions.Web),
});
return Task.CompletedTask;
}
}The row it writes has this payload:
{
"subscriptionId": "11111111-0000-4000-8000-000000000001",
"accountId": "7f8c1f0e-0000-4000-8000-000000000001",
"accessEndsOn": "2026-11-30"
}The "O" format keeps the date independent of culture, which a published format needs: a bare
"yyyy-MM-dd" rendered 2569-11-30 under th-TH. The domain record can now be renamed freely, and the
translator is the single place that has to change.
Add a test that serializes a fixed instance of the contract and compares it with a stored JSON string, so
a rename of the contract itself fails in your build instead of in someone else's consumer.
Contract changes follow the rules from API backward compatibility.
With System.Text.Json's defaults, an old consumer read a payload with an extra plan field without
complaint, and a payload missing a required property threw the endsOn exception. Add
fields, keep old ones populated, and publish v2 under a new name for a breaking change. Microsoft also
advises against sharing a common integration-events library across services, since that couples them to
one definition. Publish a schema and let each consumer keep its own copy of what it reads.
Payload size is a design choice too. Martin Fowler's event-driven patterns contrast event notification, which says only that something changed, with event-carried state transfer, which sends enough data that receivers need not call back. The second removes a runtime dependency and makes each receiver maintain its own copy. Pick per event, based on what consumers would otherwise have to fetch.
The translator writes to a table, and that detail closes the timing gap. Publishing to the broker from the handler would announce a cancellation that could still roll back. Publishing after commit would lose the event if the process died in between. An outbox row commits atomically with the subscription and the seat release, and a separate relay publishes it afterward.
The transactional outbox guide covers that relay. It delivers at least once, so consumers need to deduplicate on the message ID. Messages that keep failing belong in a dead letter queue, where someone can inspect them.
Serializing the domain event onto the broker is how the endsOn consumer broke. Its mirror image is
consuming your own integration events inside the module to update your own tables, which adds a broker hop,
retries and eventual consistency to something a handler could do in one transaction.
Mapping every domain event one to one is the next. Many domain events are internal detail. If a support agent reassigns seats inside an account, the module may record that for its own handlers while other systems have no reason to know. Each published event is a commitment you maintain for as long as anyone consumes it, so publish on request instead of by default.
The same boundary applies between modules in one process. In a modular monolith, one module reacting to another across a boundary should use a contract owned by the publisher, even in one process, because that seam is what makes the modules separable later. Inside one module, plain domain events are enough. Delivery choices across that boundary are covered in message queue vs event bus.
Apply the test to this example. SubscriptionCancelled stays private, with two handlers: one releases seats
and one translates. subscriptions.cancelled.v1 goes out, because entitlements and analytics need to know
when access ends. The cancellation reason a support agent typed is useful to internal handlers and stays
out of the contract until a consumer asks for it, since removing a published field later is far harder than
adding it.
Practice Architecture & Design
- Open in the editor: Two Sides of the Hexagon
Architecture Medium Free, no account needed
Two Sides of the Hexagon
A driving (web) adapter reaches the driven (persistence) adapter directly for a quick existence check. Inject the repository "via its interface" and you'll find the seam is still on the wrong side of the hexagon.
- Open the Pro kata: Record Events, Don't Send Them
Architecture Medium Katabench Pro
Record Events, Don't Send Them
The Order aggregate emails the customer from inside Ship and Deliver, so the domain depends on an SMTP adapter and the mail leaves before the order is saved. Let the aggregate record domain events and have the application publish them through a port after each save, exactly once, even when the same order is saved again.
More like this: C# architecture exercises →