Lesson 20 of 28Domain-driven design
Domain-Driven Design: Aggregates and Entities
Model rules in code with entities, value objects and aggregates, keep invariants safe under concurrency, and raise domain events the right way.
A B2B shop gives each company account a credit limit of 5,000. Finance finds an order for 5,900 that should never have been accepted. The code checked the limit, so what happened? Two buyers from the same company added lines to the same order at the same moment. Each request loaded the order, saw 3,800, added its line, checked "under 5,000", and saved. Both checks passed, and the rule broke anyway. This is the kind of bug tactical domain-driven design exists to prevent. It gives you building blocks (entities, value objects, aggregates, repositories, domain events) that put each business rule in one place and keep it true even under concurrent writes.
Entities and value objects
DDD sorts the objects in a domain model into two kinds.
An entity has an identity that lasts over time. Order 42 is still order 42 after you add a line, change the address and ship it. Two orders with exactly the same lines are still two different orders. Entities are compared by id, and they usually change.
A value object has no identity. It is defined entirely by its values. A 10 euro note is as good as any other 10 euro note. Money(1000, "EUR") equals any other Money(1000, "EUR"). Value objects are compared by value, and they are immutable: to "change" one, you create a new one.
The real power of value objects is that they validate once and carry their rules. An Email that exists is a valid email. A DateRange cannot end before it starts. Money refuses to add euros to dollars. Without them you get primitive obsession: amount: int and currency: str passed around separately, and every function re-checking (or forgetting to check) the same rules.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.In Python, @dataclass(frozen=True) gives you value equality, hashing and immutability for free. TypeScript has no value equality for objects, so you write equals yourself and make fields readonly. A private constructor plus a static of factory means every Money in the system went through validation.
What does this print?
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
cents: int
currency: str
@dataclass
class Customer:
id: int
name: str
prices = {Money(500, "EUR"), Money(500, "EUR"), Money(500, "USD")}
a = Customer(1, "Sam")
b = Customer(1, "Sam")
print(len(prices), a == b, a is b)Aggregates: the consistency boundary
Back to the credit limit bug. The rule "an order's total may not exceed the company's credit limit" is an invariant: something that must be true every time the order is saved. The problem was that nothing owned it. Any code could append to order.lines, and the check ran in a service, separately from the write.
An aggregate is a cluster of objects treated as one unit for changes. It has one entity at the top, the aggregate root, and outside code may only talk to the root. The Order is the root; its OrderLines are inside. Nobody outside does order.lines.append(...). They call order.add_line(...), and the root checks the invariant before accepting the change.
Press Run (⌘ Enter) to see what happens.This fixes the bug for a single request. The concurrent case needs one more piece, optimistic concurrency, which you will see shortly. The important design move is already there: the rule and the data it protects live in the same object and change in the same transaction.
Four rules for designing aggregates
Vaughn Vernon's guidelines (from Implementing Domain-Driven Design and his "Effective Aggregate Design" essays) are what interviewers and reviewers usually mean by "good aggregates":
- Model true invariants in consistency boundaries. Put together only what must be consistent immediately. The credit limit and the order lines must be. The order and the customer's loyalty points need not be.
- Design small aggregates. A
Customeraggregate that contains all their orders loads thousands of rows to change an email address, and every write to any order conflicts with every other. Most aggregates are a root plus a few value objects. - Reference other aggregates by id.
Orderholdscustomer_id, not aCustomerobject. This stops one aggregate from quietly modifying another, and keeps loading cheap. - Use eventual consistency outside the boundary. One transaction changes one aggregate. When submitting an order should award loyalty points, the order raises
OrderSubmitted, and a separate handler updates theLoyaltyAccountin its own transaction.
Rule 4 surprises people. "Why not update both in one transaction?" Because then two unrelated aggregates lock together, contention grows, and the moment the two move into different services, the code breaks. Ask the domain expert: "if the points appear two seconds later, is that a problem?" The answer is almost always no.
Match each design smell to the aggregate rule it breaks.
Anemic vs rich domain models
An anemic domain model has classes that are bags of getters and setters, with all the rules in services:
def add_line(order_id, sku, qty, unit_cents):
order = repo.get(order_id)
if order.status != "draft":
raise ValueError("locked")
total = sum(l.qty * l.unit_cents for l in order.lines)
if total + qty * unit_cents > order.credit_limit_cents:
raise CreditLimitExceeded()
order.lines.append(OrderLine(sku, qty, unit_cents))
repo.save(order)It works until a second code path (a bulk import, an admin endpoint, a CLI script) appends lines without the check. The rich version you saw above makes the wrong thing impossible: there is no public way to add a line without the check. The service shrinks to "load, call the domain, save".
Martin Fowler called the anemic model an anti-pattern, but be honest about where it is fine: if your app is mostly CRUD (forms that save rows, with few rules), a rich model adds ceremony for nothing. Use rich aggregates where the rules are complex and costly to get wrong, which is usually your core subdomain from the previous lesson.
Repositories and domain services
A repository loads and saves whole aggregates. There is one per aggregate root, not one per table: OrderRepository.get("o-42") returns an Order with its lines, even though they live in two tables. There is no OrderLineRepository, because loading a line on its own would let you change it without the root checking anything.
class OrderRepository(Protocol):
def get(self, order_id: str) -> Order: ...
def add(self, order: Order) -> None: ...
def save(self, order: Order) -> None: ... # raises ConcurrencyConflict on a stale versionRepositories sit behind a port, exactly as in the hexagonal lessons, and the Unit of Work from the Python backend lesson wraps the transaction.
Some logic does not belong to any single entity. "Transfer money between two accounts" touches two aggregates, and putting it on either one feels wrong. A domain service is a stateless function or class in the domain layer that holds such logic, expressed in the ubiquitous language: transfer(from_account, to_account, amount), or PricingService.quote(basket, customer_tier). Do not confuse it with an application service (the use case that loads, calls and saves). A domain service contains business rules; an application service contains orchestration.
Factories handle creation when it is complex: building an Order from a quote, a cart and a customer's terms, with several invariants to check. A class method like Order.from_quote(quote, terms) or a small factory function keeps the constructor simple and still guarantees that every new aggregate starts valid.
Persisting aggregates with an ORM
The question every team hits in week one: "how do I save a rich Order with SQLAlchemy or Prisma?" There are two honest options.
- Map the domain class directly. SQLAlchemy's imperative mapping (
registry.map_imperatively(Order, orders_table, ...)) attaches persistence to a plain class without the class importing SQLAlchemy. It is less code, but ORM behaviour (lazy loading, session state) can leak into the domain, and you must still hide_linesbehind methods. - Keep separate persistence models and map. The repository loads ORM rows (or Prisma or Drizzle results in TypeScript), builds the
Order, and on save turns it back into rows. It costs a mapping function per aggregate, but the domain stays plain and the table design is free to change. Most TypeScript codebases do this, since Prisma and Drizzle return plain objects anyway.
Either way, a few habits matter more than the choice:
- Save the whole aggregate in one transaction. Replacing the lines of one order in a single transaction is fine because aggregates are small.
- Put the version column on the root's table and bump it on every change, even when only a line changed. Otherwise two edits to different lines will not conflict when they should.
- Value objects usually become columns, not tables:
total_centsandtotal_currency, or a JSON column for a small list. - Never let a lazy-loaded relationship reach into another aggregate. That is the object reference rule broken through the ORM.
Domain events from aggregates
When an aggregate changes in a way others care about, it records a domain event, as submit() did above. The aggregate does not send emails or call other services. It just appends OrderSubmitted to a list.
The application service then saves the aggregate and its events in one transaction, writing events to the outbox table you met in the event-driven architecture lesson. A relay publishes them afterwards. The order matters:
- Dispatch events before commit and the transaction may roll back, so you announced something that never happened.
- Publish after commit without an outbox and a crash in between loses the event.
- Write them to the outbox in the same transaction, and both problems go away.
In-process handlers (update a read model in the same module) can run right after commit; cross-context handlers go through the outbox and broker.
Optimistic concurrency: closing the race
The aggregate guards the invariant within one request. Two concurrent requests still each load their own copy. The standard fix is optimistic concurrency: every aggregate has a version. Saving says "update this order only if its version is still the one I loaded", and bumps the version. If someone else saved first, zero rows match, and you raise a conflict. The caller retries from a fresh load, and this time the invariant check sees the other line.
add DESK (1,000)
Here it is with a real database. SQLite runs in your browser, so this is the actual SQL pattern.
Press Run (⌘ Enter) to see what happens.Two notes. Optimistic locking works because aggregates are small: conflicts are rare, so retrying is cheap. And it only protects what is inside one aggregate. If your invariant spans two aggregates, either the boundary is wrong, or the rule really is eventually consistent and needs a process (a policy or saga) to correct it.
Order the steps of a well-built add line use case.
- Tap the steps below in the right order.
- entity
- A domain object with an identity that persists over time; compared by id, not by its fields.
- value object
- An immutable object defined only by its values, such as Money or DateRange, that validates itself on creation.
- aggregate
- A cluster of objects changed as one unit through a single root, forming the boundary where invariants are enforced.
- invariant
- A business rule that must be true every time an aggregate is saved.
- anemic domain model
- Domain classes that hold data but no behaviour, with all rules in services, so any code path can bypass them.
- domain service
- Stateless domain logic that does not belong to a single entity, such as transferring money between two accounts.
- optimistic concurrency
- Saving only if the version is unchanged since loading, and retrying on conflict instead of holding locks.