Bite-sized, standalone interview questions and answers for Domain-Driven Design. Read 5-10 per sitting. Each answer is 2-4 sentences max and stands on its own.

73 questions shown. Filter by keyword or difficulty below.

Topic: Ubiquitous Language & Event Storming (Order 1)

A glossary documents terms separately from code, so developers can “translate” domain vocabulary into technical names during implementation — and every translation step is a drift opportunity where business rules silently drop. Ubiquitous language requires the exact same words the domain expert uses to appear verbatim in method names, class names, and event names with zero translation, so a rule like “you can’t ship before payment” lives at the one method named after that business action (SetShippedStatus), not scattered across utility code.

Past tense (“Order Shipped”) represents a fact that already happened, which lets other parts of the system react to it without being coupled to why or what triggered it. A command name (“ShipOrder”) implies an action at the point of invocation, mixing the trigger with the fact and coupling consumers to the command’s cause. The past-tense convention directly reflects how domain experts narrate processes — “the order shipped,” not “we ship the order.”

Event Storming surfaces vocabulary collaboratively in a workshop setting, where developers and domain experts jointly name business-significant occurrences on sticky notes before any code exists. A solo interview risks capturing one person’s mental model, which may use different words than what the warehouse team or finance team actually says. The board format also exposes sequences and dependencies between events that one-on-one conversation often misses.

Treating it as naming convention retrofitted after code is written, rather than a vocabulary agreed on before code exists. Once UpdateStatus(5) is already in production, renaming it to SetShippedStatus() is a refactor that competes with feature work — the language needs to be established in Event Storming first, so the code is written with it from day one.

SetShippedStatus() checks OrderStatus != OrderStatus.Paid and throws before allowing the transition, so the business rule “you can’t ship an unpaid order” is enforced at the single method named after that action. A raw field assignment (order.Status = 5) is a field mutation with no guard — it can’t enforce anything because it doesn’t represent a business action, just a data change. The method named after the concept is the one place the rule can actually live.

Downstream services will desynchronize on meaning — “OrderStatusChanged” in one service might map to a different field set than “OrderPaid” in another, creating silent data mismatches on the message bus. The eShop codebase avoids this by having each service define its own independently-declared copy of the event, matched by event-name convention on the bus, not by a shared type reference. Different names break that convention-based contract.

Topic: Entities vs Value Objects (Order 2)

A single domain model constantly needs to answer “are these two objects the same?” — but the correct answer depends on what is being compared. Two Order records with identical dates and items are still two different orders if they have different IDs. Two Address values with identical street/city/zip are interchangeable. Using one equality rule for both gets one of them wrong.

Entity.Equals compares only the Id field — every other field can differ (or change over time) and they’re still equal. ValueObject.Equals uses GetEqualityComponents().SequenceEqual() to compare every defining component — change any one field and they’re a genuinely different value. Both also check type first, but the identity-vs-structure split is the core distinction.

Both would have Id == default (typically 0), so Equals would wrongly conclude every newly-constructed, not-yet-saved entity is equal to every other one. The Entity base class explicitly guards against this with IsTransient() — if either side is transient, it returns false immediately, falling back to reference identity. Without this guard, two different Order objects with no database ID yet would compare as equal.

A C# record gets structural equality from the compiler for free, but a hand-written class (as Address is in eShop) needs GetEqualityComponents() written explicitly — without it, the class silently falls back to reference equality, and two Address instances with identical fields would compare as not equal. The immutability of a record and value-based equality are two separate properties; using a record gets both at once, but a class requires deliberate implementation of each.

When the concept has no meaningful identity beyond its component fields — an Address, a Money amount, a date range. You never need to look it up, reference it across contexts, or track it over time by an ID. If two instances have identical field values, they are the same thing, and there’s no reason to distinguish them. If the concept needs a unique identifier for lookup or lifecycle tracking, it’s an Entity.

