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.
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.
"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 aCustomernavigation 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
OrderPlaceddomain 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."
| 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 |
| 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 |
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%].
Checks that the candidate can design aggregate boundaries for consistency and performance, not just recite the definition.
Green flags
Red flags
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.
+------------------ 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.
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.
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.
Include for children (or a JSON column for small child collections).AsNoTracking and Select.IReadOnlyCollection<T> backed by a private List<T> field; EF Core maps the backing field.DbSet only; children are reached via navigations.AddLine calls on the same order cause a DbUpdateConcurrencyException.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);
});
Include chains pull in thousands of rows. Instead: reference by strongly typed id.List<OrderLine> publicly. Why it is wrong: callers can add lines without the root checking invariants. Instead: IReadOnlyCollection<T> over a private backing field.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.AsNoTracking and Select.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.
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.
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.
SaveChanges), so their side effects commit or roll back together.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.
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.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.
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.
Last updated 23 Nov 2026.