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

📚 Interview question

What is an aggregate and what is an aggregate root? Explain the aggregate as a consistency boundary, how you decide what goes inside it, why other aggregates are referenced by id, and why the rule is one aggregate per transaction.

Covers aggregates and aggregate roots, invariants and consistency boundaries, sizing aggregates, referencing by id, and the one-aggregate-per-transaction rule with eventual consistency between aggregates.

Mid-Level Theory Intermediate aggregates architecture domain-driven-design ef-core eventual-consistency invariants

🎯 Key points

  • Aggregate = cluster of entities and value objects that must be consistent together; one root entity
  • The root is the single entry point: it encapsulates the aggregate, so all changes go through its methods and invariants cannot be bypassed
  • Boundary is drawn around true invariants (rules that must hold at commit), not around data relationships
  • Design small aggregates (Vaughn Vernon): large ones or navigations between roots cause slow loads, wide locks and contention
  • Reference other aggregates by id (CustomerId), not by navigation property
  • Modify one aggregate per transaction; other aggregates update via domain events (eventual consistency)
  • Optimistic concurrency (rowversion) on the root protects the whole aggregate
  • Logic needing several aggregates goes in a domain service that reads them and changes only one; repository per aggregate root

⏱ 30-second answer

An aggregate is a cluster of entities and value objects that must stay consistent together, with one entity as the aggregate root. Outside code talks only to the root, so the root can enforce the invariants: rules that must be true whenever the transaction commits (an order's total equals its lines; a booking never exceeds capacity).

Keep aggregates small: draw the boundary around real invariants, not around every relationship. Reference other aggregates by id (CustomerId), not by object, so loading an order does not drag in the customer. Change one aggregate per transaction; when another aggregate must react, publish a domain event and update it in a separate transaction. The trade-off is eventual consistency between aggregates in exchange for low contention and clear ownership.

🗣 Full answer (senior)

How I would answer this in an interview

"An aggregate is a group of domain objects that we treat as one unit for changes, because there are business rules that span them. The aggregate root is the single entity that the outside world is allowed to hold and call. In an Order aggregate, the root is Order and the lines are inside it. Nobody adds an OrderLine directly; they call order.AddLine(...), and that method checks the invariants: the order is not already submitted, the quantity is positive, the total stays under the customer's credit limit snapshot. So the aggregate is a consistency boundary: when it is saved, every rule inside it holds.

The hard part is drawing the boundary. The trap is to follow the data model: an Order has a Customer, the Customer has Addresses, so let's make one big Customer aggregate with orders inside. That gives you huge objects to load and constant concurrency conflicts, because two people editing different orders are now editing the same aggregate. I follow Vaughn Vernon's rules: design small aggregates, put inside only what must be consistent at commit time, and reference other aggregates by id. So Order holds a CustomerId, not a Customer navigation property.

The other rule is one aggregate per transaction. If placing an order should also reserve stock, that is a different aggregate, so the Order raises an OrderPlaced domain event and a handler reserves stock in its own transaction, or a process manager does it with compensation if stock is short. Users usually accept a second of delay; the business rarely needs both to be atomic, and when they say they do, I ask what happens today when the warehouse is wrong. The mistake I see is reaching for a distributed transaction instead of asking that question. Small aggregates, ids between them, events across them."


Rules of aggregate design

Rule Why
Protect true invariants inside the boundary That is the only reason the boundary exists
Design small aggregates Fast to load, fewer concurrency conflicts
Reference other aggregates by identity No accidental loading or modification of others
Use eventual consistency outside the boundary One transaction per aggregate scales and keeps ownership clear
Only the root is referenced from outside Invariants cannot be bypassed

Deciding what goes inside

Question If yes If no
Must this rule hold at the moment of commit? Same aggregate Separate aggregates + event
Do these objects have a lifecycle of their own? Probably separate aggregate Probably inside
Would two users often edit them at once? Split to reduce contention Can stay together
Is the collection unbounded (all orders of a customer)? Separate aggregate Can be inside

Production example

A [booking] system had a Venue aggregate containing every Booking for the year. Loading it took [800 ms] with 20,000 rows and caused [~4%] concurrency exceptions at peak. We made Booking its own aggregate, kept capacity as a per-session SessionCapacity aggregate with a rowversion, and load time dropped to [15 ms] with conflicts under [0.1%].

🔍 What the interviewer is checking

Checks that the candidate can design aggregate boundaries for consistency and performance, not just recite the definition.

Green flags

  • Defines the aggregate as a consistency boundary around invariants
  • Argues for small aggregates and reference by id
  • Explains one aggregate per transaction and eventual consistency via events
  • Mentions optimistic concurrency on the root

Red flags

  • Treats aggregates as "a table and its child tables"
  • Puts unbounded collections inside an aggregate
  • Wants distributed transactions across aggregates

📚 Learn in depth

1. What an invariant really is

An invariant is a rule that must be true whenever an aggregate is persisted: "order total = sum of lines", "a session never has more bookings than seats". Rules that can be fixed up later ("a loyalty point is credited after an order") are not invariants of the order; they are reactions.

2. Structure

+------------------ Order aggregate -------------------+
|                                                      |
|   Order (root) ── Id, CustomerId, Status, Total      |
|     │                                                |
|     ├── OrderLine (entity, local identity)           |
|     ├── OrderLine                                    |
|     └── ShippingAddress (value object)               |
+------------------------------------------------------+
        │ CustomerId (id only)          │ ProductId (id only)
        ▼                               ▼
  Customer aggregate              Product aggregate

Inside entities (OrderLine) have identity only within the aggregate; outside code never holds them.

3. One transaction per aggregate

Tx 1: load Order ──► order.Place() ──► save Order + outbox(OrderPlaced)
                                         │
                                         ▼ (async, seconds)
Tx 2: load Stock ──► stock.Reserve(...) ──► save Stock

Within a modular monolith you can dispatch domain events in-process inside the same SaveChanges when you truly need atomicity, but it is a deliberate exception: it couples two aggregates' consistency and lock lifetimes.

4. Concurrency

A rowversion column on the root, configured with IsRowVersion(), makes EF Core add WHERE RowVersion = @original to the update. Any change to a child (adding a line) must also touch the root so its version increments; otherwise two users could add lines concurrently and break the total. EF Core updates the root's rowversion only if the root row is updated, so bump a Version or modified timestamp on the root in every behaviour method.

5. Size and performance

  • Loading an aggregate = one query with Include for children (or a JSON column for small child collections).
  • Large child collections (thousands of lines) mean the boundary is wrong.
  • Read screens should not load aggregates at all: use projections with AsNoTracking and Select.

6. EF Core specifics

  • Expose children as IReadOnlyCollection<T> backed by a private List<T> field; EF Core maps the backing field.
  • Configure the root's DbSet only; children are reached via navigations.
  • Do not add navigation properties to other aggregate roots; store their ids.

Try it yourself

  1. List the invariants of an aggregate in your current system. Is every object inside needed for one of them?
  2. Write a test that two concurrent AddLine calls on the same order cause a DbUpdateConcurrencyException.
  3. Find a navigation property between two aggregate roots and replace it with an id; see what breaks.
  4. Measure the load time of your largest aggregate with Application Insights dependency timings.

💻 Code

A small Order aggregate: the root guards invariants, children are hidden, other aggregates are ids.

namespace Ordering.Domain;

public readonly record struct OrderId(Guid Value);
public readonly record struct CustomerId(Guid Value);
public readonly record struct ProductId(Guid Value);

public enum OrderStatus { Draft, Placed, Cancelled }

public sealed class OrderLine
{
    internal OrderLine(ProductId productId, int quantity, decimal unitPrice)
        => (ProductId, Quantity, UnitPrice) = (productId, quantity, unitPrice);

    private OrderLine() { } // EF Core

    public int Id { get; private set; }          // local identity
    public ProductId ProductId { get; private set; }
    public int Quantity { get; private set; }
    public decimal UnitPrice { get; private set; }
    public decimal LineTotal => Quantity * UnitPrice;
}

public sealed class Order
{
    private readonly List<OrderLine> _lines = [];

    private Order() { } // EF Core

    public Order(CustomerId customerId) => CustomerId = customerId;

    public OrderId Id { get; private set; } = new(Guid.CreateVersion7());
    public CustomerId CustomerId { get; private set; }   // reference by id, not navigation
    public OrderStatus Status { get; private set; } = OrderStatus.Draft;
    public decimal Total { get; private set; }
    public byte[] RowVersion { get; private set; } = [];
    public IReadOnlyCollection<OrderLine> Lines => _lines.AsReadOnly();

    public void AddLine(ProductId productId, int quantity, decimal unitPrice)
    {
        if (Status != OrderStatus.Draft) throw new InvalidOperationException("Only draft orders can change.");
        if (quantity <= 0) throw new ArgumentOutOfRangeException(nameof(quantity));
        if (_lines.Count >= 50) throw new InvalidOperationException("An order has at most 50 lines.");

        _lines.Add(new OrderLine(productId, quantity, unitPrice));
        Total = _lines.Sum(l => l.LineTotal); // invariant: total = sum of lines; also updates the root row
    }

    public void Place()
    {
        if (_lines.Count == 0) throw new InvalidOperationException("Cannot place an empty order.");
        Status = OrderStatus.Placed;
    }
}
// EF Core configuration: backing field for the children, rowversion on the root.
b.Entity<Order>(e =>
{
    e.HasKey(o => o.Id);
    e.Property(o => o.Id).HasConversion(id => id.Value, v => new OrderId(v));
    e.Property(o => o.CustomerId).HasConversion(id => id.Value, v => new CustomerId(v));
    e.Property(o => o.RowVersion).IsRowVersion();
    e.Property(o => o.Total).HasPrecision(18, 2);
    e.HasMany(o => o.Lines).WithOne().HasForeignKey("OrderId");
    e.Navigation(o => o.Lines).UsePropertyAccessMode(PropertyAccessMode.Field);
});

⚠ Common mistakes

  • Mistake: Drawing aggregates around the data model (Customer with all Orders inside). Why it is wrong: huge loads and constant concurrency conflicts. Instead: draw boundaries around invariants and keep aggregates small.
  • Mistake: Navigation properties between aggregate roots. Why it is wrong: code can load and modify another aggregate in the same transaction, bypassing its root, and Include chains pull in thousands of rows. Instead: reference by strongly typed id.
  • Mistake: Modifying several aggregates in one transaction by default. Why it is wrong: wider locks, more conflicts, and unclear ownership. Instead: one aggregate per transaction; react to domain events.
  • Mistake: Exposing List<OrderLine> publicly. Why it is wrong: callers can add lines without the root checking invariants. Instead: IReadOnlyCollection<T> over a private backing field.
  • Mistake: Rowversion only on child rows. Why it is wrong: concurrent changes to different children both succeed and break aggregate-wide rules. Instead: rowversion on the root and touch the root on every change.
  • Mistake: Using ExecuteUpdate / ExecuteDelete (EF Core 7+) on aggregate data. Why it is wrong: they go straight to SQL, skipping the root's invariants, domain events and the change tracker. Instead: keep them for bulk maintenance and projections, not for business changes to aggregates.
  • Mistake: Loading aggregates for read screens. Why it is wrong: wasted tracking and joins. Instead: query projections with AsNoTracking and Select.
  • Mistake: Treating every business reaction as an invariant. Why it is wrong: it pulls unrelated objects into one boundary. Instead: ask whether the rule must hold at commit, or can be eventual.

🏛 Senior insight: trade-offs

Aggregate design is a trade-off between consistency and concurrency. A bigger aggregate gives stronger guarantees and more contention; a smaller one gives throughput and requires eventual consistency and compensations. The senior move is to challenge "it must be atomic" with the business: most cross-aggregate rules are already eventual in the real world (stock counts are wrong today too).

How I make the call: I ask the business what a user sees if the rule is briefly violated and what that costs. If the answer is "a customer could be charged twice" or "a session is overbooked and someone is turned away at the door", the rule goes inside one aggregate and I accept contention. If the answer is "a dashboard is a few seconds behind" or "loyalty points appear a moment later", it goes across aggregates with a domain event and a UX that says "processing". When a rule needs data from several aggregates (pricing using the customer's tier), a domain service reads them and changes only one.

Option When it fits Cost When not to
Small aggregate + domain events Most cases; high concurrency Eventual consistency, handlers, outbox Rule truly must hold at commit
Larger aggregate Tight invariant across a few objects, low concurrency Contention, load time Unbounded collections
Two aggregates in one transaction (in-process) Modular monolith, rare deliberate exception Coupling, longer locks Across services or databases

I measure aggregate health with load time, concurrency exception rate and row counts per aggregate.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions concurrency conflicts between users editing the same aggregate. Why: Checks they can find and fix race conditions in database-backed code.
    How to answer

    A race condition is a bug where the result depends on the timing of concurrent operations. Classic forms are read-modify-write (count++ from two threads), check-then-act (if (!dict.ContainsKey(k)) dict.Add(k, v)), and unsafe publication. In .NET they also appear with non-thread-safe collections (a shared Dictionary or List corrupted under concurrent writes), in async code that interleaves at await points even on one thread, and in databases as lost updates when two requests read, modify and save the same row. Fixes: atomic operations, locks, concurrent collections, immutability, single-writer designs, and in databases optimistic concurrency tokens, unique constraints and idempotency.

  2. When: Candidate says other aggregates are updated via domain events. Why: Checks they know domain versus integration events and dispatch timing.
    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.

  3. When: Candidate mentions one repository per aggregate root. Why: Checks they know what a good repository interface looks like.
    How to answer

    A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.

    In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:

    • IQueryable<T> GetAll() leaks EF semantics to callers.
    • Save() per repository breaks the unit of work.
    • It invites repositories for child entities, which bypass the aggregate's rules.

    A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.

🛠 Real-world problems: how you handle them

Oversized Venue aggregate causing slow loads and concurrency conflicts
Situation
A [ticketing] platform modelled `Venue` as an aggregate containing every `Session` and `Booking` for the season, [~20,000 bookings] per large venue. Peak on-sale events had [3,000] concurrent buyers.
Signals
Application Insights showed [800 ms+] SQL dependency calls on `GetVenueById`, `DbUpdateConcurrencyException` on [~4%] of booking attempts, and customer complaints about 'please try again' errors during on-sales.
Investigation
Traced booking requests end to end in Application Insights, used Query Store to find the large Include query, counted rows loaded per request, and listed the invariants the aggregate was meant to protect with the product owner: the only real rule was 'a session never exceeds capacity'.
Resolution
Short term, added retry with fresh reload on concurrency conflicts. Long term, split into a `Booking` aggregate and a small `SessionCapacity` aggregate (seats remaining + rowversion), referenced by `SessionId`. Booking reserved capacity in the same transaction for that single small row, with venue-level reporting moved to projections.
Prevention
Added an architecture test that bans navigation properties between aggregate roots, a load-time alert on aggregate repository calls over [100 ms], and an ADR documenting the aggregate boundaries and their invariants.

How to tell it (STAR)

**S:** At [company], our ticketing system's Venue aggregate held every booking for a season, and during on-sales [4%] of purchases failed with concurrency errors. **T:** I was asked to [stop the errors before the next major on-sale in three weeks]. **A:** I traced the requests, found each booking loaded [20,000] rows, and ran a short session with the product owner to list the real invariants. Only seat capacity mattered, so I proposed splitting Booking out and keeping capacity in a tiny per-session aggregate, wrote it up as an ADR and paired with [a teammate] on the migration. **R:** Load time fell from [800 ms to 15 ms] and conflict errors dropped below [0.1%] in the next on-sale.

↩ Usually asked after

More in Domain-Driven Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me