Value Objects are simpler (no ID management, no ORM identity mapping) but they’re replaceable — you can’t reference a specific Address instance across transactions. If you later discover you need to track a specific address’s lifecycle (e.g., “was this address updated after the order shipped?”), you’ve made a structural commitment to equality-by-value that’s expensive to unwind into an Entity with identity.

Topic: Aggregates & Aggregate Roots (Order 3)

Without a consistency boundary, any code path can freely mutate the internals of a related object graph — adding duplicate line items, applying incorrect discounts, adding items after an order ships — and no single place is responsible for keeping the whole graph consistent. The aggregate root (Order) is the sole entry point for all mutations, so every change runs through its business rules before it takes effect.

The item collection is private readonly List<OrderItem>, exposed externally only as IReadOnlyCollection<OrderItem> — there is no public Add or Remove method. The only way to mutate items is through Order.AddOrderItem(...), which merges duplicate product lines (keeping the higher discount) and adds units to existing lines. The language-level enforcement means a developer literally cannot bypass the root’s rules without refactoring.

You’ve defeated the purpose of the aggregate boundary: now two places are responsible for “is this consistent,” and the transactional coupling means a failure in one aggregate’s rules can roll back the other’s changes unexpectedly. The DDD rule is to reference other aggregates by identity (ID) only, not to load and mutate them together — cross-aggregate consistency is handled through domain events or eventual consistency, not a shared transaction.

Treating it as just “a bigger object with sub-objects inside it,” making it interchangeable with a plain composed class or a database join. The specific claim an aggregate makes is narrower and stronger: everything inside the boundary is only mutated through the root, and everything outside is referenced only by identity — never loaded and saved together in the same transaction. The transactional isolation between aggregates, not just internal encapsulation, is the part most often dropped.

It’s a pure marker interface — its only job is to be checkable at compile time or via reflection (“does this type represent an aggregate root?”). The codebase uses it as a constraint on generic repository interfaces (IRepository<T> where T : IAggregateRoot), so repositories can only be registered for aggregate roots, never for internal objects like OrderItem. The absence of an IOrderItemRepository is the structural enforcement of “only the root is reachable from outside.”

When a duplicate product line is found, the root keeps the higher discount and adds units to the existing line rather than creating a separate entry. This is a business policy (“the customer gets the best discount they’ve earned”) encoded in the one method responsible for item consistency. If external code could append directly to _orderItems, this rule would either be duplicated at every call site or simply not enforced at all.

Topic: Domain Events — Dispatch Timing (Order 4)

It guarantees that if a handler fails, the aggregate’s own change is rolled back along with it — both live in the same transaction. If events were dispatched after commit, the aggregate’s change would be durable regardless of whether handlers succeed, requiring compensating actions for partial failures. The before-commit approach trades atomicity for simplicity: either everything succeeds together, or nothing is persisted.

It uses EF Core’s change tracker to find all tracked entities where DomainEvents?.Any() is true, collects all events into a flat list, calls ClearDomainEvents() on every entity first, then publishes each event via mediator.Publish() — all before base.SaveChangesAsync() runs. Clearing before publishing prevents a handler that calls AddDomainEvent from having those new events re-collected in the same dispatch pass.

SaveChangesAsync never runs — the entire transaction is rolled back, including the aggregate’s own state change that triggered the event. The handler’s DB writes and the aggregate’s writes share the same DbContext and transaction, so a failure in either propagates to both. This is a deliberate choice documented explicitly in OrderingContext.SaveEntitiesAsync’s own comments.

Domain events (INotification, dispatched via MediatR, handled in-process, same transaction) represent facts internal to a single service. Integration events (UseIntegrationEventLogs(), persisted to an outbox table, published to other services after commit) cross service boundaries and are eventually consistent. Conflating them leads to either publishing cross-service messages inside a transaction that might roll back, or expecting same-transaction guarantees from an eventually-consistent mechanism.

If a handler itself calls AddDomainEvent on the same or another entity (a legitimate pattern — one event raising a further event), clearing before publishing ensures the original batch can’t be accidentally re-collected and re-published in the same pass. Only a genuinely new call to SaveEntitiesAsync would pick up newly-added events. Clearing after would risk infinite re-dispatch.

