Lesson 19 of 28Domain-driven design
Domain-Driven Design: Bounded Contexts
Split a large domain into bounded contexts with their own language, map how they relate, and protect your model from legacy and vendor systems.
Layers, ports and modules tell you how to divide code. They do not tell you where the lines should fall in the business itself. You join a company where the customers table has 74 columns. Sales added lead_score, Billing added vat_number and dunning_level, Support added sla_tier, and nobody dares delete anything because some report somewhere reads it. Every feature touches the Customer class, every pull request needs three teams to review it, and the word "customer" means something slightly different in every meeting. This is the problem strategic domain-driven design solves. It is less about code patterns and more about where to draw lines in a big system, which is exactly what senior engineers and architects get asked about in interviews and design reviews.
Ubiquitous language
Domain-driven design (DDD) comes from Eric Evans' 2003 book of the same name. Its first idea sounds soft and turns out to be very practical: the team and the domain experts share one language, and the code uses it word for word. Evans called it the ubiquitous language.
If the claims team says "a claim is lodged, then assessed, then settled or declined", your code has lodge(), assess(), settle() and decline(), and a Claim with those states. It does not have create(), update_status(3) and a records table that everyone translates in their head. Translation is where bugs hide. When an expert says "a declined claim can be reopened within 30 days" and your code has no reopen, you have just found a missing feature, not a wording issue.
What this looks like at work:
- A short glossary in the repo (a
GLOSSARY.mdor a section in the design doc) that defines each term in one sentence. - Code review comments like "the business calls this a booking, not a reservation. Can we rename it?"
- Pushing back when a term means two things. If "account" means both a login and a ledger, that ambiguity will become a bug.
The catch is that one company cannot have one language. The word "policy" means an insurance contract to underwriters and a password rule to the security team. That is not a failure to agree. It is a sign there are two models, and that is where bounded contexts come in.
Subdomains: core, supporting, generic
Before drawing boundaries, sort the business itself. A domain is the whole area the company works in (online retail, insurance, logistics). It breaks down into subdomains, and DDD sorts them by how much they matter:
| Kind | What it is | Example for an online shop | What to do |
|---|---|---|---|
| Core | What makes the company win. Competitors cannot just copy it. | Pricing and recommendations | Build it in house, with your best people and the richest model |
| Supporting | Needed and specific to you, but not a differentiator | Returns handling, warehouse slotting | Build it simply, or outsource the build |
| Generic | Every company has the same problem | Login, payments, email, tax rates | Buy it: Auth0, Stripe, SES, a tax API |
This table answers one of the most expensive questions in engineering: what to build and what to buy. Teams burn quarters building their own auth or billing engine (generic) while the pricing logic (core) lives in a 3,000-line script. A senior engineer asks "is this core?" before proposing a custom build.
Bounded contexts
A bounded context is a boundary inside which a model, and its language, is consistent. Inside it, every term has exactly one meaning. Outside it, the same word can mean something else, and that is fine.
Take "Customer" in an online shop:
- In Sales, a customer is a lead or a buyer: name, segment, lead score, assigned rep.
- In Billing, a customer is a payer: legal name, VAT number, payment method, invoices, credit limit.
- In Support, a customer is a person with tickets: contact channel, SLA tier, open cases.
- In Shipping, there is barely a customer at all: a recipient with an address and a phone number.
The tempting design is one Customer class that serves all four. It grows every quarter, every change risks breaking another team, and rules start colliding ("a customer is active if..." active for whom?). That shared model becomes a god class, and because it is shared, nobody owns it.
DDD's answer: give each context its own model, linked only by an identifier.
from dataclasses import dataclass
# Sales context
@dataclass
class Prospect:
customer_id: str
name: str
segment: str # "smb", "enterprise"
lead_score: int
# Billing context
@dataclass
class Payer:
customer_id: str
legal_name: str
vat_number: str | None
credit_limit_cents: int
# Support context
@dataclass
class Requester:
customer_id: str
contact_email: str
sla_tier: str # "standard", "priority"Each class is small and owned by one team. Billing can add dunning_level without Sales noticing. The duplication of name across contexts is deliberate: Sales' "name" might be a nickname, Billing's must be the legal name on the invoice. They are not the same data, they just look alike.
Context maps: how contexts relate
Contexts are not islands. Billing needs to know when Sales closes a deal. A context map draws the contexts and, more importantly, the relationship on each line between them. Each relationship is both technical and political: it says who has to adapt to whom.
- Partnership. Two teams succeed or fail together and plan changes jointly.
- Shared kernel. Two contexts share a small piece of model code (for example a
Moneytype), and changing it needs both teams to agree. Keep it tiny or it becomes the god class again. - Customer/supplier. The upstream team (supplier) takes the downstream team's needs (customer) into its planning. Downstream can ask for changes.
- Conformist. Downstream simply adopts upstream's model as is, because it has no power to change it and translation is not worth it. Common with a big internal platform.
- Anti-corruption layer (ACL). Downstream builds a translation layer so the upstream model never leaks in. The standard move for legacy systems and vendors.
- Open host service / published language. Upstream offers a stable, documented API or event schema for everyone (a versioned REST API, a set of JSON Schema or Protobuf events), instead of custom integrations per consumer.
- Separate ways. No integration at all. Sometimes copying a little data by hand is cheaper than coupling.
The core contexts. Ordering and Pricing are owned by teams that plan together: a partnership.
Match each situation to the context-mapping pattern it describes.
The anti-corruption layer in code
The ACL is the pattern you will build most often. The legacy CRM sends you something like this, with cryptic codes and a status meaning that drifted years ago. Your Billing context wants a clean Payer. The ACL is a small module at the edge that translates and rejects, so the rest of Billing never sees a CUST_TP_CD.
Press Run (⌘ Enter) to see what happens.Notice what the ACL buys you. When the CRM is finally replaced, you rewrite one module and Billing's model does not change. When someone asks "what does A2 mean?", the answer lives in one place. In a larger system the ACL is often a set of classes (a facade over the vendor client, an adapter that implements your port, and translators for each message type), which ties straight back to the structural patterns you met earlier.
What does this print?
CRM_ACTIVE = {"A", "A2"}
def can_invoice(raw):
return raw.get("STAT") in CRM_ACTIVE and raw.get("CR_HLD") != "Y"
rows = [
{"STAT": "A2", "CR_HLD": "N"},
{"STAT": "A", "CR_HLD": "Y"},
{"STAT": "a"},
{"STAT": "A"},
]
print(sum(can_invoice(r) for r in rows))Finding the boundaries with EventStorming
Where do the lines go? You find out with the domain experts, not alone. The most popular workshop is EventStorming, created by Alberto Brandolini. You put everyone in a room (or a shared online whiteboard) with a very long wall and coloured sticky notes:
- Orange: domain events. Everyone writes things that happen, in the past tense: "Order placed", "Payment captured", "Parcel dispatched". No order, no debate, just volume.
- Timeline. Sort the events left to right in time. Gaps and arguments appear immediately.
- Pink: hot spots. Wherever people disagree or nobody knows ("what happens if payment fails after we reserved stock?"), mark it. These are your biggest risks.
- Blue: commands. What triggers each event ("Place order" causes "Order placed"). Add actors (yellow) and policies ("whenever payment fails, release the stock").
- Pale yellow: aggregates. The things that receive commands and enforce rules (Order, Payment, Shipment). You will meet these properly in the next lesson.
- Boundaries. Look for pivotal events where the language and the people change. "Order placed" is where shopping ends and fulfilment starts. Those seams become your context boundaries.
Catalog
Product listed, Price changed
Merchandisers speak about products, variants and listings.
Sales
Item added to basket, Order placed
The pivotal event. After this, the language shifts from browsing to fulfilling.
Billing
Payment authorised, Payment captured, Invoice issued
Hot spot: what if capture fails after stock is reserved? The team writes a policy: release stock and notify the customer.
Fulfilment
Stock reserved, Parcel packed, Parcel dispatched
Warehouse staff talk about picks, bins and parcels. A different model, a different team.
Support
Return requested, Refund issued
Refund issued crosses back into Billing: a relationship to draw on the context map.
Put these domain events for one online order in time order, as they would sit on the EventStorming wall.
- Tap the steps below in the right order.
Contexts, modules and services
A frequent confusion in interviews: "so each bounded context is a microservice?" Not necessarily. A bounded context is a model and language boundary. How you deploy it is a separate choice:
- Several contexts can live in one modular monolith, one module each, as in the modular monolith lesson. This is the right default for most teams.
- One context can become one service when it needs independent deployment, scaling, or a separate team.
- One context should rarely be split across several services. If two services share one model, every change needs both deployed together, which is a distributed monolith.
The rule of thumb: a service boundary should never cut through a context, but a context does not have to be a service. Draw the contexts first. Deployment boundaries follow later, and only when there is a reason.
Teams, ownership and Conway's law
In 1968 Melvin Conway observed that organisations design systems that copy their own communication structure. If three teams build a compiler, you get a three-pass compiler. This is why strategic DDD is half an organisational tool.
- A bounded context should have one owning team. A context owned by nobody (or by everyone) decays into the shared god model.
- One team can own several small contexts. One context shared by several teams almost always goes wrong.
- If your context map and your org chart disagree, one of them will win, and it is usually the org chart. Some companies change team structure on purpose to get the architecture they want, sometimes called the inverse Conway manoeuvre. You will see more of this later in the track.
Mistakes seniors watch for
- Contexts by data, not behaviour. A "Customer service" that just stores customers is an entity service. Every use case then calls it, and it becomes a bottleneck. Contexts should be organised around what people do (ordering, invoicing, shipping).
- A shared database in disguise. Two contexts that read and write each other's tables are one context with extra steps. Each context owns its data; others get it through an API, events or a read-only replica.
- Contexts too small. One context per entity creates chatty integrations for every use case. If two "contexts" always change together, merge them.
- Translation everywhere. An ACL is cheap to write once and costly to maintain. Being conformist to a well-designed upstream is a perfectly good choice.
- Strategic DDD for a CRUD app. A small internal tool with one team and one model does not need a context map. Use the language idea, skip the ceremony.
- ubiquitous language
- The shared vocabulary of developers and domain experts, used word for word in code, inside one bounded context.
- subdomain
- A part of the business. Core subdomains differentiate the company, supporting ones are specific but not differentiating, generic ones are common to everyone.
- bounded context
- A boundary inside which one model and its language are consistent; the same word may mean something else outside it.
- context map
- A drawing of bounded contexts and the relationship on each connection between them, such as customer/supplier or conformist.
- anti-corruption layer
- A translation layer that stops an upstream or legacy model from leaking into your own model.
- EventStorming
- A workshop where experts and developers place domain events on a timeline to discover processes, hot spots and context boundaries.
- Conway's law
- Organisations build systems that mirror their communication structure, so team boundaries and context boundaries should line up.