📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the difference between a domain event and an integration event? Explain in-process versus cross-service delivery, when each should be dispatched relative to SaveChanges, and how the transactional outbox connects the two.

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.

Intermediate Theory Intermediate architecture domain-events ef-core integration-events messaging outbox

🎯 Key points

  • Domain event: something that happened inside one bounded context, in-process, uses domain types, past tense (OrderPlaced)
  • Integration event: a published contract for other services or modules, serialised, versioned, owned by the publisher
  • Domain event handlers run in-process, usually synchronously inside the unit of work before commit; anything remote is deferred to an integration event
  • Integration events are published only after commit, via a transactional outbox row written in the same EF Core transaction
  • Translate a domain event into an integration event at the boundary; never publish domain types externally
  • Delivery is at-least-once, so integration consumers are idempotent (inbox keyed on event id)
  • Failure semantics differ: a failing domain handler rolls back the whole unit of work; an integration consumer retries, then dead-letters, independently
  • Both decouple: domain events keep aggregates unaware of who reacts; integration events keep services unaware of each other

⏱ 30-second answer

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.

  • Domain events are dispatched inside the unit of work (just before or as part of SaveChanges), so their side effects commit or roll back together.
  • Integration events must only leave after the commit. You write them to an outbox table in the same transaction, and a relay publishes them to Azure Service Bus.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 SaveChangesInterceptor or an overridden SaveChangesAsync before 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 maps OrderPlaced to an OrderPlacedV1 integration 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."


Side by side

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

Dispatch timing options

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

When something fails

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.

Production example

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.

🔍 What the interviewer is checking

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

  • Distinguishes in-process domain types from versioned, serialised contracts
  • Dispatches domain events within the unit of work and integration events after commit
  • Names the dual-write problem and the transactional outbox
  • Mentions at-least-once delivery and idempotent consumers

Red flags

  • Treats the two as the same thing with different names
  • Publishes to the broker before or immediately after SaveChanges without an outbox
  • Shares domain event classes with other services

📚 Learn in depth

1. Two kinds of fact

An 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)

2. Why domain events exist

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.

3. The dual-write problem

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).

4. The outbox with EF Core and Azure Service Bus

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:

  • The outbox row is just another entity on the same 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.
  • Setting 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.
  • If the send succeeds and the 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.

5. Designing the integration contract

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.

6. Ordering, duplicates and idempotency

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.

Try it yourself

  1. Add a DomainEvents list to an aggregate and dispatch it from a SaveChangesInterceptor; throw in a handler and confirm the original insert rolls back.
  2. Publish directly to the Service Bus emulator after SaveChangesAsync, kill the process between the two calls with a debugger, and observe the lost message.
  3. Replace it with the outbox table and relay above; repeat the kill and confirm the message is delivered after restart.
  4. Deliver the same message twice to a consumer and add an inbox table with a unique key to make the second a no-op.
  5. Rename a property on the domain event and confirm the integration contract (a separate record) is unaffected.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Publishing domain event classes directly to the broker. Why it is wrong: every internal refactor becomes a breaking change for consumers, and domain types may leak sensitive fields. Instead: map to a separate, versioned integration contract at the boundary.
  • Mistake: Sending to Service Bus before 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.
  • Mistake: Sending to Service Bus right after 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.
  • Mistake: Calling HTTP APIs, sending email or doing other slow, remote work from a domain event handler that runs inside the transaction. Why it is wrong: the transaction holds locks while it waits on the network, and the remote effect cannot be rolled back if the commit later fails. Instead: keep in-transaction handlers local and fast; have them write an outbox row, and do the remote work asynchronously in a consumer after commit.
  • Mistake: Assuming exactly-once delivery for integration events. Why it is wrong: outbox relays and brokers redeliver. Instead: make consumers idempotent with an inbox keyed on event id.
  • Mistake: Swallowing exceptions in domain event handlers so the save "still works". Why it is wrong: the aggregate change commits without its required side effect, leaving the context inconsistent. Instead: let the exception roll back the unit of work, or move the reaction to an outbox-backed asynchronous handler with retries.
  • Mistake: Putting the whole aggregate in the integration event. Why it is wrong: it creates a fat, unstable contract and leaks PII under the Privacy Act. Instead: send ids and the facts consumers need.
  • Mistake: Treating every state change as an event. Why it is wrong: noise hides the business-meaningful facts. Instead: raise events the business would name.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the outbox or the dual-write problem. Why: Checks depth on the outbox mechanics and its operational cost.
    How to answer

    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.

  2. When: Candidate says integration events are delivered at least once. Why: Checks that they make consumers idempotent.
    How to answer

    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:

    1. Insert the inbox row first.
    2. Apply the business change.
    3. Commit, then complete the Service Bus message.

    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.

  3. When: Candidate says domain events are dispatched before commit. Why: Checks that they can turn the concept into working EF Core code.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Lost OrderPlaced events after deployments
Situation
An [e-commerce] order service on Azure Container Apps in Australia East saved orders with EF Core and then published `OrderPlaced` to Azure Service Bus straight after `SaveChangesAsync`. Throughput was [~40 orders per second] at peak.
Signals
Warehouse reported [a few dozen] orders a week with no pick list; the gaps clustered around deployment times; Service Bus metrics showed fewer incoming messages than rows inserted into Orders.
Investigation
Compared Orders row counts with Service Bus incoming message counts per minute in Application Insights; correlated gaps with revision restarts; reviewed the code path and found the publish call outside any transaction; reproduced by killing the process between the save and the send.
Resolution
Immediate: a reconciliation job re-published events for orders with no matching warehouse record. Long term: added an outbox table written by a domain event handler in the same EF Core transaction, plus a relay with retries, and an inbox in the warehouse consumer to absorb duplicates.
Prevention
Architecture test forbidding `ServiceBusSender` usage outside the relay project; alert on outbox oldest-unsent age above [60 seconds]; a daily reconciliation report comparing orders with warehouse receipts.

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].

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me