System Design HLD-14.06
Domain-driven design for architects
Bounded contexts, ubiquitous language, aggregates and context maps, and why bounded contexts are the best guide for drawing service boundaries.
The big idea
Ask five departments of an online store what a "product" is. Catalog says: title, description, photos, categories. Pricing says: list price, discounts, currency rules. Warehouse says: dimensions, weight, bin location, stock count. Shipping says: package size, hazardous-goods flags. One shared Product class with all of that becomes a 200-field monster that every team edits and every change breaks. The word "product" means different things in different parts of the business, and that is fine.
Domain-driven design (DDD)An approach to software design that models the business domain closely, dividing it into bounded contexts with their own models and language, developed with domain experts. embraces this. It splits a large domain into bounded contextsA part of the business with its own consistent model and vocabulary, within which each term has one precise meaning., each with its own model and its own precise vocabulary. Inside Pricing, "product" means a priced item, and that is all. Contexts relate to each other through explicit translations, not a shared model. Those boundaries turn out to be the most reliable places to draw service and team boundaries.
Think of a hospital. Billing, the pharmacy and the operating theatre all deal with "the patient", but each keeps its own records in its own terms. They exchange exactly what they need, through defined forms, rather than sharing one giant chart everyone scribbles on.
How it works
Step 1: Ubiquitous language
Within a context, developers and domain experts use one shared vocabulary, the ubiquitous languageThe precise shared vocabulary that domain experts and developers use within a bounded context, reflected directly in the code., in conversation, documents and code. If the business says "a booking is confirmed when the deposit clears", the code has a Booking with a confirm() triggered by DepositCleared, not a record with status = 3. When the language becomes ambiguous ("customer" meaning two different things), that is often a sign of two contexts.
Step 2: Bounded contexts and context maps
A context map shows the contexts and how they relate, which is as much about teams as code. Common relationships:
- Customer and supplier: one context depends on another, which accommodates its needs.
- Open host service and published language: a context offers a stable, documented API or event format for anyone to use.
- Anti-corruption layer: a translation layer that protects your model from a messy or foreign one, such as a legacy system or an external provider ( Migrating architectures: the strangler fig ).
- Conformist: you simply adopt another context's model, typically when you have no influence over it.
- Shared kernel: two contexts deliberately share a small piece of model, with joint ownership.
Step 3: Aggregates
Inside a context, an aggregateA cluster of domain objects treated as one unit for changes, accessed only through its root, which enforces the cluster's invariants; one aggregate is saved in one transaction. groups objects that must change together to stay consistent, with one root that all changes go through. An Order with its OrderLines is an aggregate: you never edit a line directly, because the order enforces rules such as "the total must not exceed the customer's credit limit" and "a placed order cannot change".
class Order:
"""Aggregate root: all changes to the order and its lines go through here,
so the invariants are checked in one place and saved in one transaction."""
MAX_LINES = 50
def __init__(self, order_id, credit_limit):
self.id, self.credit_limit = order_id, credit_limit
self.lines, self.status = [], "draft"
def add_line(self, sku, qty, unit_price):
if self.status != "draft":
raise ValueError("cannot change a placed order")
if len(self.lines) >= self.MAX_LINES:
raise ValueError("too many lines")
if self.total() + qty * unit_price > self.credit_limit:
raise ValueError("over the customer's credit limit")
self.lines.append((sku, qty, unit_price))
def total(self):
return sum(q * p for _, q, p in self.lines)
def place(self):
if not self.lines:
raise ValueError("empty order")
self.status = "placed"
return {"event": "OrderPlaced", "order": self.id, "total": self.total()} # for other contexts
o = Order("A-17", credit_limit=500)
o.add_line("book", 2, 30)
o.add_line("lamp", 1, 120)
for attempt in (lambda: o.add_line("sofa", 1, 900), o.place, lambda: o.add_line("pen", 1, 2)):
try:
print("ok:", attempt())
except ValueError as e:
print("rejected:", e)Output
rejected: over the customer's credit limit
ok: {'event': 'OrderPlaced', 'order': 'A-17', 'total': 180}
rejected: cannot change a placed order Every rule lives in the root, so it cannot be bypassed. Aggregates are also the unit of transactions: one aggregate is saved atomically; changes spanning several aggregates are coordinated by events and eventual consistency, which is exactly what place() returns. Keep aggregates small; a giant aggregate becomes a contention hotspot.
Step 4: From contexts to services
A bounded context is a natural candidate for a service or a module of a modular monolith ( Monolith and modular monolith ): it has its own model, its own data and its own language, and it communicates through explicit contracts. Usually one team owns one or more contexts. A service should not span several contexts (it becomes a tangle of conflicting models), and splitting one context across many services usually creates chatty, tightly coupled services that must change together.
Going deeper
Strategic before tactical
DDD has a strategic side (contexts, maps, which parts of the domain are core and deserve the best people) and a tactical side (aggregates, entities, value objects, domain events, repositories). For architects, the strategic side matters most: it decides where boundaries go, and boundaries are expensive to move once services and teams form around them. Event storming workshops, where engineers and domain experts map business events on a wall, are a popular way to discover contexts.
Trade-offs
| Option | Wins when | Loses when |
|---|---|---|
| One shared enterprise model | Tiny domains with one team | Becomes a bloated model every team must coordinate on |
| Bounded contexts with their own models | Complex domains and multiple teams | Translation between contexts and some duplicated data |
| Rich aggregates enforcing invariants | Business rules that must always hold | Design effort; cross-aggregate changes become eventual |
| Services by technical layer | Rarely anything | Every feature touches every service |
Common mistakes
- Building one canonical model of "customer" or "product" for the whole company.
- Drawing service boundaries by technical layer or by database table instead of by domain.
- Huge aggregates that lock half the system on every change.
- Letting a legacy or external model leak into your domain without an anti-corruption layer.
- Using DDD terms without involving the domain experts whose language it is.
In the wild
Domain-driven design was described by Eric Evans in his 2003 book of the same name, and it became the standard vocabulary for discussing service boundaries as microservices spread. Uber's domain-oriented microservice architecture ( Microservices ), which groups services into domains with gateways, applies the same idea at large scale, and event storming is widely used to find boundaries before splitting a system.
Check yourself
-
What is a bounded context?
Show answer
B. A part of the domain with its own consistent model and vocabulary Inside it, terms have one precise meaning; other contexts can model the same word differently.
-
Why does an Order aggregate force all line changes through the order?
Show answer
B. So its invariants, such as the credit limit, are always enforced in one place and saved atomically The root guards the aggregate's consistency rules.
-
You integrate with a payment provider whose data model is awkward. What protects your domain?
Show answer
B. An anti-corruption layer that translates their model into yours The ACL keeps a foreign model from leaking into your context.
-
Which is the best guide for service boundaries?
Show answer
B. Bounded contexts of the business domain Contexts have their own models and data, so changes tend to stay inside them.
Recap
- DDD models the business closely, with domain experts, in a shared ubiquitous language.
- Bounded contexts give each part of the domain its own model; the same word can mean different things in different contexts.
- Context maps describe relationships: customer-supplier, published APIs, anti-corruption layers and more.
- Aggregates group what must change together, enforce invariants through a root and are saved atomically.
- Bounded contexts are the most reliable guide for service and team boundaries.