After-commit dispatch means the aggregate’s change is already durable regardless of what handlers do — so handler failures require compensating actions (retries, dead-letter queues, rollback commands) rather than a simple transaction rollback. It gives better availability (the aggregate’s write succeeds even if side effects fail) at the cost of eventual consistency and significantly more failure-handling complexity.

Topic: Domain Services vs Application Services (Order 5)

An application service orchestrates a use case: it resolves dependencies via DI, loads or creates the aggregate, calls the aggregate’s own methods (never re-implementing decisions), persists the result, and publishes integration events. It deliberately contains no business rules. A domain service holds logic that’s genuinely part of the domain but doesn’t belong to any single aggregate instance — logic that must reason across many instances or coordinate between different aggregate types.

Not as a textbook domain service — it’s a raw SQL query run from a background worker (GracePeriodManagerService, a BackgroundService in a separate OrderProcessor process). The query (WHERE CURRENT_TIMESTAMP - "OrderDate" >= @GracePeriodTime) directly hits the ordering.orders table, bypassing the aggregate and repository entirely. This is a pragmatic infrastructure choice, not the clean IGracePeriodPolicy domain service a textbook would suggest.

The business rule exists in exactly one place — the SQL predicate — but nothing about Order itself enforces or represents it. A future change to what “expired” means has to be made in a raw SQL string in an unrelated microservice, not in the domain model a reader would naturally look to first. This is a real, honest gap worth naming: the logic is correct but its location violates the principle of keeping domain rules in the domain layer.

The handler sequences steps: publish an integration event, build the aggregate via its constructor, call AddOrderItem, save. Every line that could be described as “a business rule” is actually a call into the aggregate — the handler never decides whether an order is valid. Order’s constructor and AddOrderItem are where invariants are enforced. The handler is pure orchestration.

Rules in the application service only apply when that specific use case is executed — a different API endpoint or background job that constructs the same aggregate won’t run those rules. The aggregate is the consistency boundary; rules inside it apply regardless of who constructs or mutates it. Rules in the application service are effectively per-use-case guards, not invariants.

Performance — loading every submitted Order aggregate through IOrderRepository and inspecting its date in memory would be orders of magnitude slower than a single SQL query that filters at the database level. The pragmatic choice trades domain purity for operational efficiency, especially when the policy runs as a periodic background job where query performance directly affects system throughput.

Topic: Repositories as Aggregate Persistence Boundaries (Order 6)

Without this restriction, any code path can independently query OrderItem rows directly (raw SQL, a generic DbSet<OrderItem> LINQ query, a separate OrderItemRepository), load/mutate/save items without touching the Order that owns them — silently bypassing every invariant AddOrderItem enforces. The repository boundary mirrors the domain model’s consistency boundary at the persistence layer.

It performs two separate calls to the DbContext: FindAsync for the Order root, then an explicit Entry(order).Collection(i => i.OrderItems).LoadAsync() for the items. This eagerly loads the entire graph before returning — the caller never receives an Order that looks complete but silently issues another database round-trip the first time .OrderItems is touched (which is what lazy loading would do).

Lazy loading would let a caller receive an Order that looks complete but silently issues another database round-trip when .OrderItems is first accessed — possibly outside the original transaction or DbContext lifetime. This defeats the aggregate’s consistency boundary: the caller thinks it has the whole graph, but parts of it are loaded later, in a potentially different context, without the root’s invariants being re-checked.

All the actual decision-making already happened earlier through the aggregate’s own methods — the repository’s job at save time is purely mechanical. The aggregate ensured invariants when the mutation happened; the repository just tells EF Core to persist whatever state the aggregate ended up in. Duplicating that logic in the repository would violate single responsibility and create two places to update when invariants change.

The DbContext itself is the unit of work — so _orderRepository.UnitOfWork returns the same context the repository operates through. This makes SaveEntitiesAsync() (the method that dispatches domain events before committing) available directly from _orderRepository.UnitOfWork, unifying repository and unit-of-work without two competing abstractions.