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

📚 Interview question

Show me how you would implement domain events with EF Core 10: collecting them on aggregates, dispatching them from a SaveChangesInterceptor, and keeping the handlers' changes consistent with the original save. What can go wrong?

A working EF Core 10 implementation of domain events: an aggregate base class, a SaveChangesInterceptor that collects and dispatches events before commit, transaction and execution-strategy handling, and the failure modes such as recursion, lost events and re-entrancy.

Mid-Level Coding Intermediate architecture dependency-injection domain-events ef-core savechanges-interceptor transactions

🎯 Key points

  • Aggregates collect events in a private list exposed read-only; Raise() inside behaviour methods
  • SaveChangesInterceptor.SavingChangesAsync reads ChangeTracker.Entries<AggregateRoot>(), copies and clears events
  • Dispatch before commit so handler changes join the same SaveChanges and transaction
  • Dispatch in the order events were raised; never depend on handler order for one event; cascades loop with a depth limit
  • Clear events before dispatching to avoid double dispatch on retry
  • Interceptor resolves handlers from the request scope (scoped interceptor, AddDbContext with the (sp, options) overload)
  • Wrap in an execution strategy when retries are enabled; outbox for anything leaving the process, accepting eventual consistency there

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I start with the aggregate. It inherits an AggregateRoot base class that holds a private List<IDomainEvent> and exposes it as IReadOnlyList. Behaviour methods like Order.Place() change state and call Raise(new OrderPlaced(...)); nothing outside the aggregate can add events. Then I write a SaveChangesInterceptor and override SavingChangesAsync. That hook runs after EF Core has called DetectChanges but before it builds and executes any SQL, so it's the right moment: I pull every tracked aggregate with pending events, copy the events, clear them on the aggregates, and dispatch each to its handlers.

Handlers are resolved from the same scope as the DbContext, so a handler that adds loyalty points or writes an outbox row modifies the same context. When my interceptor returns, EF Core runs DetectChanges again as part of saving, and all those changes go into one batch inside the implicit transaction. If a handler throws, nothing is saved. Handlers can raise further events, so I loop until there are none, with a limit of, say, five passes so a cycle fails loudly instead of hanging.

There are traps. If I don't clear events before dispatching, a retry from EnableRetryOnFailure dispatches them twice. If I register the interceptor as a singleton but it needs scoped handlers, I get a captive dependency, so I add it with the AddDbContext((sp, options) => ...) overload and resolve it per scope. And I never call an external API from a handler inside the transaction; that goes to the outbox.

The mistake I see is dispatching events after SaveChanges returns and assuming they are part of the same unit of work. They aren't, and a crash in between silently loses the side effect."


Where to dispatch

Hook Runs Handler changes saved? Use for
SavingChangesAsync (interceptor) Before SQL, inside the save Yes, same transaction Domain event handlers that must be atomic
Override SaveChangesAsync before base call Same as above Yes Same, when you prefer no interceptor
SavedChangesAsync (interceptor) After commit (implicit tx) Needs another save Post-commit, non-critical side effects
Outbox relay Later, background N/A Integration events to other services

Interceptor vs overriding SaveChangesAsync

Approach Pros Cons
Interceptor Reusable, testable, keeps DbContext clean Must get DI scoping right
Override in DbContext Simple, obvious DbContext needs a dispatcher dependency

Production example

In a [claims] service, moving loyalty and audit side effects into in-transaction domain event handlers removed a class of partial failures that had produced [~15] inconsistent records a month. Average SaveChanges time rose from 18 ms to 22 ms, which we accepted; a slow PDF-generation handler was moved to the outbox after it pushed p99 above 400 ms.

🔍 What the interviewer is checking

Checks that the candidate can implement domain events correctly with EF Core, understands the save pipeline and transaction, and anticipates DI scoping, retries and recursion.

Green flags

  • Uses SavingChangesAsync (or pre-base override) and explains why it is atomic
  • Clears events before dispatch and guards recursion
  • Gets DI scoping right for the interceptor and handlers
  • Keeps external calls out of the transaction (outbox)

Red flags

  • Dispatches after commit and calls it consistent
  • Calls SaveChanges or HTTP inside handlers
  • Public mutable event lists on entities

📚 Learn in depth

1. The save pipeline

SaveChangesAsync()
  -> DetectChanges
  -> interceptors: SavingChangesAsync      <-- dispatch domain events here
  -> DetectChanges again (picks up handler changes)
  -> begin implicit transaction (if none)
  -> batched INSERT / UPDATE / DELETE
  -> commit
  -> interceptors: SavedChangesAsync / SaveChangesFailedAsync

