Learning Domain-Driven Design: Study Notes
Learning Domain-Driven Design: Study Notes
- Book: Learning Domain-Driven Design by Vlad Khononov
- Publisher: O’Reilly Media
- These notes: original summaries written in our own words. Read them alongside the book, not instead of it.
Domain-driven design (DDD) has two halves. Strategic design works out what to build and why: the business, its parts, the shared language and the boundaries between models. Tactical design works out how to build each part. These notes cover both halves.
Start reading
- Part I: Strategic Design
- Part II: Tactical Design
- Part III: Applying DDD in Practice
- Table of Contents
- Glossary
title: “Learning Domain-Driven Design: Study Notes” linkTitle: DDD Notes description: “Independent study notes on Learning Domain-Driven Design by Vlad Khononov.” type: book book_kind: book outputs: [HTML, print, markdown] search_exclude: true cascade: type: book breadcrumbs: false breadcrumbs: false
- Book: Learning Domain-Driven Design by Vlad Khononov
- Publisher: O’Reilly Media
- These notes: original summaries written in our own words. Read them alongside the book, not instead of it.
Domain-driven design (DDD) has two halves. Strategic design works out what to build and why: the business, its parts, the shared language and the boundaries between models. Tactical design works out how to build each part. These notes cover both halves.
Start reading
Table of Contents
Part I: Strategic Design
1. Analyzing Business Domains
- Business domains and subdomains
- Types of subdomains
- Identifying subdomain boundaries
- Worked examples
- Domain experts
- Check yourself
2. Discovering Domain Knowledge
- Why knowledge gets lost
- Ubiquitous language
- Models
- Keeping the language alive
- Common challenges
- Check yourself
3. Managing Domain Complexity
- When models disagree
- Bounded contexts
- Choosing the size
- Subdomains versus bounded contexts
- Physical and ownership boundaries
- Everyday examples
- Check yourself
4. Integrating Bounded Contexts
Part II: Tactical Design
5. Implementing Simple Business Logic
6. Tackling Complex Business Logic
- Domain model
- Value objects
- Entities and aggregates
- Domain events
- Domain services
- Why this tames complexity
- Check yourself
7. Modeling the Dimension of Time
8. Architectural Patterns
9. Communication Patterns
Part III: Applying DDD in Practice
10. Design Heuristics
- What a heuristic is
- Sizing bounded contexts
- Picking a business logic pattern
- Picking an architecture
- Picking a testing strategy
- The whole decision tree
- Check yourself
11. Evolving Design Decisions
- When subdomains change type
- Migrating between patterns
- Organizational change
- Domain knowledge
- Growth
- Check yourself
12. EventStorming
Glossary
I Strategic Design
Before talking about a solution, the team has to agree on the problem. Part I is about building that agreement.
- Chapter 1 maps the business: its domain, its subdomains and which of them really matter.
- Chapter 2 shows how engineers learn the business from domain experts through a shared language.
- Chapter 3 deals with conflicting models by giving each one an explicit boundary.
- Chapter 4 covers how those bounded parts connect, and how team relationships shape the integration.
Later, Part II turns to tactical design: how to build what’s inside each boundary.
1. Analyzing Business Domains
2. Discovering Domain Knowledge
3. Managing Domain Complexity
- When models disagree
- Bounded contexts
- Subdomains versus bounded contexts
- Physical and ownership boundaries
4. Integrating Bounded Contexts
1 Analyzing Business Domains
In one sentence: you can’t design good software for a business you don’t understand, so start by mapping what the company does and where it actually competes.
It’s tempting to treat this chapter as “business stuff, not my job”. It isn’t. The software is the answer to a business problem. If you misread the problem, even clean code is aimed at the wrong target.
Business domains and subdomains
A business domain is the company’s main line of work, the thing customers pay it for. A delivery company’s domain is moving parcels. A coffee chain’s domain is selling coffee. Large companies often work in several domains at once (think of a retailer that also sells cloud hosting), and a company’s domains can shift completely over its lifetime.
A subdomain is one smaller piece of activity that the business needs in order to operate. Selling coffee also means picking store locations, hiring and scheduling staff, buying beans and keeping the books. No single subdomain makes the company successful, but take one away and the whole thing wobbles.
Types of subdomains
Not every subdomain is worth the same to the business. DDD puts them in three groups.
Core subdomains
What the company does differently and better than its competitors. This is where the competitive advantage comes from: a smarter pricing engine, a better matching algorithm, a cheaper way to run operations.
- They are complex. If they were easy to build, competitors would copy them quickly.
- They are volatile. The company keeps experimenting and improving them to stay ahead.
- They are not always technical. For a handmade-furniture brand, the core is the furniture design. The online store that sells it is not.
Naming note: some people say core domain. These notes stick with core subdomain, because it is a subdomain and subdomains can change type over time.
Generic subdomains
Activities that every company does the same way: sign-in and permissions, encryption, payroll, accounting. They can be hard to build, but they are already solved, and doing them “your own way” gains you nothing. Buy a product or use an open-source one.
Supporting subdomains
Things the business needs but doesn’t compete on, and that are simple. They’re usually data-entry screens, basic CRUD or simple ETL jobs. Nothing ready-made fits them exactly, so you build them yourself, but cheaply.
Side-by-side comparison
| Core | Generic | Supporting | |
|---|---|---|---|
| Competitive edge | Yes | No | No |
| Business-logic complexity | High | High | Low |
| How often it changes | Often | Rarely (patches, upgrades) | Rarely |
| How to get it | Build in-house with your best people | Buy or adopt | Build simply, or outsource |
| Nature of the problem | Interesting | Solved | Obvious |
Rules of thumb for telling them apart
- Core or supporting? Could the capability be sold as a separate business? If yes, it’s probably core.
- Supporting or generic? Is it cheaper to write a quick version yourself than to integrate a product? If yes, it’s supporting.
- Look at the logic you’ll have to write. If it’s mostly forms and tables, it’s supporting. If it’s full of rules, algorithms and invariants, it’s likely core.
Why it matters for design: each type gets a different strategy. Put your strongest engineers and best practices on core subdomains. Don’t spend effort reinventing generic ones. Keep supporting ones simple, or outsource them, which also makes them good projects for growing junior engineers.
Identifying subdomain boundaries
Nobody hands you the list of subdomains. Executives rarely think in these terms, so you have to work it out.
- Start with the org chart. Departments such as warehouse, support or finance are a first rough cut.
- Distill. Break each rough area into its parts. A support department might turn out to be a ticketing tool (generic), a phone system (generic), shift planning (supporting) and a clever way of routing tickets to the best-suited agent (core). That last item would stay hidden if you stopped at “support”.
- Know when to stop. A subdomain is roughly a group of closely related use cases that share the same actors and the same data. Once you reach that level, stop.
- Spend the effort where it pays. Distill core subdomains carefully. For generic and supporting ones, stop once splitting further doesn’t change any decision.
- Leave out what isn’t software. Some business strengths, like a designer’s taste, have nothing to do with the system. Note them and move on.
Worked examples
A concert-ticket app. It recommends nearby shows based on users’ music and social activity, and it protects their privacy.
- Core: the recommendation engine, data anonymization and the app experience.
- Generic: encryption, accounting, payment clearing and authentication.
- Supporting: connectors to streaming and social platforms, and a “shows I’ve been to” log.
- Decisions: build the core in-house with care, buy the generic pieces, and outsource the supporting ones.
An on-demand bus service. Buses change their routes in real time to pick up riders.
- Core: the routing algorithm (a hard optimization problem tuned to business goals such as faster pickups), ride-data analysis, the rider and driver apps, and fleet health.
- Generic: live traffic feeds, accounting, billing and authorization.
- Supporting: managing promo codes and discounts.
Domain experts
Domain experts are the people who really know how the business works, the source of the knowledge we turn into software. They are not the analysts or engineers who translate it. In practice they’re the people who set the requirements or the people who use the system day to day. Some know the whole business; others know one subdomain deeply.
Check yourself
- Which subdomain types give no competitive advantage?
- Where would you expect competitors to use the exact same solution?
- Which type changes most often, and why?
- Pick a product you use. Name one core, one generic and one supporting subdomain.
Answers
- Generic and supporting.
- Generic.
- Core, because the company keeps refining it to stay ahead.
- Your call. Check it against the rules of thumb above.
2 Discovering Domain Knowledge
In one sentence: what ships to production is the team’s understanding of the business, so the most important engineering skill is learning that business accurately.
Chapter 1 looked across the business. This chapter looks inside a single subdomain: how its rules actually work, and how engineers can learn them without distorting them.
Business problems
Here a “problem” isn’t a puzzle you solve once. It’s an ongoing need: streamlining a workflow, cutting manual work, managing resources, supporting decisions. Problems exist at the level of the whole company and inside each subdomain.
Why knowledge gets lost
On a typical project, business knowledge passes through a chain of hand-offs:
expert → analyst → analysis model → requirements → design doc → code
Every hand-off is a translation, and every translation loses detail, much like whispering a message down a line of people. The documents in the middle also go out of date quickly. You end up with the wrong solution, or a good solution to the wrong problem.
Ubiquitous language
DDD’s answer is simple: stop translating and share one language. Experts, engineers, product people, designers and testers all describe the business with the same words, and the experts must feel comfortable with those words because the language reflects their way of thinking.
What makes a good ubiquitous language
- Business words only. Say “an order can ship once every item is reserved”, not “an order row needs matching rows in the reservations table”. Experts can check the first sentence. They can’t check the second.
- One meaning per term. If “account” sometimes means a customer and sometimes a ledger entry, split it into two terms.
- No hidden synonyms. Words that look interchangeable (“member”, “guest”, “user”) often mean different roles with different behavior. Keep them separate and precise.
Models
A model is a simplified picture built for a specific purpose. It deliberately leaves things out. Maps are the classic example: a metro map, a hiking map and a flight chart all describe the same planet, but each shows only what its user needs.
- A good model has just enough detail for its job, nothing more and nothing missing.
- Abstraction isn’t about being vague. It’s about being exact at the level that matters.
- When you build a ubiquitous language, you’re really building a model of how the experts think: the entities, their behavior, cause and effect, and the rules that must always hold.
- It doesn’t have to cover the whole business, only what the system needs.
The more complex the domain, the more a small misunderstanding costs. The only reliable way to check your understanding is to talk it through with the experts in their own language.
Keeping the language alive
- Use it everywhere: in conversations, tickets, docs, tests and code (class and method names).
- Expect it to change. As the team learns, the language will sharpen. Update it, and update the code to match.
- Supporting tools:
- A shared glossary (wiki) that anyone can edit. It’s great for nouns.
- Behavior-style tests (for example Gherkin
Given / When / Then). They capture rules and flows, which glossaries handle badly, and experts can read them, though don’t expect experts to write them. - Static analysis can flag code that drifts from agreed terms.
- Tools only help. People actually speaking the language is what counts.
Common challenges
- Tacit knowledge. The important rules often live only in experts’ heads. Ask lots of questions.
- Co-discovery. Your questions often expose gaps and unhandled edge cases the experts hadn’t thought about, especially in core subdomains. You end up shaping the model with them.
- Legacy vocabulary. Existing teams may talk in table names and system jargon. Change it patiently, starting where you have control: your code and docs.
- Non-English organizations. Using English nouns for entities at least keeps code and conversation aligned.
Check yourself
- What is a ubiquitous language for?
- Who contributes to it?
- Where should it be used?
- Two departments use “policy” for unrelated things. What do you do? (Chapter 3 gives the full answer.)
Answers
- To give business and technical people one shared, precise vocabulary.
- Everyone on the project.
- Everywhere: in talk, docs and code.
- Each meaning gets its own explicit context, which is a bounded context.
3 Managing Domain Complexity
In one sentence: when different parts of the business mean different things by the same word, don’t force one model. Give each meaning its own explicit boundary.
When models disagree
Picture a company where marketing and sales both talk about “leads”.
- To marketing, a lead is a moment: someone filled in a form and showed interest.
- To sales, a lead is a journey: a long process with stages, calls, follow-ups and an outcome.
People cope with this easily because context tells them which meaning is intended. Code doesn’t. The usual fixes fail:
- One giant shared model (the wall-sized ER diagram) tries to serve everyone and serves no one well. It is too heavy for marketing and too thin for sales.
- Prefixing names (“marketing lead” and “sales lead”) adds mental load, invites mistakes and doesn’t match how anyone actually talks.
Bounded contexts
DDD’s move: split the language. Each smaller language applies inside an explicit boundary, its bounded context. “Lead” can exist in both the Marketing context and the Sales context, as long as it has exactly one meaning inside each.
- A model needs a boundary. Without one, it keeps growing until it tries to copy reality.
- A ubiquitous language is only “ubiquitous” inside its bounded context. It is not company-wide.
- Conflicting terms are normal in any business of real size. Bounded contexts make those contexts explicit instead of hidden.
Choosing the size
- Language conflicts set the maximum size of a context. You can always make it smaller.
- Small isn’t automatically good. Large contexts are hard to keep consistent, and many small contexts cost more to integrate. Aim for useful.
- Reasons to split further include new teams, parts that need different release cycles, and parts that must scale on their own.
- Don’t cut through a cohesive group of use cases that work on the same data. Every change would then hit both sides and force them to deploy together.
Subdomains versus bounded contexts
| Subdomains | Bounded contexts | |
|---|---|---|
| Where they come from | Discovered, because the business strategy defines them | Designed, because you choose them |
| Question answered | What does the business do? | How do we divide the models and the software? |
Possible arrangements include one context for a whole small system, contexts split along language conflicts, or one context per subdomain. A one-to-one match is fine, but it isn’t required, and sometimes two different models of the same subdomain are useful at once, the same way you’d carry two kinds of map.
Physical and ownership boundaries
- Physical: each bounded context is its own service or project. It is built, versioned and deployed independently and can use a different tech stack. If a context holds several subdomains, those are logical boundaries inside it, such as modules, packages or namespaces.
- Ownership: a bounded context belongs to exactly one team. One team can own several contexts, but two teams never share one. That stops teams making silent assumptions about each other’s models and pushes them to agree explicit contracts.
Everyday examples
- Words in different fields. “Port”, “monitor” and “driver” mean different things to a network engineer, a hardware engineer and a race fan. Each field is its own semantic area.
- Is a tomato a fruit? A botanist says yes (it carries seeds). A cook says it’s a vegetable (savory, cooked). Tax law in one country once officially called it a vegetable too. Each answer is right in its own context.
- Competing theories. Classical and relativistic physics contradict each other, yet each is the right tool in its own range.
- Will the fridge fit? A sheet of cardboard cut to the fridge’s footprint checks the doorway width, and a tape measure checks the height. Two crude, single-purpose models beat one detailed replica, which would be over-engineering. (A phone AR scanning app would be the “buy a generic solution” option.)
Check yourself
- Which are discovered and which are designed: subdomains or bounded contexts?
- A bounded context is a boundary of what?
- Is a smaller bounded context always better?
- Can two teams share a bounded context? Can one team own two?
Answers
- Subdomains are discovered; bounded contexts are designed.
- A model, a lifecycle and ownership.
- No. It depends on the project and its constraints.
- No, and yes.
4 Integrating Bounded Contexts
In one sentence: bounded contexts evolve on their own but still have to talk to each other, and how the teams relate decides how the systems should integrate.
The touchpoints between contexts are contracts. Each side speaks its own language, so you have to decide whose language the contract uses and who adapts when it changes. DDD groups the answers by the kind of team relationship.
Cooperation
The teams communicate well, or their success depends on each other.
Partnership
Integration is worked out as it comes up and in both directions. One team changes an API, tells the other, and the other adapts without friction. Nobody dictates. Problems get fixed together.
- Needs: trust, frequent syncing and continuous integration of both sides’ changes.
- Weak spot: teams spread across locations or time zones, where syncing is hard.
Shared kernel
A small piece of model is shared by several contexts, for example a custom permissions model that all of them must apply identically. A change to it affects everyone at once.
- Keep it tiny, ideally just the contracts and data structures that cross the boundary.
- Implement it as one source of truth: the same files in a monorepo, or one shared library. Every change triggers integration tests in all dependent contexts.
- Use it only when duplicating would cost more than coordinating. That’s most likely for fast-changing core logic.
- It bends the one-team-per-context rule, so it needs a real justification. Typical reasons: teams that can’t work as partners (because of distance or politics), a temporary step while breaking up a legacy system, or one team that wants a clear, explicit line between its own contexts.
Customer–supplier
One context (the upstream supplier) provides a service, and another (the downstream customer) uses it. Each can succeed without the other, so one side usually has more power over the contract.
Conformist
The upstream side holds the power and offers a take-it-or-leave-it contract. The downstream side adopts the upstream model as it is. That’s reasonable when the upstream model is an industry standard or simply good enough.
Anticorruption layer (ACL)
The upstream side still holds the power, but the downstream side won’t let the foreign model leak in. It adds a translation layer that turns the upstream model into its own. Use it when:
- the downstream context is core and needs a clean model of its own,
- the upstream model is awkward or messy, which is common with legacy systems (adopt a mess and you become one), or
- the upstream contract changes often, so only the translator has to change.
Open-host service (OHS)
The power sits with the consumers, and the supplier wants to serve them well. It separates its internal model from a public, consumer-friendly protocol called the published language.
- The internal model can change freely as long as it still maps to the published language.
- Several versions of the published language can run side by side, so consumers migrate when they’re ready.
- It’s the mirror image of an ACL: here the supplier does the translating.
Separate ways
Sometimes the cheapest option is not to integrate at all and to let each context build its own version.
- Collaboration is too costly, because of organization size, politics or poor communication.
- The capability is generic and easy to plug in, like a logging library. Each context just uses it directly.
- The models are too different to conform to, and translating would cost more than duplicating.
Avoid separate ways for core subdomains. Building the most valuable capability twice contradicts the reason it’s core.
Context map
A context map is a diagram of all bounded contexts and the patterns between them. It shows:
- High-level design: the components and the models they own.
- Team dynamics: who works closely together and who keeps their distance (ACL, separate ways).
- Organizational smells: if every consumer of one team builds an ACL, or all the separate-ways links cluster around one team, ask why.
Maintenance: start one on day one and keep it up to date as a shared job, with each team updating its own links. It can live as code (for example with Context Mapper). Limit: when a context spans several subdomains, one pair of contexts may use more than one pattern, which makes the map harder to read.
Pattern cheat sheet
| Pattern | Power sits with | Who adapts or translates | Good fit when |
|---|---|---|---|
| Partnership | Shared | Both, as needed | Teams sync often and trust each other |
| Shared kernel | Shared | Nobody (same code) | Duplicating costs more than coordinating |
| Conformist | Upstream | Downstream adopts as is | The upstream model is standard or good enough |
| Anticorruption layer | Upstream | Downstream translates | Protecting a core model or a messy upstream |
| Open-host service | Downstream | Upstream translates | Many consumers, versioned public API |
| Separate ways | n/a | n/a | Duplicating is cheaper (never for core) |
Check yourself
- Which pattern should never be used for a core subdomain?
- Which kind of downstream subdomain most needs an ACL?
- Which kind of upstream subdomain is likely to offer an open-host service?
- Which pattern, in a sense, breaks ownership boundaries?
Answers
- Separate ways.
- Core.
- Any type can. What matters is wanting to protect consumers.
- Shared kernel.
II Tactical Design
Part I decided what to build and where the boundaries go. Part II is about how to build what’s inside those boundaries: how to code the business logic, how to arrange a component’s internals, and how components talk to each other reliably.
- Chapter 5 covers two lightweight ways to code simple logic: transaction script and active record.
- Chapter 6 brings in the domain model and its building blocks (value objects, aggregates, domain events and domain services) for complex logic.
- Chapter 7 adds time to the model: store every change as an event and derive state from the history.
- Chapter 8 zooms out to how a component is organized: layers, ports & adapters, and CQRS.
- Chapter 9 covers communication between components: translating models, publishing events reliably, and running processes that span several transactions.
Later, Part III puts the tools to work: design heuristics, evolving decisions and EventStorming.
Thread running through Part II: match the tool to the complexity. Simple subdomains get simple patterns, and only the complex core gets the heavier machinery.
5. Implementing Simple Business Logic
6. Tackling Complex Business Logic
7. Modeling the Dimension of Time
8. Architectural Patterns
9. Communication Patterns
5 Implementing Simple Business Logic
In one sentence: when the logic is simple, use a simple pattern, but get the transactional behavior exactly right, because that’s where “simple” code usually breaks.
Business logic is the reason the software exists. A beautiful UI on top of logic that doesn’t serve the business is just an expensive demo. This chapter covers the two patterns for the easy end of the spectrum, which fits supporting subdomains.
Transaction script
Idea: organize the logic as a set of procedures, one per operation the system exposes (“register member”, “cancel booking”, “export invoices”). Each procedure is a straightforward script. It can use a thin data-access helper or talk to the database directly.
The one non-negotiable rule: each script must behave like a transaction. It either fully succeeds or leaves no trace. If it fails halfway, the system must not be left in a half-updated state, so roll back or run a compensating action.
Where it goes wrong
It looks trivial, yet broken transactional behavior is behind many real data-corruption bugs. Three classic traps:
- No transaction around several writes. Two updates run separately, and a crash between them leaves only the first one applied. Fix: wrap them in one database transaction.
- Database plus message bus. You update a row, then publish a message. If the process dies in between, the database changed but nobody was told. A distributed transaction across both is complex and rarely worth it. Fix: use patterns from later chapters (the outbox in Chapter 9, or CQRS projections in Chapter 8).
- The hidden distributed transaction: the caller. Even a single-row update such as
points = points + 10is risky. If the update succeeds but the reply to the caller is lost (network blip, crash), the caller retries and the points are added twice. Fixes:- Make the operation idempotent: the caller sends the target value (
points = 120), so repeating it changes nothing. - Or use optimistic concurrency: only apply the change if the value is still what the
caller saw (
... WHERE points = 110).
- Make the operation idempotent: the caller sends the target value (
When to use it
- Simple, procedural logic such as ETL jobs (extract, transform, load).
- Supporting subdomains, and adapters for integrating generic subdomains or building an anticorruption layer.
- Never for core subdomains. As logic grows, rules get copied across scripts, the copies drift apart, and you end up with a big ball of mud.
Its strength and its weakness are the same thing: very little abstraction. And every other business-logic pattern still has a transaction script inside it somewhere.
Active record
Idea: the logic is still simple, but the data structures aren’t: nested objects, one-to-many and many-to-many relations. Mapping those by hand in every script means a lot of repeated code. So each structure becomes an active record, an object that holds the data and knows how to load and save itself (CRUD), usually through an ORM.
- The procedures are still transaction scripts. They just work with active records instead of raw tables.
- Active records may contain light logic such as validating fields, but their data is usually open (public getters and setters), so behavior and data stay separate. Code outside the object changes its state.
- Fits supporting subdomains, integrations and model transformations.
- It’s sometimes called an “anemic domain model” antipattern. A fairer view is that it’s a tool: fine for simple logic, harmful for complex logic. Using a heavier pattern for simple logic causes harm too, through needless complexity.
(This is the design pattern, not any specific framework that took the name.)
Being pragmatic
Data integrity matters, but not every corner needs gold plating. At very large scale, ask the business whether losing or duplicating a tiny fraction of records (say, telemetry pings) actually hurts. Sometimes cutting corners is the right call, as long as you judged the risk deliberately.
Check yourself
- Can transaction script or active record implement a core subdomain?
- Which of them fits a supporting subdomain?
- A function picks the least-busy courier, increments their job counter, saves a new delivery assigned to them, then sends a push notification, all with no transaction. Name three ways the data can end up wrong.
Answers
- No.
- Both.
- The counter goes up but no delivery is saved; the delivery is saved but the notification never goes out; a retry after a lost reply bumps the counter twice. There are more, such as two requests racing for the same courier.
6 Tackling Complex Business Logic
In one sentence: for complex logic, put data and behavior together in objects that speak the ubiquitous language and protect their own rules, so nothing outside can break them.
Where this comes from
The domain model pattern was first named in Fowler’s Patterns of Enterprise Application Architecture. Eric Evans’s Domain-Driven Design then supplied its building blocks (aggregates, value objects and so on), which are often called “tactical DDD”. These notes follow the book in calling the pattern domain model and treating the rest as its building blocks. You can do DDD without them.
Domain model
Use it when the logic is about state transitions, business rules and invariants (rules that must always hold), not CRUD screens. Think of a co-working space booking flow:
- Members book desks or rooms for time slots. Rooms have capacity limits.
- Bookings unconfirmed 15 minutes before the start are released.
- Premium members can book further ahead and get priority on waitlists.
- No-shows three times in a month lose booking rights for a week.
Rules like these depend on each other. Spread them across active records and scripts and they’ll be duplicated and eventually contradict each other.
Two design principles:
- No accidental complexity. Domain objects are plain objects with no database calls, framework base classes or infrastructure inside them.
- Speak the language. Because the objects are free of technology, their names and methods can follow the ubiquitous language directly.
Value objects
An object defined entirely by its values. It has no ID. Two Money(25, "EUR") instances are
the same money, and changing any field gives you a different value.
Why bother? Using raw strings and ints for business concepts (“primitive obsession”) scatters
validation and meaning everywhere. Compare email: str with email: EmailAddress. The value
object validates itself once, carries its meaning in its type, and collects related behavior in
one place.
- Immutable. Operations return new instances. That makes them side-effect free and safe to share across threads.
- Value equality. Equality must compare fields. Many languages have record or dataclass types that do this for you.
- Rich behavior, not just validation: a
Durationthat converts units, aPhoneNumberthat knows its country, aDateRangethat checks overlaps. - Use them as much as possible, especially for things that describe other objects: names, statuses, amounts, addresses. Always model money as a value object, because primitives cause rounding and precision bugs.
- Fun fact: the built-in string type in most languages is already a value object (immutable, with operations that return new strings).
Entities and aggregates
Entity
The opposite of a value object: it needs an explicit ID because two instances with identical data can still be different things. Two members both called “Priya Shah” are still two people. The ID itself is usually a value object, it shouldn’t change, and the rest of the entity’s state is expected to change over time. Entities don’t stand alone in this pattern; they live inside aggregates.
Aggregate
An entity (or a cluster of entities and value objects) whose job is to keep its data consistent.
- Consistency boundary. Only the aggregate’s own methods may change its state. Everyone else
can only read it. Every change goes through a command on its public interface, as a method
(
booking.confirm()) or a command object (booking.execute(Confirm(...))). The aggregate validates the input and enforces every relevant rule. - Thin application layer. Outside code just does load → run command → save → return result. All the rules live in the aggregate, in one place.
- Concurrency control is mandatory. Keep a
versionfield and only save if the stored version still matches the one you loaded. Otherwise someone else changed it first, so reload and retry.
- Transaction boundary. An aggregate is saved atomically, and one aggregate instance per transaction. Needing to change two aggregates in one transaction means the boundaries are wrong (or it’s a job for Chapter 9’s patterns).
- A hierarchy of entities. If several objects must change together or depend on each other’s
rules, they belong in the same aggregate: a
Bookingwith itsCheckInrecords, for example. That’s where the name comes from. - Keep it small. Include only what the rules need to be strongly consistent. Reference
everything else by ID (
member_id,room_id). Test: if this data were slightly out of date, could the aggregate make a wrong decision? If yes, it goes inside. If no, it stays out. - Aggregate root. One entity is the entry point. Inner entities are changed only through the
root (
booking.record_check_in(...), nevercheck_in.save()directly).
Domain events
A message saying something significant happened in the business. It’s named in the past
tense (BookingConfirmed, SlotReleased, MemberSuspended) and carries the data subscribers need.
Events are part of an aggregate’s public interface. The aggregate records them, and other aggregates, processes or systems subscribe and react. Chapter 9 shows how to publish them reliably. Name everything (the aggregate, its fields, commands and events) in the ubiquitous language.
Domain services
Some logic doesn’t belong to any single aggregate or value object, usually a calculation that needs data from several sources. Put it in a domain service: a stateless object that hosts business logic.
Example: computing a booking’s confirmation deadline might need the room’s policy, the member’s
tier and the building’s opening hours. A ConfirmationDeadlinePolicy service reads all three and
returns the deadline.
- It’s good for reading several aggregates. It is not a loophole for changing several in one transaction; that rule still holds.
- “Service” here has nothing to do with microservices or SOA. It’s just a home for logic.
Why this tames complexity
One useful way to measure complexity is degrees of freedom: how many independent values you need to describe the system’s state. An object with five freely settable fields has five. If some fields are derived from others by enforced rules, it has fewer, which makes it easier to predict and control. Value objects and aggregates do exactly that: they lock invariants inside and reduce the degrees of freedom. Since this pattern is for complex logic, it’s mostly used in core subdomains.
Check yourself
- Are value objects data-only, behavior-only, immutable, or mutable?
- What’s the guiding principle for an aggregate’s size?
- Why commit only one aggregate per transaction?
- Main difference between an active record and an aggregate?
Answers
- Immutable, and they carry both data and behavior.
- As small as possible while still keeping the data that must be strongly consistent together.
- To force correct consistency and transaction boundaries.
- An aggregate holds all of its logic. An active record’s logic can live outside it.
7 Modeling the Dimension of Time
In one sentence: instead of storing only where things are now, store everything that happened and work out the current state (and any other view) from that history.
The event-sourced domain model uses the same building blocks as Chapter 6: value objects, aggregates and domain events. The only difference is how aggregate state is persisted.
Event sourcing
What a state table hides
Picture a shipments table with id, status, address, eta and updated_at. You can tell
each parcel’s current status, but you can’t answer:
- How many delivery attempts happened before it was delivered?
- How often did customers change the address after dispatch?
- Which depots cause most of the delays?
The table holds the latest state but has lost the story. Those missing answers are often exactly what the business needs to improve a core process.
Store the story
Event sourcing adds time to the data model. Every change to an aggregate is saved as an event:
Projection means rebuilding a state by applying events in order:
- Time travel: apply only the first n events to see the state at any point in the past.
- Many views from one history: a search projection that keeps every address ever used, an analytics projection that counts attempts per depot, and new projections added later from the same events. (Persisting these views is what CQRS in Chapter 8 is for.)
Source of truth and event store
- The events are the source of truth, the only strongly consistent data.
- They live in an event store: append-only, with no updates or deletes (apart from rare cases such as migrations).
- At minimum it needs two operations: fetch all events for an aggregate ID, and append new events with an expected version. If the stored version moved on, it raises a concurrency error, which gives you optimistic concurrency.
- It isn’t a new idea: an accounting ledger is an append-only log, and a balance is a projection of it.
Event-sourced domain model
A regular domain model stores state and emits some events. An event-sourced one expresses every state change as an event. Each operation follows the same four steps:
- Load the aggregate’s events.
- Rehydrate by projecting them into an in-memory state used for decisions.
- Run the command. The logic doesn’t set fields directly; it creates new events and applies them to its own state.
- Append the new events to the store (with the expected version).
Naming note: event sourcing can be used without the domain model, so “event-sourced domain model” spells out that you’re using both together.
Trade-offs
Benefits
- Time travel and retroactive debugging: reproduce the exact state at the moment a bug happened.
- Deep insight: new projections can answer questions nobody had thought of yet, which is valuable for optimizing core subdomains.
- Audit log for free, and a strongly consistent one. It’s great where regulation or money flows demand traceability.
- Smarter concurrency: on a conflict you can inspect which events were added in the meantime and decide whether they actually clash with your change.
Costs
- Learning curve: a very different way of thinking about data, so the team needs training.
- Evolving events is hard: events are immutable, so changing their shape is a discipline of its own (event versioning).
- More moving parts in the architecture (see CQRS).
Use it when the business really benefits, not by default (Chapter 10 gives heuristics).
FAQ
- Won’t replaying events get slow? Measure it. Most aggregates live for well under a hundred events, and replay usually only hurts at around ten thousand or more. If it does, add snapshots: cache a projected state and replay only the events after it. That’s an optimization that needs a justification. First check whether the aggregate is simply too big.
- Does it scale? Yes. Operations always target one aggregate, so you can shard the store by aggregate ID.
- What about deleting personal data (for example GDPR)? Use the forgettable payload pattern (also called crypto-shredding): encrypt sensitive fields with a key per aggregate held in a separate key store, and delete the key to make the data unreadable.
- Why not just write logs to a file? That’s two separate writes (database and file) without a shared transaction, so they drift apart.
- Why not a log table in the same transaction? Someone will eventually forget to write the log row, and since the state stays the source of truth, the log format decays.
- Why not a database trigger that copies rows to a history table? It records what changed but not why, and that business intent is what makes new projections possible.
Check yourself
- How do domain events relate to value objects?
- How many projections can you build from one aggregate’s events?
- True or false: only event-sourced aggregates emit domain events.
- In a support-ticket product, which fits event sourcing best: the ticket lifecycle, the admin screens, or staff rotas?
Answers
- Events use value objects to describe what happened.
- As many as you like, including new ones added later.
- False. Both kinds emit them, but only event-sourced ones use them as the source of truth (and record every change).
- The ticket lifecycle, because it’s complex, core and benefits from history.
8 Architectural Patterns
In one sentence: an architectural pattern decides where business logic sits relative to UI, storage and integrations, and the right choice depends on which business-logic pattern you use.
Why organize at all
A codebase also has to take input, show output, store data and call other systems. Without clear boundaries, business rules leak into controllers, SQL and UI code, or get copied between them. Then nobody knows what a change will break. Architectural patterns set the rules for what each part may know and depend on.
Layered architecture
Horizontal layers, each depending only on the layer directly below it:
| Layer | Responsibility today |
|---|---|
| Presentation | Every way into or out of the program: web UI, CLI, public API, message subscriptions, outgoing event topics. |
| Business logic | Rules and decisions. This is where transaction scripts, active records or a domain model live. |
| Data access | Every persistence and outside dependency: several databases, object storage, an internal message bus, third-party APIs and managed cloud services. |
Service layer variant
An extra service (application) layer between presentation and business logic. It exposes the
system’s operations (register_member, cancel_booking, …) and handles orchestration such as
transactions and error mapping, so controllers stay thin.
- Benefits: one service layer can serve both a UI and an API without duplication, related operations are grouped in one place, and it’s easier to test.
- Not always needed: transaction scripts already are a service layer. Active record, on the other hand, needs one to orchestrate it.
- It’s a logical boundary, not a separately deployed service.
Other names: presentation is the UI layer; service is the application layer; business logic is the domain (or model) layer; data access is the infrastructure layer.
When to use it: good with transaction script or active record. It’s awkward with a domain model, because the logic layer depends on data access, while domain objects should know nothing about infrastructure.
Layers versus tiers: a layer is logical, and all layers ship together as one unit. A tier is physical and deployed independently (browser, reverse proxy, app server, database server).
Ports & adapters
Start from layers and make two changes:
- Combine presentation and data access into one infrastructure layer, since both are just technology at the edges.
- Invert the dependency (the Dependency Inversion Principle): the business logic depends on nothing, and infrastructure depends on it. Add an application layer as the façade for the system’s operations.
How it plugs together: the core defines ports (interfaces it needs, such as “publish an event” or “load a booking”), and infrastructure provides adapters (concrete implementations for a specific database or queue), connected through dependency injection or at startup.
- Also known as: hexagonal, onion and clean architecture. The same idea with different labels (application = use-case layer; business logic = domain or core layer).
- When to use it: the natural home for a domain model or an event-sourced domain model.
CQRS
Command-Query Responsibility Segregation. It’s organized like ports & adapters, but the data lives in more than one persistent model.
Why more than one model?
- One model rarely suits every need. Transactional work and analytics want different shapes.
- Polyglot persistence: no database is perfect, so you might use a document store for writes, a search engine for queries and a column store for reports.
- Event sourcing can only query one aggregate’s events at a time. CQRS turns projections into queryable databases. CQRS started there, but it’s useful with any business-logic pattern.
Two kinds of model
- Command execution model: the single model used to change state and enforce rules. It’s the only strongly consistent source of truth, with optimistic concurrency.
- Read models (projections): as many as you need, precomputed for display or for other systems. They’re read-only, stored anywhere (a database, files, a cache), and can be wiped and rebuilt from scratch, so you can add new ones later.
Keeping projections up to date
- Synchronous (catch-up subscription): a projection engine asks the write store for “everything changed after checkpoint N”, updates the read models and saves the new checkpoint. The checkpoint must be strictly increasing and consistent (a database row-version, or your own counter), or records get skipped. Rebuilding is easy: reset the checkpoint to 0.
- Asynchronous: the write side publishes changes to a message bus and projectors subscribe. It scales well, but out-of-order or duplicate messages can corrupt views, and rebuilding is harder.
- Advice: always have the synchronous path, and add asynchronous on top if needed.
A common myth
“Commands must never return data.” Wrong. A command should report success or failure and why, and it may return data the caller needs, as long as that data comes from the strongly consistent command model, not from a projection that may not have caught up yet.
When to use it
When the same data must live in several models or stores, and it’s required for an event-sourced domain model. It fits DDD’s habit of using the best model for each job.
Scope: per module, not per system
None of these patterns has to cover a whole system or even a whole bounded context. A context can contain several subdomains, each needing different logic and architecture. Add vertical slices (modules per subdomain) on top of the horizontal layers, and choose the right pattern for each slice. That keeps a monolith modular, and those slices can later be split into separate bounded contexts.
| Business logic pattern | Natural architecture |
|---|---|
| Transaction script / active record | Layered |
| Domain model | Ports & adapters |
| Event-sourced domain model | CQRS |
Check yourself
- Which architectures can host active records?
- Which ones keep business logic free of infrastructure?
- In ports & adapters, where does the code for a managed cloud queue go?
- True or false: a CQRS command can return data.
- CQRS keeps several models in one bounded context. Does that break the “one model per context” idea?
Answers
- Layered, and also ports & adapters and CQRS. All three can work.
- Ports & adapters and CQRS.
- The infrastructure layer, as an adapter.
- True, as long as it comes from the strongly consistent model.
- No. The read models are projections of the one command model, not competing models.
9 Communication Patterns
In one sentence: to make separate components work together safely, translate between their models, publish events reliably, and coordinate multi-step processes without pretending they’re one transaction.
Model translation
Recap from Chapter 4: partners and shared kernels coordinate directly. In customer–supplier relationships where the downstream side won’t conform, someone has to translate: the downstream side with an anticorruption layer (ACL), or the upstream side with an open-host service (OHS) and its published language. The techniques are the same for both.
Stateless translation (on the fly)
The translating side acts as a proxy: it intercepts requests or messages and maps one model to the other.
- Synchronous:
- Put the mapping in the bounded context’s own code (OHS for incoming requests, ACL for outgoing calls).
- Or move it to an API gateway (open-source or cloud-managed). For an OHS, a gateway makes it easy to serve several API versions side by side.
- A shared ACL used by several consumers effectively becomes its own small interchange context.
- Asynchronous: a message proxy subscribes to the source, transforms each message, can
filter out noise, and forwards it on.
- Important for an OHS: don’t expose internal domain events as they are. Translate them into the published language so internals stay private. This separates private events (for internal use) from public events (for integration).
Stateful translation (needs its own storage)
- Aggregating incoming data: batching many small requests for efficiency, or combining several fine-grained events into one. A gateway can’t do this, so it needs storage, a custom component or a stream or batch platform.
- Unifying several sources:
- Backend-for-frontend: one component combines data from several services for a UI.
- An ACL in front of a complex context collects data from many upstream contexts, so the context deals with business complexity instead of integration complexity.
Outbox
Aggregates communicate through domain events, but how do you publish them safely?
Two tempting but broken approaches:
- Publish from inside the aggregate. The event goes out before the state is saved. If the save then fails, you’ve announced something that never happened, and you can’t take it back.
- Publish from the application layer after saving. Better, but if the process crashes or the bus is down between “saved” and “published”, the event is lost forever.
The outbox pattern:
- Save the aggregate’s new state and its new events in one atomic transaction.
- A relay reads the unpublished events.
- The relay publishes them to the bus.
- Then it marks them published, or deletes them.
- Relational database: a dedicated outbox table, written in the same transaction.
- Document store without multi-document transactions: embed an
outboxarray inside the aggregate’s own document. - How the relay finds events:
- Pull (polling publisher): keep querying for unpublished rows, with good indexes.
- Push (transaction log tailing): react to the database’s change feed or change streams.
- Delivery is at least once. A crash after publishing but before marking means a resend, so subscribers must handle duplicates.
Saga
The rule from Chapter 6 still applies: one aggregate per transaction. So how do you run a business process that spans several aggregates or contexts?
A saga is a long-running process: long in transactions, not necessarily in time (it can take seconds or months). It listens for events and issues commands in response. If a step fails, it issues compensating actions to put things back in order.
Example, a marketplace order:
OrderPlaced→ commandReserveStockto the warehouseStockReserved→ commandChargePaymentto billingPaymentDeclined→ compensate:ReleaseStock, thenCancelOrderSimple sagas just map events to commands and need no state.
Stateful sagas track what they’ve done so they know what to undo. You can build one as an event-sourced aggregate, and send its commands through an outbox-style relay (record a “command issued” event, and let the relay execute it), so a crash can’t lose a step.
Consistency is eventual. Only the data inside one aggregate is strongly consistent. If you keep needing sagas to keep data in step that really has to be consistent together, the aggregate boundaries are probably wrong.
Process manager
Similar machinery, but a different purpose.
| Saga | Process manager | |
|---|---|---|
| Flow | Linear: event → command matching | Branching business logic decides the next step |
| How it starts | Implicitly, when a trigger event appears | Explicitly, because the process is a thing in its own right |
| State | Optional | Always has its own ID and state |
Rule of thumb: if your “saga” is full of if/else deciding what to do next, it’s a process manager.
Example, onboarding a new employee: create accounts, then wait for the manager’s equipment choice. If the equipment isn’t in stock, order it and adjust the start date. Then book the induction session. If HR rejects the documents, pause everything and notify the recruiter. No single event “owns” this flow; the onboarding is the process.
Process managers are usually built as aggregates (state-based or event-sourced) that subscribe to the relevant events and record “command issued” events for an outbox relay to execute.
Check yourself
- Which integration patterns need translation logic: conformist, ACL, OHS?
- What is the outbox for?
- Is the outbox only useful for message buses?
- Which are true? (a) a process manager is started explicitly, a saga by an event; (b) a process manager never stores state; (c) sagas require event-sourced participants; (d) process managers suit complex workflows.
Answers
- ACL and OHS.
- To publish messages reliably.
- No. Any “do X after commit” side effect can use it, such as saga or process-manager commands.
- (a) and (d).
III Applying Domain-Driven Design in Practice
Parts I and II gave you the tools. Part III is about using them on real projects: turning the analysis into concrete design choices, keeping those choices up to date as things change, and running a workshop that gets everyone to a shared model quickly.
- Chapter 10 connects strategy to tactics with rules of thumb: which logic pattern, architecture and testing approach to use, and how wide to draw the first boundaries.
- Chapter 11 covers what to do when the business, the organization, your understanding or the system’s size changes, and how to migrate between patterns.
- Chapter 12 walks through EventStorming, a sticky-note workshop for exploring a business process and building a shared language.
Coverage note: these notes currently cover Chapters 10–12 of Part III.
10. Design Heuristics
- What a heuristic is
- Sizing bounded contexts
- Picking a business logic pattern
- Picking an architecture
- Picking a testing strategy
- The whole decision tree
11. Evolving Design Decisions
12. EventStorming
10 Design Heuristics
In one sentence: “it depends” is usually true, so this chapter spells out what it depends on, chiefly the subdomain’s type and complexity, and turns that into a decision tree.
What a heuristic is
A heuristic is a rule of thumb. It isn’t guaranteed to be right every time, but it’s good enough to make a sound decision quickly, because it focuses on the few signals that matter most and ignores the noise. Everything in this chapter is a heuristic, not a law.
Sizing bounded contexts
- Size is a poor target. Don’t aim for “small” (or “micro”) for its own sake. Let the model decide the size of the context, not the other way round.
- Changes that cut across contexts are expensive, especially when different teams own them. Frequent cross-context changes mean the boundaries are wrong, and moving physical boundaries later is costly, so bad ones tend to stay and turn into technical debt.
- Boundaries break most when the domain is uncertain or keeps changing, which describes core subdomains, especially early on.
- The heuristic: start wide for core subdomains. Put a new core subdomain in a context together with the subdomains it talks to most (core, supporting or generic). Mistakes inside one context are cheap to fix, because moving logical boundaries is far cheaper than moving physical ones. Split the context once your understanding settles.
- Generic and supporting subdomains are more predictable, so they’re less risky to separate early.
Picking a business logic pattern
Ask these questions in order:
- Does it handle money, need a reliable audit trail, or need deep analysis of its behavior? If yes, use an event-sourced domain model.
- Is the business logic complex? If yes, use a domain model.
- Are the data structures complex? If yes, use active record.
- Otherwise, use a transaction script.
What counts as “complex”? Complex logic has real rules, invariants and algorithms. Simple logic mostly validates input. Another clue is the ubiquitous language itself: does it describe CRUD operations, or processes and rules?
Use the result to check your assumptions. If what you called a core subdomain only needs a transaction script, or a “supporting” one clearly needs a full domain model, look again at how you classified it. And remember that a core subdomain’s edge isn’t always technical.
Picking an architecture
Once the logic pattern is chosen, the architecture mostly follows from it:
| Business logic | Architecture | Why |
|---|---|---|
| Event-sourced domain model | CQRS | Without projections you can only load single aggregates by ID |
| Domain model | Ports & adapters | Keeps aggregates and value objects free of persistence concerns |
| Active record | Layered + service layer | The service layer orchestrates the active records |
| Transaction script | Minimal layered (three layers) | Nothing more is needed |
Exception: CQRS is useful with any of these whenever the subdomain needs its data in several persistent models.
Picking a testing strategy
The same choices also suggest where to put most of your testing effort:
| Shape | Emphasis | Fits |
|---|---|---|
| Testing pyramid | Mostly unit tests | Domain model and event-sourced domain model, because aggregates and value objects make ideal units |
| Testing diamond | Mostly integration tests | Active record, because the logic is spread across the service and business layers |
| Reversed pyramid | Mostly end-to-end tests | Transaction script, because the logic is simple and there are few layers, so test the whole flow |
The whole decision tree
Put it all together and the subdomain’s type and complexity guide the logic pattern, which guides the architecture, which guides the testing strategy:
The tree reflects a deliberate bias: use the simplest tool that works, and reach for the heavier patterns only when you need them. Some teams are so comfortable with event sourcing that they use it everywhere, and that can work for them. Treat the tree as a starting point, adjust it to your context, or build your own. It doesn’t replace thinking.
Check yourself
For each, pick a logic pattern, an architecture and a testing approach:
- A core claims-assessment engine at an insurer, where every decision must be explainable afterwards.
- A supporting staff-holiday request screen.
- A nightly job that pulls exchange rates from a third-party API and stores them.
Answers
- Event-sourced domain model, CQRS, mostly unit tests. It’s core and needs a full history.
- Active record (or transaction script if the data is flat), layered architecture, integration-focused tests.
- Transaction script, layered architecture, end-to-end tests.
11 Evolving Design Decisions
In one sentence: businesses keep changing, so design decisions have to be revisited. Watch for four kinds of change (the domain, the organization, what you know, and growth) and adapt the design when they happen.
When subdomains change type
A subdomain’s type isn’t fixed. Some common shifts, with made-up examples:
| Shift | What it looks like |
|---|---|
| Core → generic | A food-delivery startup built its own route optimizer as a differentiator. Then a vendor starts selling a better one cheaply, so the advantage becomes a commodity anyone can buy. |
| Generic → core | The same company used an off-the-shelf stock planner, but poor forecasts keep causing waste. It decides to build its own demand forecasting, which becomes a new source of advantage. (Large tech companies have done this with their own infrastructure and then sold it as a product.) |
| Supporting → generic | An in-house supplier-contracts screen gets replaced by an open-source tool that does more (search, document scanning). |
| Supporting → core | Simple supporting logic gets steadily smarter because it increases profit or cuts costs. If it grows more complex without that payoff, it’s just accidental complexity. |
| Core → supporting | A “core” feature whose complexity no longer pays for itself gets trimmed back to the minimum. |
| Generic → supporting | Integrating the bought tool turns out to cost more than it’s worth, so the team goes back to a simple in-house version. |
What that means for strategic design
- Integration patterns. Core subdomains need protection: an ACL against messy upstream models, and an OHS so their own frequent changes don’t break consumers. If a subdomain that was handled with separate ways becomes core, duplicating it is no longer acceptable. One team should own it, with customer–supplier links to the others.
- Who builds it. A subdomain that becomes core must come in-house, close to the domain experts. A core subdomain that drops to supporting can be outsourced, freeing the strong teams for what matters.
What that means for tactical design
The main signal is pain: the current design can’t support what the business now needs. New rules keep piling up in a transaction script or active record and every change hurts. Treat that pain as a prompt to reassess both the subdomain and the patterns. Needing to change patterns is normal. You can’t predict the future, and using the heaviest patterns everywhere “just in case” would be wasteful.
Migrating between patterns
If you chose a pattern deliberately and know the alternatives, moving to the next one is manageable.
Transaction script → active record
Both are procedural, so the difference is the data. When working with the data in scripts gets messy, wrap the complex structures in active record objects and stop reaching into the database directly.
Active record → domain model
When the logic around active records gets complex, duplicated or inconsistent:
- Find value objects: structures that can be immutable. Move their related logic into them.
- Make setters private. The code won’t compile anymore, and every error shows a place where outside code changes state. Move that logic into the object as methods.
- Find consistency boundaries: which data really must be strongly consistent together? Those groups become aggregates. Keep them small and refer to other aggregates by ID.
- Choose each aggregate’s root and make the internal objects reachable only through it.
Domain model → event-sourced domain model
Once the aggregates have sound boundaries, model the events of each aggregate’s lifecycle instead of changing state directly. The hard part is existing data, which has no history. Two options:
- Reconstruct plausible past events. Generate a best-guess event stream that projects to the current state, and check it by projecting and comparing. The downside: the history is incomplete (you can’t know how many times something really happened), which undermines why you wanted event sourcing.
- Model a migration event. Start each stream with one explicit “migrated from legacy” event carrying the old state. It’s honest about the missing history, but projections must handle that event type forever.
Organizational change
Team structure changes how contexts should integrate:
- More teams. Since a bounded context has exactly one owning team, a wide context may need to split so each new team gets its own.
- Partnership → customer–supplier. Partnership needs close collaboration. If one side moves to a distant office or time zone, switch to a clearer upstream/downstream relationship.
- Customer–supplier → separate ways. If teams keep fighting over integration (because of distance or politics), at some point duplicating the functionality is cheaper. That’s only acceptable for supporting or generic subdomains.
Domain knowledge
- Domains often look simple at first, then edge cases and rules surface and can force a big remodel.
- Heuristic: when knowledge is thin or the logic keeps changing, keep contexts wide. Split them into narrower contexts (or microservices) once things settle.
- Knowledge can also be lost: documentation goes stale and people leave, until the system becomes “legacy”. Recover it on purpose. EventStorming (Chapter 12) works well for this.
Growth
Growth is healthy, but unmanaged growth turns a codebase into a big ball of mud: features get bolted on without anyone revisiting the original design decisions. The rule is to remove accidental complexity (from outdated decisions) and manage essential complexity (inherent to the business) with DDD tools. Check every kind of boundary again:
- Subdomains. As a subdomain grows, look for finer-grained subdomains inside it, using the “coherent use cases on the same data” test. This matters most for core subdomains: separate out the parts that really differentiate the business.
- Bounded contexts. Watch for contexts that drift into solving unrelated problems (“jack of all trades”) and extract focused ones. Contexts that can’t do anything without calling each other are a sign that the boundaries need redrawing for autonomy.
- Aggregates. New features tend to land in existing aggregates. If an aggregate now holds data that doesn’t need to be strongly consistent with the rest, extract it. That often reveals a hidden model, which may even belong in its own bounded context.
Check yourself
- What integration change does organizational growth often cause?
- Integration moves from conformist to separate ways. What can you infer?
- Signs that a supporting subdomain is turning core?
- Spotting a new business opportunity can cause which type changes?
Answers
- Partnership becomes a customer–supplier relationship (conformist, ACL or OHS).
- The teams struggled to work together, and the duplicated part is supporting or generic, not core.
- The model gets painful to change, and it changes more often.
- Supporting to core, or generic to core.
12 EventStorming
In one sentence: EventStorming gets the right people in a room with a wall of paper and colored sticky notes to map a business process as a timeline of events. The shared understanding it builds matters more than the diagram it produces.
What it is
A low-tech, group modeling workshop created by Alberto Brandolini. You choose a scope (one business process), and the group describes it as domain events on a timeline. Step by step you add commands, actors, policies, read models, external systems, and finally aggregates and context boundaries, until the wall tells the whole story of how the process works.
Who and what you need
People: anyone with knowledge of the process: domain experts, engineers, product, QA, UX, support. The more varied the group, the more you’ll uncover. Keep it to about 10 people at most in person, so everyone can contribute.
Supplies:
- A huge modeling surface: a wall covered in paper roll is ideal, or the biggest whiteboard you can find.
- Plenty of sticky notes in the standard colors, enough that supplies never slow anyone down.
- A marker for every person.
- A big room with no table in the middle and ideally no chairs, so people stay engaged and moving. Keep a few for anyone who needs to sit.
- Snacks. Sessions usually run two to four hours.
Color legend (the usual conventions)
| Element | Note |
|---|---|
| Domain event (past tense) | Orange |
| Pain point / hotspot | Pink, rotated into a diamond |
| Pivotal event | Vertical line on the timeline |
| Command (imperative) | Light blue |
| Actor / persona | Small yellow |
| Policy (automation) | Purple |
| Read model | Green |
| External system | Pink |
| Aggregate | Large yellow |
The ten steps
Using a made-up library book loan process as the running example:
- Unstructured exploration. Everyone writes past-tense events on orange notes and sticks them up, in any order, duplicates welcome: Book Reserved, Book Borrowed, Due Date Passed, Fine Charged, Book Returned. Keep going until new ideas slow down.
- Timelines. Put the events in order, starting with the happy path, then add alternative and failure branches (Book Reported Lost). Remove duplicates, fix wording, and fill in gaps.
- Pain points. Mark anything that needs attention (bottlenecks, manual steps, missing knowledge) with pink diamonds: “Who decides when a fine is waived?” Keep doing this throughout the session.
- Pivotal events. Find events that mark a change of phase and draw a vertical line at each: Book Borrowed, Book Returned. They hint at bounded context boundaries.
- Commands. Add imperative blue notes before the events they cause (Borrow Book), and small yellow actor notes where it’s clear who issues them (Member, Librarian).
- Policies. For commands with no actor, find the automation behind them: “Whenever Due Date Passed happens, then Charge Fine*.”* Use purple notes between the event and the command, and note any condition (“only if not renewed”).
- Read models. Add a green note for the information an actor looks at before issuing a command (“Member’s current loans and fines”), placed before the command.
- External systems. Pink notes for anything outside the scope that sends commands or receives events, such as the payment provider or the email service. By the end of this step, every command should come from an actor, a policy or an external system.
- Aggregates. Group related commands and events around large yellow notes, commands on the left, events on the right. An aggregate takes in commands and emits events (Loan, Membership).
- Bounded contexts. Cluster aggregates that are closely related or tied together by policies. Those clusters are candidate bounded contexts (Lending, Billing).
Variants
The steps are guidance, not rules. A common approach:
- Big picture first: run steps 1–4 across a broad area of the business. That lays a foundation for the ubiquitous language and sketches possible context boundaries.
- Then go deep: run a full ten-step session for each important process you found.
The model you end up with (events, commands, aggregates and candidate contexts) can even be a blueprint for an event-sourced domain model, if that fits. But the real value is the conversation: shared knowledge, aligned mental models, conflicts brought into the open, and a ubiquitous language starting to form.
When to run one
- Build a ubiquitous language. People naturally converge on shared terms while they model together.
- Model a business process, and find aggregate and context boundaries along the way.
- Explore new requirements, so everyone agrees and edge cases come out early.
- Recover lost domain knowledge, which is especially useful before modernizing a legacy system.
- Find improvements by looking at the process end to end.
- Onboard new team members.
When not to: simple, linear processes with no interesting logic gain little from it.
Facilitation tips
- Start with a short briefing: the goal, the scope, and a visible legend of the note colors.
- Watch the energy. When it drops, ask questions or move on to the next step.
- Keep everyone involved. Draw quieter people in by asking them about the current state of the model.
- Take breaks, and restart together: wait until everyone is back, then walk through the wall to get back in the flow.
- Remote sessions (on an online whiteboard such as Miro) are possible but less effective. Be patient, keep groups to about five, run several small sessions and merge the results, and go back to in-person sessions when you can.
It’s like riding a bike: you learn far more by running one than by reading about it, and you don’t need to be an expert to facilitate your first session.
Check yourself
- Who should be invited?
- Name three good reasons to run a session.
- What outcomes can you expect?
Answers
- Anyone with knowledge of the business area being explored, not only engineers or only experts.
- Building a ubiquitous language, exploring a new domain or requirement, recovering lost knowledge from a legacy system, or onboarding newcomers.
- Shared understanding, a foundation for the ubiquitous language, the gaps in what people know brought into the open, and an event-based model you can build from.
Glossary
Short, plain definitions. Follow the links for the full notes.
accidental complexity
Complexity caused by design choices that no longer fit, as opposed to complexity inherent in the business. Remove it. See Chapter 11.
active record
An object that holds a data structure and knows how to load and save itself. It suits simple logic over complex data. See Chapter 5.
aggregate
A cluster of entities and value objects that guards its own consistency. It is changed only through its root’s commands and saved as one transaction. See Chapter 6.
aggregate root
The single entry-point entity of an aggregate. Inner objects are changed only through it. See Chapter 6.
anticorruption layer
A translation layer that a downstream context builds so that an upstream model doesn’t leak into its own. See Chapter 4.
big ball of mud
A codebase that grew without structure after many quick fixes and unexamined design decisions. See Chapter 11.
bounded context
An explicit boundary inside which one model and its language stay consistent. It is designed, not discovered, and it also marks a deployable unit and a single team’s ownership. See Chapter 3.
business domain
A company’s main area of activity: what customers pay it for. See Chapter 1.
command
A request to change state, run by an aggregate after it checks the rules. See Chapter 6.
conformist
An integration where the downstream side adopts the upstream model as it is. See Chapter 4.
context map
A diagram of all bounded contexts and the integration patterns between them. See Chapter 4.
core subdomain
Where the company competes: complex, frequently changing work that sets it apart. Build it in-house. See Chapter 1.
CQRS
Command-Query Responsibility Segregation: one strongly consistent model for changes, plus any number of rebuildable read models. See Chapter 8.
domain event
A past-tense message describing something significant that happened in the business. See Chapter 6.
domain expert
A person who knows how the business really works and is the source of the knowledge being modeled. See Chapter 1.
domain model
An object model that puts data and behavior together to handle complex business logic. See Chapter 6.
domain service
A stateless object for business logic that belongs to no single aggregate, often a calculation that reads several. See Chapter 6.
entity
An object identified by an ID rather than its values, whose state changes over time. See Chapter 6.
essential complexity
Complexity inherent in the business domain itself. Manage it with DDD tools rather than trying to remove it. See Chapter 11.
event sourcing
Storing every state change as an event and deriving state by replaying the events. See Chapter 7.
event store
An append-only database of events, with fetch-by-ID and append-with-expected-version. See Chapter 7.
EventStorming
A sticky-note workshop for mapping a business process as a timeline of domain events, then adding commands, policies, aggregates and contexts. See Chapter 12.
generic subdomain
A complex but already-solved problem that every company handles the same way. Buy or adopt it. See Chapter 1.
heuristic
A rule of thumb that is good enough to decide quickly without being guaranteed correct. See Chapter 10.
idempotent
Giving the same result however many times it is repeated. See Chapter 5.
layered architecture
Presentation, business logic and data access layers, each depending only on the layer below. See Chapter 8.
migration event
A single explicit event that starts an event stream for data migrated from a state-based system. See Chapter 11.
model
A purposeful simplification that keeps only what a specific problem needs. See Chapter 2.
open-host service
An integration where the upstream side exposes a consumer-friendly published language, separate from its internal model. See Chapter 4.
optimistic concurrency
Saving a change only if the data hasn’t changed since it was read, usually checked with a version number. See Chapter 6.
outbox
Saving new events in the same transaction as the state change, then having a relay publish them. Delivery is at least once. See Chapter 9.
partnership
An integration where two teams coordinate changes in both directions as they come up. See Chapter 4.
pivotal event
An EventStorming event that marks a change of phase in a process. It often hints at a bounded-context boundary. See Chapter 12.
policy (EventStorming)
An automation rule saying ‘when this event happens, run that command’. See Chapter 12.
ports & adapters
An architecture where the core defines interfaces (ports) and infrastructure implements them (adapters). Also called hexagonal, onion or clean architecture. See Chapter 8.
process manager
An explicitly started, stateful coordinator whose business logic decides each next step of a multi-step process. See Chapter 9.
projection
A state or read model derived from events or from the command model. See Chapter 7 and Chapter 8.
published language
The public, integration-focused model exposed by an open-host service. See Chapter 4.
read model (EventStorming)
The information an actor looks at before issuing a command. See Chapter 12.
saga
A process spanning several transactions that reacts to events with commands and compensates on failure. See Chapter 9.
separate ways
Choosing to duplicate a capability instead of integrating it. See Chapter 4.
shared kernel
A small piece of model that several contexts share and change together. See Chapter 4.
snapshot
A cached projection that lets you replay only the newer events, as an optimization. See Chapter 7.
subdomain
A smaller area of business activity: core, generic or supporting. It is discovered, not designed. See Chapter 1.
supporting subdomain
A simple, necessary activity with no competitive value. Build it cheaply or outsource it. See Chapter 1.
testing diamond
A testing strategy weighted toward integration tests. It suits active record. See Chapter 10.
testing pyramid
A testing strategy weighted toward unit tests. It suits domain models. See Chapter 10.
transaction script
One procedure per system operation, each running as an all-or-nothing transaction. See Chapter 5.
ubiquitous language
The shared business vocabulary used by everyone on the project, with one meaning per term inside a bounded context. See Chapter 2.
value object
An immutable object defined entirely by its values, with no ID. See Chapter 6.
title: Glossary weight: 500 breadcrumbs: false
Short, plain definitions. Follow the links for the full notes.
active record
An object that holds a data structure and knows how to load and save itself. It suits simple logic over complex data. See Chapter 5.
aggregate
A cluster of entities and value objects that guards its own consistency. It is changed only through its root’s commands and saved as one transaction. See Chapter 6.
aggregate root
The single entry-point entity of an aggregate. Inner objects are changed only through it. See Chapter 6.
anticorruption layer
A translation layer that a downstream context builds so that an upstream model doesn’t leak into its own. See Chapter 4.
bounded context
An explicit boundary inside which one model and its language stay consistent. It is designed, not discovered, and it also marks a deployable unit and a single team’s ownership. See Chapter 3.
business domain
A company’s main area of activity: what customers pay it for. See Chapter 1.
command
A request to change state, run by an aggregate after it checks the rules. See Chapter 6.
conformist
An integration where the downstream side adopts the upstream model as it is. See Chapter 4.
context map
A diagram of all bounded contexts and the integration patterns between them. See Chapter 4.
core subdomain
Where the company competes: complex, frequently changing work that sets it apart. Build it in-house. See Chapter 1.
CQRS
Command-Query Responsibility Segregation: one strongly consistent model for changes, plus any number of rebuildable read models. See Chapter 8.
domain event
A past-tense message describing something significant that happened in the business. See Chapter 6.
domain expert
A person who knows how the business really works and is the source of the knowledge being modeled. See Chapter 1.
domain model
An object model that puts data and behavior together to handle complex business logic. See Chapter 6.
domain service
A stateless object for business logic that belongs to no single aggregate, often a calculation that reads several. See Chapter 6.
entity
An object identified by an ID rather than its values, whose state changes over time. See Chapter 6.
event sourcing
Storing every state change as an event and deriving state by replaying the events. See Chapter 7.
event store
An append-only database of events, with fetch-by-ID and append-with-expected-version. See Chapter 7.
generic subdomain
A complex but already-solved problem that every company handles the same way. Buy or adopt it. See Chapter 1.
idempotent
Giving the same result however many times it is repeated. See Chapter 5.
layered architecture
Presentation, business logic and data access layers, each depending only on the layer below. See Chapter 8.
model
A purposeful simplification that keeps only what a specific problem needs. See Chapter 2.
open-host service
An integration where the upstream side exposes a consumer-friendly published language, separate from its internal model. See Chapter 4.
optimistic concurrency
Saving a change only if the data hasn’t changed since it was read, usually checked with a version number. See Chapter 6.
outbox
Saving new events in the same transaction as the state change, then having a relay publish them. Delivery is at least once. See Chapter 9.
partnership
An integration where two teams coordinate changes in both directions as they come up. See Chapter 4.
ports & adapters
An architecture where the core defines interfaces (ports) and infrastructure implements them (adapters). Also called hexagonal, onion or clean architecture. See Chapter 8.
process manager
An explicitly started, stateful coordinator whose business logic decides each next step of a multi-step process. See Chapter 9.
projection
A state or read model derived from events or from the command model. See Chapter 7 and Chapter 8.
published language
The public, integration-focused model exposed by an open-host service. See Chapter 4.
saga
A process spanning several transactions that reacts to events with commands and compensates on failure. See Chapter 9.
separate ways
Choosing to duplicate a capability instead of integrating it. See Chapter 4.
shared kernel
A small piece of model that several contexts share and change together. See Chapter 4.
snapshot
A cached projection that lets you replay only the newer events, as an optimization. See Chapter 7.
subdomain
A smaller area of business activity: core, generic or supporting. It is discovered, not designed. See Chapter 1.
supporting subdomain
A simple, necessary activity with no competitive value. Build it cheaply or outsource it. See Chapter 1.
transaction script
One procedure per system operation, each running as an all-or-nothing transaction. See Chapter 5.
ubiquitous language
The shared business vocabulary used by everyone on the project, with one meaning per term inside a bounded context. See Chapter 2.
value object
An immutable object defined entirely by its values, with no ID. See Chapter 6.