EF Core runs DetectChanges automatically in SaveChanges unless AutoDetectChangesEnabled is off, so entities added or modified by handlers are included. Check the behaviour for your version with a test: if your handlers add new entities after detection, calling context.ChangeTracker.DetectChanges() at the end of the interceptor is a cheap safety net.

2. Collecting events

ChangeTracker.Entries<AggregateRoot>()
   .Select(e => e.Entity)
   .Where(a => a.DomainEvents.Count > 0)

Copy to a list, then call ClearDomainEvents() on each aggregate before dispatching. Clearing first means a retry (from an execution strategy) or a second SaveChanges does not dispatch the same events again.

3. Resolving handlers

The interceptor needs IServiceProvider for the current scope. Options:

  • Register the interceptor as scoped and add it in AddDbContext((sp, o) => o.AddInterceptors(sp.GetRequiredService<DomainEventInterceptor>())).
  • With AddDbContextPool, the options are built once, so a scoped interceptor is captured by the pool. Use IDbContextFactory or resolve handlers through context.GetService<IServiceProvider>() carefully, or avoid pooling for this context.

4. Recursion and ordering

Handlers may raise events on other aggregates. Loop:

pass = 0
while (events = collect()).Any():
    if ++pass > 5: throw
    dispatch(events)

Dispatch in the order events were raised. Do not rely on handler order for the same event; if order matters, it's one handler.

5. Transactions and retries

The implicit transaction wraps the whole save. If you start an explicit transaction with BeginTransactionAsync, the save joins it. With EnableRetryOnFailure, wrap user-initiated transactions in Database.CreateExecutionStrategy().ExecuteAsync(...). Because events are cleared before dispatch, a retried operation must re-run the aggregate behaviour, which the execution strategy does when you put the whole operation inside its delegate.

6. What not to do in a handler

No HTTP calls, no broker sends, no SaveChanges calls of their own (re-entrancy into the same context throws or nests saves). Write an outbox row instead.

Try it yourself

  1. Build the interceptor below with SQLite or Testcontainers SQL Server and assert that a handler's insert and the aggregate's insert share one transaction (log with LogTo).
  2. Throw in a handler and assert nothing is saved.
  3. Make two handlers raise events on each other and confirm the depth limit throws.
  4. Enable EnableRetryOnFailure, inject a transient failure with an interceptor, and check events are not dispatched twice.
  5. Measure SaveChanges time with and without handlers using BenchmarkDotNet.

💻 Code

Aggregate base class, an interceptor that dispatches before the SQL runs, and the registration that keeps handlers in the request scope.

namespace Ordering.Domain;

public interface IDomainEvent;

public abstract class AggregateRoot
{
    private readonly List<IDomainEvent> _domainEvents = [];
    public IReadOnlyList<IDomainEvent> DomainEvents => _domainEvents;
    protected void Raise(IDomainEvent e) => _domainEvents.Add(e);
    public void ClearDomainEvents() => _domainEvents.Clear();
}

public sealed record OrderPlaced(Guid OrderId, decimal Total) : IDomainEvent;

public sealed class Order : AggregateRoot
{
    private Order() { }
    public Guid Id { get; private set; }
    public decimal Total { get; private set; }
    public bool IsPlaced { get; private set; }

    public static Order Create(decimal total) => new() { Id = Guid.NewGuid(), Total = total };

    public void Place()
    {
        if (IsPlaced) throw new InvalidOperationException("Order already placed.");
        IsPlaced = true;
        Raise(new OrderPlaced(Id, Total));
    }
}
namespace Ordering.Infrastructure;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using Ordering.Domain;

public interface IDomainEventHandler<in T> where T : IDomainEvent
{
    Task HandleAsync(T domainEvent, CancellationToken ct);
}

// Scoped: resolves handlers from the same scope as the DbContext.
public sealed class DomainEventInterceptor(IServiceProvider services) : SaveChangesInterceptor
{
    private const int MaxPasses = 5;

    public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
    {
        if (eventData.Context is not { } db) return result;

        for (var pass = 1; ; pass++)
        {
            var aggregates = db.ChangeTracker.Entries<AggregateRoot>()
                .Select(e => e.Entity)
                .Where(a => a.DomainEvents.Count > 0)
                .ToList();
            if (aggregates.Count == 0) break;
            if (pass > MaxPasses)
                throw new InvalidOperationException("Domain event dispatch exceeded the maximum depth; check for cycles.");

            var events = aggregates.SelectMany(a => a.DomainEvents).ToList();
            aggregates.ForEach(a => a.ClearDomainEvents()); // clear first: no double dispatch on retry

            foreach (var domainEvent in events)
                await DispatchAsync(domainEvent, ct);
        }

        db.ChangeTracker.DetectChanges(); // pick up entities handlers added
        return result;
    }

    private async Task DispatchAsync(IDomainEvent domainEvent, CancellationToken ct)
    {
        var handlerType = typeof(IDomainEventHandler<>).MakeGenericType(domainEvent.GetType());
        foreach (dynamic handler in services.GetServices(handlerType))
            await handler.HandleAsync((dynamic)domainEvent, ct);
    }
}
// Program.cs
builder.Services.AddScoped<DomainEventInterceptor>();
builder.Services.AddScoped<IDomainEventHandler<OrderPlaced>, AwardLoyaltyPoints>();
builder.Services.AddScoped<IDomainEventHandler<OrderPlaced>, WriteOrderPlacedToOutbox>();

// The (sp, options) overload resolves the scoped interceptor per DbContext instance.
builder.Services.AddDbContext<OrderingDbContext>((sp, options) => options
    .UseSqlServer(builder.Configuration.GetConnectionString("Ordering"),
        sql => sql.EnableRetryOnFailure())
    .AddInterceptors(sp.GetRequiredService<DomainEventInterceptor>()));

The dynamic dispatch keeps the sample short; in production I'd cache a compiled delegate per event type (or use a source-generated dispatcher) to avoid reflection cost and stay trimming-friendly.

⚠ Common mistakes

  • Mistake: Dispatching events after SaveChanges returns. Why it is wrong: handler changes need a second save and a crash in between loses them. Instead: dispatch in SavingChangesAsync so they join the same transaction.
  • Mistake: Not clearing events before dispatch. Why it is wrong: retries or a second SaveChanges dispatch them again. Instead: copy, clear, then dispatch.
  • Mistake: Letting a long-lived interceptor resolve scoped handlers from the root provider (for example, a singleton interceptor holding the root IServiceProvider, or one captured by AddDbContextPool). Why it is wrong: the singleton itself is fine, but the scoped handlers it resolves become captive dependencies with a different DbContext from the one being saved, so their changes are never persisted in this transaction. Instead: make the interceptor scoped and add it with the (sp, options) overload, or have a singleton interceptor resolve handlers from the saving context's own scope.
  • Mistake: Calling SaveChanges inside a handler. Why it is wrong: re-entrant saves on the same context fail or split the transaction. Instead: only modify the context; the outer save persists everything.
  • Mistake: Calling HTTP APIs or Service Bus from in-transaction handlers. Why it is wrong: the transaction holds locks while waiting on the network, and the external effect can't be rolled back. Instead: write an outbox row.
  • Mistake: No recursion guard. Why it is wrong: two handlers raising each other's events loop forever. Instead: a pass limit that throws.
  • Mistake: Relying on the registration order of several handlers for the same event. Why it is wrong: DI enumeration order is an implementation detail and a refactor silently changes behaviour. Instead: if one step depends on another, make it one handler or raise a second event.
  • Mistake: Making aggregates' event list publicly mutable. Why it is wrong: anything can fake events. Instead: private list, Raise() only from behaviour methods.

🏛 Senior insight: trade-offs

I treat the interceptor as infrastructure plumbing that the domain never sees: the domain only knows Raise(). The design question is which handlers belong in the transaction. My rule is: in-transaction handlers only touch the same database and finish in milliseconds; everything else becomes an outbox message, even inside a modular monolith. That keeps the transaction small and the failure modes understandable.

Domain events are not free. Each one adds indirection (a reader can't see from Order.Place() what happens next), reflection or generated dispatch cost per event, and a bigger SaveChanges with more rows and longer lock duration. In the service above, average save time went from 18 ms to 22 ms, which was fine; but on a hot path doing thousands of saves a second, I'd measure before adding handlers and might prefer an explicit call. If a use case has one follow-on step, an explicit call in the handler is clearer. Domain events pay off when several independent reactions hang off one fact, or when the aggregate shouldn't know who cares. Outbox-backed reactions add another trade-off: they're eventually consistent, so the UI and other modules must tolerate a short lag.

Option When it fits Cost When not to
Hand-rolled interceptor Small to medium codebase, full control ~100 lines to own and test You already use Wolverine/MassTransit outbox
Library (Wolverine, MassTransit EF outbox) Many events, messaging already in place Dependency, learning curve Single simple service
Explicit calls in the use case One or two follow-on steps, hot paths Coupling in the handler Many independent reactions

I'd measure SaveChanges duration (EF Core metrics or Application Insights dependency timing) before and after, and alert if p99 grows past the budget.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions writing an outbox row from a handler. Why: Checks they know where domain events stop and integration events start.
    How to 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.

  2. When: Candidate mentions DetectChanges or the implicit transaction. Why: Checks understanding of the EF Core save pipeline the interceptor hooks into.
    How to answer

    SaveChanges runs a pipeline:

    1. DetectChanges: compares every tracked entity with its original-values snapshot and marks changed properties Modified (skipped if AutoDetectChangesEnabled is false, so you must call it yourself).
    2. Ordering: builds commands per entity and sorts them by the foreign-key graph, so principals are inserted before dependants and dependants deleted before principals.
    3. Batching: groups commands into as few round trips as possible (SQL Server's default MaxBatchSize is 42).
    4. Transaction: wraps them in an implicit transaction when more than one statement is needed, or joins your explicit one.
    5. Fix-up: on SQL Server, INSERT ... OUTPUT INSERTED.[Id] returns identity keys and UPDATE ... OUTPUT INSERTED.[RowVersion] returns new row versions; EF Core replaces temporary keys, propagates them to foreign keys, then marks everything Unchanged.

    The trade-off: one call gives atomicity and few round trips, but its cost grows with every tracked entity.

  3. When: Candidate says external effects go to an outbox. Why: Checks depth on reliable cross-service publishing.
    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.

  4. When: Candidate says external effects become outbox messages and are eventually consistent. Why: Checks how they keep services consistent once events leave the process (outbox, inbox, delivery guarantees).
    How to answer

    These are two bugs with different causes, so I quantify each with reconciliation queries first.

    • Lost messages: usually a dual write. The order is saved, then the publish fails or is never awaited (a fire-and-forget Task.Run killed on deploy, or a swallowed ServiceBusException).
    • Duplicates: usually publisher retries that create a new MessageId each time, which defeats duplicate detection, plus peek-lock redelivery after lock expiry on a consumer that isn't idempotent.

    Fix: an outbox. A SaveChanges interceptor writes domain events to OutboxMessages in the same transaction, and a relay publishes with MessageId = outbox id. Add an inbox on each consumer: (MessageId, Consumer) PK, insert first, treat 2627/2601 as done.

    Roll out the inbox first, because the outbox makes delivery at-least-once. Then backfill missing events, refund double charges, and keep daily reconciliation. The trade-off is extra tables and a relay against guaranteed, deduplicated delivery.

🛠 Real-world problems: how you handle them

Domain events dispatched twice after enabling SQL retries
Situation
A [policy administration] service used a domain event interceptor. After enabling `EnableRetryOnFailure` for Azure SQL in Australia East, [~0.5%] of renewals produced duplicate renewal letters and double loyalty credits.
Signals
Customer complaints about duplicate letters; the loyalty ledger showed pairs of identical credits [milliseconds apart]; Application Insights showed SQL transient errors (40613, 40501) during those requests.
Investigation
Correlated duplicates with dependency failures and retries in Application Insights traces; read the interceptor and found events were cleared only after successful dispatch; reproduced with a test interceptor that throws a transient `SqlException` on the first save.
Resolution
Changed the interceptor to copy and clear events before dispatch, wrapped the renewal use case in an execution strategy so the whole operation (aggregate behaviour plus save) re-runs, and moved letter generation to an outbox message with an idempotent consumer. Credited back the duplicate loyalty points.
Prevention
Integration test that injects a transient failure and asserts each handler ran once; idempotency keys on loyalty credits; a dashboard of duplicate-letter counts.

How to tell it (STAR)

**S:** After we enabled SQL retries, [some] customers got duplicate renewal letters and double loyalty points. **T:** I [owned the domain event infrastructure] and needed to stop the duplicates. **A:** I matched the duplicates to transient SQL errors in Application Insights, reproduced it with a failing interceptor in a test, and found events were cleared too late. I changed the order to copy-clear-dispatch, wrapped the use case in an execution strategy, and moved letters to the outbox. **R:** Duplicates went from [~0.5%] of renewals to zero, and the new test has caught [one] regression since.

↩ Usually asked after

More in Architecture Patterns

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me