Bounded Context: Discovering and Drawing the Lines
"Explicitly define the context within which a model applies. Explicitly set boundaries in terms of team organization, usage within specific parts of the application, and physical manifestations such as code bases and database schemas." — Eric Evans, Domain-Driven Design Reference (2015), pattern "Bounded Context"
Summary: A bounded context is an explicit boundary inside which one model holds and every word of the language means exactly one thing; outside it the same word may mean something else, and that is allowed. Focus: The definition and where it comes from, bounded context vs subdomain (solution vs problem space), context vs module vs microservice vs team, discovery heuristics (language, pivotal events, rate of change, data ownership, capabilities, teams, consistency, legacy, compliance), the Bounded Context Canvas filled in for Sales and Fulfilment, deliberate model duplication, sizing, the signals of a wrong line, evolving lines, and how a context looks in Go, in Laravel, in the database and in tests. Learning goal: Given a business you have just met, draw its bounded contexts with reasons you can defend, fill a canvas for each, recognise a wrong boundary from its symptoms, and lay the contexts out in a Go module and a Laravel app so that the compiler, the database and the test suite keep the lines honest.
This chapter is group DD 01 (Strategic Design), after Domains & Subdomains and Ubiquitous Language and before Context Maps & Integration Patterns. It owns the model boundary: where one model stops and the next starts. It does not re-teach the service-level questions (Conway's law, Team Topologies, the distributed monolith, the hidden tax of a network); those live in Service Boundaries. Who owns which table across services is Data Ownership in Microservices; how contexts talk is Service Communication and the next chapter. The running example is the same as in the rest of the DDD path: an online ordering and fulfilment business with the contexts Sales, Fulfilment, Billing, Catalog, Identity and Notifications.
Page map
| If you are looking for | Go to |
|---|---|
| The page in three tables | Everything in one minute |
| Why one big model fails | Why bounded contexts exist |
| Evans 2003 to the canvas and Khononov | Where it comes from |
| The precise definition | What a bounded context is |
| Problem space vs solution space | Bounded context vs subdomain |
| Module, microservice, team | Context vs module vs service vs team |
| How to find the lines | Discovery heuristics |
| Purpose, classification, roles, messages, language, decisions | The Bounded Context Canvas |
| Two Customer classes on purpose | Model duplication is fine |
| Too big, too small | Sizing |
| Symptoms of a wrong line | Signals you got it wrong |
| Split, merge, strangler, bubble | Evolving boundaries |
| Evans's "Continuous Integration" inside a context | Keeping one context sound |
| Packages, providers, schemas, tests | Mechanics, Go, Laravel |
| UserContext, layers as contexts, one per table | Solving the classic problems |
| Which shape for which situation | Choosing |
| Monolith to distributed data | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Bounded context | The fence inside which one model and one language hold | Inside Sales, "customer" = someone we sell to | One model with contradictory meanings |
| Model | The concepts, rules and words we chose to solve a problem | Sales: Customer, Segment, Order, Quote | Code that matches nobody's way of thinking |
| Ubiquitous language | The team's words, used in talk and in code, inside one context | "Place order", "discount tier" | Translation in every meeting |
| Subdomain | A part of the business problem (found, not designed) | Ordering, Fulfilment, Payments | Effort spread evenly over core and commodity |
| Context map | The drawing of all contexts and how they relate | Sales → Fulfilment via sales.order.placed.v1 | Hidden coupling between models |
| Translation at the edge | Converting another context's terms into ours at the boundary | Sales ShipTo → Fulfilment Recipient | Foreign words leak into our model |
| Bounded Context Canvas | One page that designs and documents a single context | Purpose, roles, messages, decisions | Boundaries that live only in heads |
Bounded context vs its neighbours.
| Is it the same as a bounded context? | Relationship | |
|---|---|---|
| Subdomain | No: problem space vs solution space | 1 : 1 is common; 1 subdomain : n contexts and n subdomains : 1 context both happen |
| Microservice | No | A service should not span contexts; a context may be 1 or several services, or none (a module) |
| Module / package | Can be | In a modular monolith a context is often one top-level module |
| Team | No | One team may own several contexts; one context should have one owning team |
| Database schema | Usually follows | One schema (or database) per context; never two contexts writing one table |
Signals at a glance.
| You see | It suggests | Move |
|---|---|---|
| Same word, different attributes or rules | Two contexts in one model | Split the model, translate at the edge |
| Two words for one thing inside one context | Synonyms, a language that was never agreed | Pick one word, rename in code |
| Every change touches the same two contexts | Line in the wrong place | Merge, or move the concept |
| Transaction that must cover two contexts | Invariant split across the line | Move the invariant's data into one context |
| Two contexts write one table | The boundary exists only on paper | One owner, the other reads a copy |
Why bounded contexts exist
Evans starts the pattern with an observation, not a rule: "Multiple models are in play on any large project." Different user communities need different models, teams build their own, tools differ. The trouble begins when we pretend there is only one: "Multiple models are inevitable, yet when code based on distinct models is combined, software becomes buggy, unreliable, and difficult to understand." A bounded context is the decision to stop pretending: each model gets a named fence, and the fence is drawn in team ownership, in code and in the database schema.
Fowler puts the history in one line: "In those younger days we were advised to build a unified model of the entire business, but DDD recognizes that we've learned that “total unification of the domain model for a large system will not be feasible or cost-effective”". His example is an electricity utility where "meter" meant three different things to three departments.
| One enterprise model | One model per bounded context |
|---|---|
One Customer table with every field any team ever needed | Each context keeps the customer attributes it uses |
| A meeting to add a column | A team changes its own model alone |
| Words need adjectives ("billing customer", "shipping customer") | Words are short and exact inside each context |
| Invariants of different areas mixed in one class | Each rule lives with the model that owns it |
| Integration is "just a join" | Integration is explicit: messages, translation |
| Simple to start | More design up front, much cheaper to change later |
The analogy we reuse on this page: a hospital. "Patient" at the admissions desk is a name, an insurance number and a bed. In the operating theatre it is a body with allergies, blood type and anaesthesia history. In the billing office it is a payer with procedures and tariffs. Nobody in the hospital is confused, because each department speaks inside its own room. Confusion starts only when one form tries to serve all three rooms. A bounded context is a room with a door; the hand-over sheet at the door is the translation.
The picture is the running example: six contexts, each with its own word for the person (user, customer, recipient, account, contact) and its own events. The arrows are previewed here and named properly in Context Maps & Integration Patterns.
Three common misunderstandings, up front
- "A bounded context is a microservice." It is a model boundary. Khononov: "A Microservice is a Bounded Context, but not vice versa." A context can be one module inside a monolith.
- "Bounded contexts are the same as subdomains." Subdomains describe the business problem; contexts are design decisions about models. They often line up, but not always.
- "Duplicating the customer in two contexts is a smell." It is the point. Each context keeps the attributes and rules it needs; one shared "Customer" for everyone is the god model.
Where it comes from
Evans, 2003. Domain-Driven Design opens its strategic-design part with Bounded Context (Fowler: "Bounded Context opens part IV (Strategic Design)"). The free DDD Reference (2015) keeps the pattern text and adds the glossary definition used on this page.
Brandolini, 2009. Strategic Domain Driven Design with Context Mapping (InfoQ, 25 November 2009) made the idea practical with banking examples and states the size limit: "The maximum extent a model can be stretched without compromising its conceptual integrity is called a context."
Vernon, IDDD. Implementing Domain-Driven Design put strategic design first. In its first chapter (published as an InformIT excerpt, 9 November 2012): "There is one Ubiquitous Language per Bounded Context" and "Bounded Contexts are relatively small; smaller than we might at first imagine." Fowler points to chapter 2 for "how a domain is divided into Bounded Contexts" (we could read chapter 1 only).
Fowler, 2014. The BoundedContext bliki entry (15 January 2014) is the short reference most people link.
Microservices. Richardson's Decompose by subdomain pattern made subdomains a service-decomposition strategy: "Define services corresponding to Domain-Driven Design (DDD) subdomains."
Khononov, 2018. Bounded Contexts are NOT Microservices (21 January 2018) and his DDD eXchange 2018 talk separated the three ideas: contexts, subdomains, services.
DDD-crew. Nick Tune and the DDD-crew published the Bounded Context Canvas (now version 5) and the five bounded context design heuristics.
Year Idea What it added
1 2003 Evans: Bounded Context, Context Map One model per explicit boundary
2 2009 Brandolini: context mapping in practice Size limit = conceptual integrity
3 2012 Vernon: IDDD excerpt, strategy first One language per context; contexts are small
4 2014 Fowler bliki; then decompose by subdomain Contexts become the service-design vocabulary
5 2018 Khononov: contexts are not microservices Context = largest valid service, not the unit
6 later DDD-crew: Bounded Context Canvas, heuristics A repeatable way to design one contextWhat a bounded context is
Evans's glossary: "A description of a boundary (typically a subsystem, or the work of a particular team) within which a particular model is defined and applicable." Three parts of that sentence matter:
| Part | Meaning | Consequence |
|---|---|---|
| "a boundary" | A line that has an inside and an outside | You must be able to say whether a class, table or word is inside |
| "a particular model" | One consistent set of concepts and rules | No two meanings for one word inside |
| "defined and applicable" | The model is valid only inside | Outside, translate; never reuse the model raw |
Khononov makes the consequence explicit: "A model is only valid in its Bounded Context." Fowler adds the main driver: "Usually the dominant one is human culture, since models act as Ubiquitous Language, you need a different model when the language changes."
The running example, drawn with reasons. Each line below is a decision; the heuristics are explained in Discovery heuristics.
| Context | Why it is its own context | Heuristics that draw the line | Its word for the person |
|---|---|---|---|
| Sales | Ordering and pricing share one language and the invariant "price fixed at placement" | Language, consistency, business value (core) | Customer |
| Fulfilment | Pickers and dispatchers talk about shipments, bins and parcels, never prices; their work starts after the pivotal event OrderPlaced | Pivotal event, language, rate of change | Recipient |
| Billing | Invoices, tax and payment providers change with law, not with checkout; payment data is regulated | Compliance, data ownership, external system edge | Account |
| Catalog | Merchandisers curate listings, media and copy on their own schedule | Business capability, team ownership, rate of change | (none; it talks about products) |
| Identity | Login, MFA and roles are a solved problem, bought as a product, with security rules of their own | Business value (generic), compliance | User |
| Notifications | Channels, templates and opt-outs; it reacts to others' events and owns none of their decisions | Business value (generic), data ownership (opt-outs) | Contact |
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, a comparison table, and how to use it.
Bounded context Must-know
In plain words: a named area of the system where one model applies and the team speaks one language without ambiguity.
Common misunderstanding: "A bounded context is a folder or a deployable." Those are where a context is implemented. The context is the model plus its language plus its owner; the folder only makes it visible.
Definition: Evans: "Explicitly define the context within which a model applies." Vernon (IDDD ch. 1): "A Bounded Context gives the team a modeling boundary in which to create a solution to a specific business problem domain."
The word "order" in the running example
1 Storefront: customer clicks "Buy" -> Sales: Order {lines, prices, total}; status placed
2 Sales publishes sales.order.placed.v1 -> only ids, SKUs, quantities, ship-to leave Sales
3 Fulfilment receives it -> creates a Shipment, status released (no prices)
4 Billing receives it -> creates an Invoice draft (amount, payer, tax)
Same business event, three models; each word is exact inside its own fenceReal scenario: Fowler's utility "meter"; a bank where "account" is a customer's current account in Banking but a payee record in a personal-finance app (Brandolini's example); a marketplace where "listing" is marketing copy to Catalog and a stock record to the warehouse; an insurer where "policy" is a quote in Sales and a contract in Claims.
| Element | Inside the context | Outside |
|---|---|---|
| Words | One meaning each | May mean something else |
| Classes / types | Free to use | Not imported; use published shapes |
| Tables | Owned and written | Not read directly |
| Rules (invariants) | Enforced here | Not duplicated elsewhere |
| Team | One owner | Others ask or listen |
How to use it: name each context, write its language down (Ubiquitous Language), and make the name visible in code (top-level package or module), in the database (schema) and in ownership files.
Bounded context vs subdomain Must-know
In plain words: a subdomain is a piece of the business you discover; a bounded context is a piece of software model you design. One is the problem, the other is our answer.
Common misunderstanding: "Each subdomain becomes exactly one bounded context." Often it does, and starting there is sensible. But Khononov reports (via InfoQ) that his team's contexts sometimes covered several subdomains, and in his own post: "even Subdomains can be decomposed further."
Definition: subdomains belong to the problem space and are classified core, supporting or generic (Domains & Subdomains). Bounded contexts belong to the solution space; they are where a model is applied. The mapping between them is a design decision with three shapes:
| Shape | Running example | Why it happens |
|---|---|---|
| 1 subdomain : 1 context | Catalog subdomain → Catalog context | Simplest; same experts, same language |
| n subdomains : 1 context | Ordering + Pricing & Promotions → Sales | One language and one invariant ("the price is fixed when the order is placed") span both |
| 1 subdomain : n contexts | Fulfilment → later Warehouse and Delivery | Two groups of experts use different words (bin, pick list vs route, slot, proof of delivery) |
| Subdomain with no context of ours | Payments → external provider wrapped by Billing | Generic: buy it, translate at the edge |
The overlay shows the three shapes at once: Sales covers two subdomains, Fulfilment is one subdomain likely to split into two models, and Billing covers its own subdomain plus a generic one it buys.
How the mapping drifts over time
1 Year 1 Fulfilment subdomain -> Fulfilment context, one team, one model
2 Year 2 Same-day delivery launched; drivers, routes, slots arrive
3 Year 2 "Shipment" means a box on a shelf to pickers, a stop on a route to dispatchers
4 Year 3 Fulfilment context splits: Warehouse (pick, pack) and Delivery (route, proof)
The subdomain did not change; our model of it didReal scenario: a payments company where "Payments" is one subdomain but card acquiring and bank transfers need separate models (1 : n); a small shop whose Billing context covers invoicing and payments because one person owns both (n : 1); a hotel chain whose Identity subdomain is a bought IdP with no context of its own.
How to use it: list subdomains first (to know where to invest), then draw contexts (to know where models stop), then check the mapping: every core subdomain should have a context that a strong team owns, and no context should mix a core subdomain with generic plumbing.
Context vs module vs microservice vs team Must-know
In plain words: a context is a model boundary. You can implement it as a module in one app, as one service, or as a few services. A team can own several contexts. What you must not do is run one service across two contexts.
Common misunderstanding: "One bounded context = one microservice = one team." Khononov: "A Bounded Context defines the boundaries of the biggest services possible", that is, a context is the upper limit for a service, not its size. His heuristic, reported by InfoQ: "Always decompose to the level of bounded contexts. Don’t decompose further, unless you have good reasons to."
Definition: the four units and the rules between them:
| Unit | What it bounds | Rule against a context |
|---|---|---|
| Module (package, namespace) | Code visibility | A context is usually one top-level module; a module never spans two contexts |
| Microservice (deployable) | Process, deploy, failure | A service sits inside one context; a context may have 1..n services |
| Team | Ownership, communication | A team owns 1..n contexts; a context has one owning team |
| Database schema | Data and its writer | One schema per context; split further per service if needed |
Same Sales context, three implementations
1 Startup (6 people): app/Modules/Sales in one Laravel app; schema `sales`
2 Scale-up (40 people): sales-api service + sales-pricing worker; both inside the Sales context, same model, same team
3 Enterprise: Sales split into Quoting and Ordering contexts, two teams; now two models, two schemas
Step 2 is two services, one context. Step 3 is a new context, not just a new service.Real scenario: a modular monolith where Billing is a namespace with its own migrations (context = module); a Sales context with an API service and a separate pricing batch job (1 context : 2 services); one small team owning Catalog and Notifications (1 team : 2 contexts). Lewis and Fowler's microservices article and the Service Boundaries chapter cover the team and deployment side.
How to use it: decide contexts first, then decide deployment per context. Never let a service's code base contain two models with conflicting meanings for one word.
Discovery heuristics Must-know
In plain words: you do not invent context lines; you look for places where the business already changes, and you check each candidate line with several independent tests.
Common misunderstanding: "Draw the database diagram and cluster the tables." Tables tell you how data was stored, not where meanings change. Nick Tune's first heuristic is "Align with domain language", and his fourth reminds you that "Technical concerns should influence your bounded contexts", in that order.
Definition: a heuristic is a rule of thumb that suggests a boundary; good lines pass several. The ones practitioners use:
| Heuristic | Ask | Suggests a line when | Source |
|---|---|---|---|
| Language changes | Does the word mean something else here? | Same word, different attributes or rules; different experts | Evans, Fowler, Tune ("Align with domain language") |
| Pivotal events | Which few events change the phase of the process? | Before/after a pivotal event, different people care | Brandolini via DDD-crew glossary |
| Lifecycle / rate of change | Does this part change weekly while that one is stable? | Promotions rules weekly vs order capture yearly | Brandolini: "different evolutionary forces" |
| Data ownership | Who is the single writer of this record? | Two groups write the same data for different reasons | microservices.io database per service; Data Ownership |
| Business capability | What does the business do, as a verb? | Distinct capabilities with distinct owners | microservices.io decompose by business capability |
| Business value | Is this core, supporting or generic? | Core logic tangled with commodity | Tune ("Align with business value"; "Decouple high value and low value parts") |
| Team ownership | Who would own it? Can one team hold it in its head? | A model needs two teams to change | Tune ("Optimise for social needs"), Team Topologies |
| Consistency requirements | Which data must change atomically together? | Data that need not be consistent at once | Khononov via InfoQ ("Use consistency requirements ...") |
| Legacy system edges | Is there a system whose model we cannot change? | Always: the legacy model is a context | Brandolini: "chances are high that this will be in a different bounded context" |
| Compliance / security | Is this data regulated? | Card data, health data, personal data with its own rules | Tune ("Respect technical constraints": legacy, security, storage) |
| UX | Will the user see seams? | A split would fragment one screen into five calls | Tune ("Don’t ignore the UX") |
Pivotal events in more detail. In a Big Picture EventStorming the group first lays out every domain event on a timeline, then picks out the pivotal ones. The DDD-crew glossary (citing Brandolini's essay Discovering Bounded Contexts with EventStorming): "With Pivotal Events, we start looking for the few most significant events in the flow. For an e-commerce website, they might look like 'Article Added to Catalogue', 'Order Placed', 'Order Shipped', 'Payment Received' and 'Order Delivered'." Pivotal events tend to sit on the seams: the work before "Order Placed" (browsing, quoting, pricing) is done by other people with other words than the work after it (picking, packing). The workshop itself is Event Storming.
Big Picture timeline of the running example, pivotal events marked ||
1 ProductListed PriceChanged || ProductPublished || CartUpdated QuoteGiven
2 || OrderPlaced || PaymentAuthorised InvoiceIssued || PaymentCaptured ||
3 ShipmentReleased ItemsPicked ParcelPacked || ParcelDispatched || OrderDelivered
4 Candidate lines: Catalog | Sales | Billing | Fulfilment; Identity and Notifications sit outside the flow
Then test each line with the other heuristics before you trust itReal scenario: a team that first drew "Orders" around everything from cart to delivery, then saw on the timeline that pickers never say "cart" and sales never says "bin"; a bank whose regulated card data forced its own context regardless of language; a company that kept "Quote" and "Order" together because the business rule "price fixed at placement" needs both atomically.
How to use it: produce candidate lines from language and pivotal events, then run every candidate through value, team, consistency, legacy, compliance and UX. A line that only one heuristic supports is weak; a line that consistency contradicts is wrong.
The Bounded Context Canvas Must-know
In plain words: a one-page form that forces a team to decide what a context is for, what it says, what comes in and goes out, and what it assumes, before writing code.
Common misunderstanding: "The canvas is documentation you fill in after the design." The DDD-crew README calls it "a collaborative tool for designing and documenting the design of a single bounded context"; designing comes first, and the open-questions box exists because the first draft is uncertain.
Definition: the v5 canvas sections, in the README's order of definitions: Name; Purpose ("A few sentences describing the why and what of the context in business language. No technical details here."); Strategic classification (domain: core, supporting, generic; business model: revenue generator, engagement creator, compliance enforcer; evolution: genesis, custom built, product, commodity); Domain roles (e.g. execution model, analysis model, approver, gateway, from the model-traits worksheet); Inbound communication and Outbound communication (messages as commands, queries or events, with collaborators and relationship types); Ubiquitous language; Business decisions ("key business rules and policies"); Assumptions ("Most design happens based on assumptions and it is highly recommended to make them explicit"); Verification metrics; Open questions.
Filling a canvas (the README: name and purpose first, then any order)
1 Name + purpose agreed in business words 10 min
2 Outside-in: who sends what to us? what do we send? 20 min
3 Inside-out: language and business decisions 20 min
4 Classification and roles 10 min
5 Assumptions, metrics, open questions 10 min
6 Challenge: move one message to another context; does the design get better?Sales and Fulfilment, side by side (the Sales card is the diagram above):
| Section | Sales | Fulfilment |
|---|---|---|
| Purpose | Turn shoppers into confirmed, correctly priced orders | Get every placed order to the recipient complete and on the promised day |
| Classification: domain | Core (ordering, pricing) | Core or supporting (the delivery promise; see Domains & Subdomains) |
| Classification: business model | Revenue generator | Engagement creator (the promise brings customers back) |
| Classification: evolution | Custom built | Custom built (warehouse software for parts is a product) |
| Domain roles | Execution model, approver | Execution model |
| Inbound | PlaceOrder, Quote (commands from Storefront); ProductRepriced (Catalog); CustomerRegistered (Identity) | sales.order.placed.v1, sales.order.cancelled.v1 (events from Sales); SkuCreated (Catalog) |
| Outbound | sales.order.placed.v1, sales.order.cancelled.v1 | fulfilment.parcel.dispatched.v1, fulfilment.order.delivered.v1 |
| Ubiquitous language | Customer, Segment, Discount Tier, Quote, Order, Order Line | Shipment, Recipient, Pick List, Parcel, Tracking Ref, released / picking / packed / dispatched |
| Business decisions | Discount by segment and tier; an order needs at least one line; quote valid 15 minutes; price fixed at placement | A shipment needs a deliverable recipient; dispatch needs a tracking reference; cut-off 16:00 for same-day |
| Assumptions | B2B stays under 30% of orders; Fulfilment never needs prices | One warehouse; couriers give tracking refs synchronously |
| Verification metrics | % of PRs touching only sales/; sync cross-context calls per checkout | % of changes needing a Sales change; event lag from placed to released |
| Open questions | Who owns returns? | Does a split delivery create two shipments or one? |
Real scenario: a team that discovered, while filling "Outbound", that Sales was sending prices to Fulfilment only because the packing slip printed them; the fix was a slip without prices. Another found that "Business decisions" of their Notifications context were really Sales rules ("send a discount code after the third order") and moved them.
| Canvas question | Bad answer | Good answer |
|---|---|---|
| Purpose | "CRUD for orders" | Business outcome in business words |
| Outbound | 25 message types | A handful of coarse, named events |
| Language | Generic nouns: Data, Item, Info | Words the experts use |
| Metrics | None | Something you can measure from CI or production |
How to use it: keep the canvas in the repository next to the context (the README lists HTML, YAML, draw.io and Excalidraw versions), review it when the context's contract changes, and use the README's interface tips: is the interface too big, is the context "exposing too much of its internals", do any messages belong elsewhere?
Model duplication is fine Must-know
In plain words: Sales has a Customer with a segment and a discount tier; Fulfilment has a Recipient with an address and a phone. They describe the same human being, and that is correct.
Common misunderstanding: "DRY: one Customer class, reused everywhere." DRY is about one piece of knowledge having one home. A Sales discount rule and a Fulfilment address rule are different knowledge. Forcing them into one class couples every context to every other. Brandolini's banking example keeps a BankingAccount and a separate PayeeAccount because "we have two clear and distinct uses, each one calling for a distinct model."
Definition: each context keeps its own representation of shared real-world concepts, with only the attributes and behaviour it needs, linked by an identifier. Fowler: "Different contexts may have completely different models of common concepts with mechanisms to map between these polysemic concepts for integration."
| Concept | Sales | Fulfilment | Billing | Identity | Notifications |
|---|---|---|---|---|---|
| The person | Customer {id, segment, tier} | Recipient {name, address, phone} | Account {id, VAT no, credit limit, payment method} | User {login, password hash, MFA, roles} | Contact {channels, opt-outs, locale} |
| Linked by | customer_id | sales_order_id → address copied at placement | customer_id | user_id = customer_id | customer_id |
| Changes when | Segment rules change | Courier needs change | Tax law changes | Security policy changes | Messaging law changes |
Customer moves house the day after ordering
1 Day 0 Order placed; Sales publishes ship_to = old address; Fulfilment copies it into Recipient
2 Day 1 Customer updates profile address (Identity or Sales profile)
3 Day 1 Fulfilment still ships to the old address: the copy is the address *for this order*
4 Fix is a business decision, not a data sync: "address changes after placement need a support request"
Duplication made the rule visible; a shared table would have changed the parcel silentlyReal scenario: a shop where a shared customers.address column meant invoice address to Billing and delivery address to Fulfilment, and a gift order sent the invoice to the gift recipient; an airline where the passenger name on a ticket must not change when the loyalty profile name changes.
How to use it: copy what you need at the moment you need it (usually from an event), keep the source's identifier, and write down which context owns the original. The data-flow side (events, read models) is Data Ownership in Microservices and Microservices Data Patterns.
Sizing a context Important
In plain words: a context should be as big as one consistent language and the invariants that use it, and no bigger; smaller than that, it starts calling its neighbours for everything.
Common misunderstanding: "Smaller is always better." Vernon: contexts are "relatively small", but the full sentence sets the floor: "It is large enough only to capture the complete Ubiquitous Language of the isolated business domain, and no larger." Khononov describes his team's road from contexts to subdomains to entity services, ending in a distributed monolith.
Definition: two failure modes. Too big: the model fragments, words gain several meanings, a god model appears, many people edit it (Evans: "there is a strong tendency for the model to fragment"). Too small: invariants split across contexts, chatty synchronous calls, anemic models that only hold data, distributed transactions.
"Too small" in practice: placing one order with entity-sized contexts
1 Checkout -> CustomerContext.get(cus-42) sync call 1
2 Checkout -> ProductContext.get(MUG-01) sync call 2
3 Checkout -> PriceContext.calc(cus-42, MUG-01) sync call 3 (needs segment from call 1 again)
4 Checkout -> OrderContext.create(...) sync call 4
5 Checkout -> OrderLineContext.add(...) x n n calls; the rule "price fixed at placement" spans 3 contexts
One use case, five contexts, no single place that owns the invariant| Symptom | Too big | Too small |
|---|---|---|
| Language | Words with several meanings | Same word, same meaning, in several contexts |
| Change | Many teams edit one model | One change edits several contexts |
| Calls | In-process, unbounded | Many sync calls per use case |
| Models | God classes | Anemic data holders |
| Transactions | Huge, cover unrelated rules | Needed across contexts |
| Team | Too many people per model | One team per three tiny contexts |
How to use it: start bigger (Khononov: decompose to context level, not further, without a reason), watch the symptoms, and split when ambiguity appears. Merging two tiny contexts later is cheap inside a monolith and expensive across a network.
Signals that the line is wrong Important
In plain words: a wrong boundary keeps sending you the same bills: transactions across it, tables shared over it, two words for one thing, and one team that can never change one side alone.
Common misunderstanding: "If it compiles and the tests pass, the boundary is fine." Boundaries fail in the change history and in the database long before they fail in the build.
Definition: the signals, how to measure them, and the usual cause:
| Signal | How to see it | Usual cause | Move |
|---|---|---|---|
| Constant cross-context transactions | A use case needs both contexts' tables in one COMMIT | An invariant was split | Move the invariant's data into one context |
| Shared tables | More than one context's role can write a table | Line drawn on paper only | One writer; others read events or copies |
| Synonyms inside one context | Code says client, customer and buyer for one thing | Language never agreed | Pick one word (Ubiquitous Language) |
| Homonyms inside one context | status means two state machines | Two models in one | Split |
| Same team always touches two contexts | Change coupling in git > 30% | Line in the wrong place or a missing concept | Merge or move the concept |
| A context imports another's internals | Architecture test fails, internal error | Shortcut taken | Publish a contract, translate |
| Long chains of sync calls | Trace depth per request | Contexts too small | Merge, or replicate data |
Detecting a split invariant
1 Rule: "a B2B order over the credit limit must not be placed"
2 Sales owns orders; Billing owns credit limits
3 Today: Sales calls Billing synchronously inside its transaction; Billing down = no orders
4 Question: is "credit limit" a Sales word or a Billing word?
5 Business answer: placing is allowed; Billing holds the order for approval -> the rule belongs to Billing, async
Moving the rule removed the cross-context transaction; no new service was neededReal scenario: a team whose Sales and Pricing contexts changed together in 70% of commits and were merged; a Catalog that wrote stock_level because the product page showed availability, removed by publishing a stock event from Fulfilment.
How to use it: check these signals each quarter with numbers (writers per table, change coupling, cross-context transactions). The tooling for change coupling is in Service Boundaries: Measuring boundary health.
Evolving boundaries Important
In plain words: boundaries are hypotheses. You will split some contexts, merge others, and grow new ones next to a legacy system.
Common misunderstanding: "Once drawn, the context map is the architecture." Evans's Context Map advice is to describe what is there first: "Map the existing terrain. Take up transformations later."
Definition: the four moves:
| Move | When | How, safely |
|---|---|---|
| Split | New language appears inside one context; two teams fight over one model | Split the model in-process first (two modules, translation between them), then the schema, then deployment |
| Merge | Change coupling high, cross-context transactions, one team owns both | Merge the modules; keep one language; drop the translation |
| Bubble context | A clean model is needed next to a legacy system | A small new context with its own model and an anticorruption layer to legacy (Fowler links Evans's "bubble context") |
| Strangler fig | Replace a legacy context gradually | Route capability by capability to the new context (Strangler Fig) |
Splitting Fulfilment into Warehouse and Delivery, inside one app
1 Week 1 Create modules warehouse/ and delivery/ under fulfilment/; move types, no behaviour change
2 Week 2 Introduce ParcelPacked event between them; delivery/ stops reading warehouse tables
3 Week 3 Separate schemas fulfilment_warehouse and fulfilment_delivery; roles per schema
4 Week 6 Delivery gets its own team; only then consider a separate deployable
Each step is reversible until the network stepReal scenario: a marketplace that split "Seller" into Onboarding and Payouts when compliance rules diverged; a team that merged "Cart" back into Sales after a year of lockstep releases; a bank that put a bubble context in front of its mainframe for a new mobile product.
How to use it: treat each move as a refactoring with tests at the boundary (Go, Laravel); record it in an ADR; update the canvas and the context map.
Keeping one context sound: Evans's Continuous Integration Good to know
In plain words: inside one context, everybody must keep merging their code and their understanding of the words, or the one model quietly becomes several.
Common misunderstanding: "Continuous Integration means a CI server." Evans's pattern is about the model, not only the build. Automated tests are part of it; so is the conversation.
Definition: Evans: "Once a bounded context has been defined, we must keep it sound. When a number of people are working in the same bounded context, there is a strong tendency for the model to fragment." Therefore: "Institute a process of merging all code and other implementation artifacts frequently, with automated tests to flag fragmentation quickly. Relentlessly exercise the ubiquitous language to hammer out a shared view of the model as the concepts evolve in different people’s heads."
Fragmentation inside Sales, caught early
1 Dev A adds Order.discount (percent); Dev B adds Order.discount (minor units) in a branch
2 Both merge daily; the test "total = gross - discount" fails on B's change
3 Five-minute talk: the language says "discount percent" and "discount amount"; rename both
Without daily merges the two meanings ship and the model has split silently| Practice | Protects against |
|---|---|
| Trunk-based or short-lived branches | Parallel models in long branches |
| Tests named in the domain language | Rules changing meaning unnoticed |
| Glossary in the repo, reviewed in PRs | Synonyms creeping in |
| One owning team | "Everyone's model" that nobody guards |
How to use it: this is the inside-the-fence partner of the context map: the map handles relations between contexts, continuous integration keeps each one whole. When the effort of keeping one model sound grows too large, the context is too big.
Mechanics
Drawing the lines step by step Must-know
A first pass at contexts (one to two days with domain experts)
1 List subdomains and classify them (core / supporting / generic) -> /ddd/domains-subdomains
2 Big Picture EventStorming; mark pivotal events and language changes -> /ddd/event-storming
3 Draw candidate contexts around stable language islands
4 Run the heuristics: value, team, consistency, legacy, compliance, UX
5 Fill one Bounded Context Canvas per candidate; challenge by moving messages
6 Draw the context map: relations and translation points -> /ddd/context-maps-integration-patterns
7 Implement each context as a module with its own schema and tests; add architecture tests
8 Revisit with metrics after one quarter: change coupling, cross-context transactionsCode layout: one tree per context Must-know
| Concern | Go | Laravel 13 |
|---|---|---|
| Context root | sales/, fulfilment/ top-level packages in one module | app/Modules/Sales, app/Modules/Fulfilment |
| Private model | sales/internal/domain: the go command refuses imports from outside sales/ | Domain/ namespace; Pest arch() forbids use from other modules |
| Published language | sales/salesapi: plain structs, versioned names | Contracts/OrderPlacedV1 readonly class |
| Translation at the edge | fulfilment/internal/acl | Fulfilment/Acl/SalesOrderTranslator |
| Wiring | cmd/shop/main.go | SalesServiceProvider, FulfilmentServiceProvider in bootstrap/providers.php |
| Persistence | Repository per context, own schema | #[Connection('sales')] models, migrations per module via loadMigrationsFrom |
| Routes | http.ServeMux patterns per context | loadRoutesFrom per module |
| Tests | go test ./sales/... ./fulfilment/... | tests/Fulfilment, tests/ArchitectureTest.php (a tests/Sales folder follows the same shape) |
Go's rule (Go 1.4 release notes): internal packages "may not be imported by packages outside the source subtree in which they reside". That makes the model boundary a compiler error rather than a review comment.
Persistence: a schema per context Must-know
In one PostgreSQL database, give each context a schema and a role; later, moving a context to its own database is a dump and a connection-string change, because nothing else reads its tables.
-- PostgreSQL: one schema and one login role per bounded context.
CREATE ROLE sales_ctx LOGIN PASSWORD 'change-me';
CREATE ROLE fulfilment_ctx LOGIN PASSWORD 'change-me';
CREATE SCHEMA sales AUTHORIZATION sales_ctx;
CREATE SCHEMA fulfilment AUTHORIZATION fulfilment_ctx;
REVOKE ALL ON SCHEMA sales, fulfilment FROM PUBLIC;
ALTER ROLE sales_ctx SET search_path = sales;
ALTER ROLE fulfilment_ctx SET search_path = fulfilment;
-- Sales: the customer as Sales sees it. No address, no credit limit.
-- Tables belong to the role that creates them, so create them as the context's role.
SET ROLE sales_ctx;
CREATE TABLE sales.customers (
id text PRIMARY KEY,
segment text NOT NULL CHECK (segment IN ('retail', 'b2b')),
discount_tier smallint NOT NULL DEFAULT 0 CHECK (discount_tier BETWEEN 0 AND 3)
);
CREATE TABLE sales.orders (
id text PRIMARY KEY,
customer_id text NOT NULL REFERENCES sales.customers (id), -- FK inside the context: fine
lines jsonb NOT NULL,
total_minor bigint NOT NULL CHECK (total_minor >= 0),
placed_at timestamptz NOT NULL
);
RESET ROLE;
-- Fulfilment: the same human as a recipient, copied at placement.
SET ROLE fulfilment_ctx;
CREATE TABLE fulfilment.shipments (
id text PRIMARY KEY,
sales_order_id text NOT NULL UNIQUE, -- reference across contexts: no FK
recipient jsonb NOT NULL, -- name, line1, city, postal_code, country, phone
items jsonb NOT NULL,
status text NOT NULL CHECK (status IN ('released', 'picking', 'packed', 'dispatched')),
tracking_ref text
);
RESET ROLE;
-- Health check: exactly one writer per schema.
SELECT table_schema, grantee, string_agg(DISTINCT privilege_type, ',') AS privileges
FROM information_schema.role_table_grants
WHERE table_schema IN ('sales', 'fulfilment') AND privilege_type IN ('INSERT', 'UPDATE', 'DELETE')
GROUP BY table_schema, grantee ORDER BY 1, 2;On MySQL, a "schema" is a database: CREATE DATABASE sales; GRANT ALL ON sales.* TO 'sales_ctx'@'%';. On SQL Server, CREATE SCHEMA sales AUTHORIZATION sales_ctx. The path from schema-per-context to database-per-context, and the brownfield options, are in Data Ownership in Microservices; persistence design inside one context is Data Persistence Design.
Errors you will see when a boundary holds
| Where | Message | Meaning |
|---|---|---|
| Go build | use of internal package academy/bounded-context/sales/internal/domain not allowed | Fulfilment tried to import the Sales model |
| Go arch test (this page) | sales/sales.go imports academy/bounded-context/fulfilment (forbidden: sales is upstream and must not know fulfilment) | Upstream reached downstream |
| PostgreSQL | ERROR: permission denied for schema sales (SQLSTATE 42501) | Fulfilment's role read Sales tables |
| MySQL | ERROR 1142 (42000): SELECT command denied to user 'fulfilment_ctx'@'%' for table 'orders' | Same, MySQL wording |
Pest arch() | Failing expectation naming the class and the forbidden namespace | Module used another context's Domain |
Go
The module is docs/snippets/ddd/bounded-context/go (go 1.24); gofmt -l . is clean and go vet ./... and go test ./... pass. Two contexts, Sales and Fulfilment, live in one module, each with an internal/ model.
Wrong: one Customer for everybody
The god model compiles and works. Every context's rules sit in CanOrder, and Address and Status already mean two things:
// Package wrong shows the god model: one Customer type that every part of
// the shop shares. It compiles and works; it is bad design, not broken code.
package wrong
import (
"errors"
"time"
)
// Customer is used by Sales, Fulfilment, Billing, Identity and Notifications.
// Every team adds fields; nobody can remove one.
type Customer struct {
ID string
Email string // Identity: login name. Notifications: where to send mail.
PasswordHash string // Identity
Segment string // Sales: "retail" | "b2b"
DiscountTier int // Sales
CreditLimit int64 // Billing, in minor units
VATNumber string // Billing
Address string // Fulfilment: delivery address? Billing: invoice address? Both, until they differ.
Phone string // Fulfilment courier, or Sales account manager?
Status string // "active" means "can log in" to Identity and "can order" to Sales
OptedOut bool // Notifications: marketing only, or also shipping updates?
UpdatedAt time.Time
}
// CanOrder mixes rules from three contexts into one method. A change to any
// of them (a new Billing rule, a new Identity status) changes this file.
func (c *Customer) CanOrder(totalMinor int64) error {
if c.Status != "active" {
return errors.New("customer not active")
}
if c.Segment == "b2b" && c.VATNumber == "" {
return errors.New("b2b customer without VAT number")
}
if totalMinor > c.CreditLimit {
return errors.New("over credit limit")
}
if c.Address == "" {
return errors.New("no address")
}
return nil
}Right: the Sales model and its published language
The Sales customer knows segments and tiers, nothing else:
// Package domain is the Sales model. Only code under academy/bounded-context/sales
// can import it: the go command enforces the internal/ rule.
package domain
import "errors"
// Segment is a Sales word: it drives pricing, not shipping or invoicing.
type Segment string
// Segments known to Sales.
const (
Retail Segment = "retail"
B2B Segment = "b2b"
)
// Customer in Sales is someone we sell to: a segment and a discount tier.
// It has no address, password or credit limit; those belong to other models.
type Customer struct {
ID string
Segment Segment
DiscountTier int // 0..3
}
// ErrUnknownTier is returned for a tier outside the price list.
var ErrUnknownTier = errors.New("sales: unknown discount tier")
// DiscountPercent is a Sales business decision.
func (c Customer) DiscountPercent() (int, error) {
tiers := map[Segment][]int{Retail: {0, 2, 5, 8}, B2B: {5, 10, 12, 15}}
t, ok := tiers[c.Segment]
if !ok || c.DiscountTier < 0 || c.DiscountTier >= len(t) {
return 0, ErrUnknownTier
}
return t[c.DiscountTier], nil
}package domain
import (
"errors"
"time"
)
// Line is an order line with the price Sales agreed with the customer.
type Line struct {
SKU string
Quantity int
UnitPriceMinor int64
}
// Order in Sales is a commercial agreement: what, how many, at what price.
type Order struct {
ID string
CustomerID string
Lines []Line
TotalMinor int64
PlacedAt time.Time
}
// ErrEmptyOrder is returned when an order has no lines.
var ErrEmptyOrder = errors.New("sales: order has no lines")
// Place applies the Sales rules (non-empty, positive quantities, discount)
// and returns the accepted order.
func Place(id string, c Customer, lines []Line, now time.Time) (Order, error) {
if len(lines) == 0 {
return Order{}, ErrEmptyOrder
}
pct, err := c.DiscountPercent()
if err != nil {
return Order{}, err
}
var gross int64
for _, l := range lines {
if l.Quantity <= 0 {
return Order{}, errors.New("sales: quantity must be positive")
}
gross += int64(l.Quantity) * l.UnitPriceMinor
}
total := gross - gross*int64(pct)/100
return Order{ID: id, CustomerID: c.ID, Lines: lines, TotalMinor: total, PlacedAt: now}, nil
}What leaves Sales is a plain, versioned shape. Prices stay inside:
// Package salesapi is the published language of the Sales context: plain
// data shapes, versioned by name. Other contexts may import this package and
// nothing else from Sales.
package salesapi
import "time"
// OrderPlacedV1 is announced once Sales has accepted an order.
type OrderPlacedV1 struct {
EventID string `json:"event_id"`
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
Lines []LineV1 `json:"lines"`
ShipTo AddressV1 `json:"ship_to"`
PlacedAt time.Time `json:"placed_at"`
}
// LineV1 is one ordered item. Prices stay inside Sales; Fulfilment does not need them.
type LineV1 struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
}
// AddressV1 is the delivery address captured at checkout.
type AddressV1 struct {
Name string `json:"name"`
Line1 string `json:"line1"`
City string `json:"city"`
PostalCode string `json:"postal_code"`
Country string `json:"country"`
Phone string `json:"phone"`
}// Package sales is the public face of the Sales context: one use case and
// the port it publishes through. Its model stays in sales/internal/domain.
package sales
import (
"context"
"time"
"academy/bounded-context/sales/internal/domain"
"academy/bounded-context/sales/salesapi"
)
// Publisher sends published-language events. In a monolith it is an
// in-process bus; in services it is an outbox relay to a broker.
type Publisher interface {
Publish(ctx context.Context, e salesapi.OrderPlacedV1) error
}
// PlaceOrderCmd is the inbound command (from the storefront).
type PlaceOrderCmd struct {
OrderID string
CustomerID string
Segment string
Tier int
Lines []LineInput
ShipTo salesapi.AddressV1
}
// LineInput is one requested item with its catalogue price.
type LineInput struct {
SKU string
Quantity int
UnitPriceMinor int64
}
// Module is the Sales context as one unit.
type Module struct {
Pub Publisher
Now func() time.Time
}
// PlaceOrder runs the Sales rules, then announces the result in the
// published language. Fulfilment never sees domain.Order.
func (m Module) PlaceOrder(ctx context.Context, cmd PlaceOrderCmd) (totalMinor int64, err error) {
c := domain.Customer{ID: cmd.CustomerID, Segment: domain.Segment(cmd.Segment), DiscountTier: cmd.Tier}
lines := make([]domain.Line, 0, len(cmd.Lines))
for _, l := range cmd.Lines {
lines = append(lines, domain.Line{SKU: l.SKU, Quantity: l.Quantity, UnitPriceMinor: l.UnitPriceMinor})
}
o, err := domain.Place(cmd.OrderID, c, lines, m.Now())
if err != nil {
return 0, err
}
ev := salesapi.OrderPlacedV1{
EventID: "evt-" + o.ID, OrderID: o.ID, CustomerID: o.CustomerID,
ShipTo: cmd.ShipTo, PlacedAt: o.PlacedAt,
}
for _, l := range o.Lines {
ev.Lines = append(ev.Lines, salesapi.LineV1{SKU: l.SKU, Quantity: l.Quantity})
}
return o.TotalMinor, m.Pub.Publish(ctx, ev)
}Right: the Fulfilment model and translation at the edge
Fulfilment has no Customer at all. It has a Recipient and a Shipment with its own life cycle:
// Package domain is the Fulfilment model. "Customer" does not exist here:
// the person at the door is a Recipient, and what we move is a Shipment.
package domain
import "errors"
// Recipient is Fulfilment's view of the customer: who receives the parcel
// and how the courier reaches them. No segment, no discount, no password.
type Recipient struct {
Name string
Line1 string
City string
PostalCode string
Country string // ISO 3166-1 alpha-2
Phone string
}
// ErrUndeliverable is returned when the courier could not deliver to this recipient.
var ErrUndeliverable = errors.New("fulfilment: recipient address incomplete")
// Validate applies Fulfilment's rule: a courier needs all of these.
func (r Recipient) Validate() error {
if r.Name == "" || r.Line1 == "" || r.City == "" || r.PostalCode == "" || len(r.Country) != 2 {
return ErrUndeliverable
}
return nil
}package domain
import "fmt"
// Status is the life cycle of a Shipment; Sales has no such words.
type Status string
// Shipment states, in order.
const (
Released Status = "released"
Picking Status = "picking"
Packed Status = "packed"
Dispatched Status = "dispatched"
)
// Item is a stock-keeping unit to pick, without any price.
type Item struct {
SKU string
Quantity int
}
// Shipment is what Fulfilment creates from a sales order.
type Shipment struct {
ID string
SalesOrder string // reference to the other context, by ID only
Recipient Recipient
Items []Item
Status Status
TrackingRef string
}
// NewShipment starts a shipment in Released if the recipient is deliverable.
func NewShipment(id, salesOrder string, r Recipient, items []Item) (*Shipment, error) {
if err := r.Validate(); err != nil {
return nil, err
}
if len(items) == 0 {
return nil, fmt.Errorf("fulfilment: shipment %s has no items", id)
}
return &Shipment{ID: id, SalesOrder: salesOrder, Recipient: r, Items: items, Status: Released}, nil
}
var next = map[Status]Status{Released: Picking, Picking: Packed, Packed: Dispatched}
// Advance moves the shipment one step; tracking is required to ship.
func (s *Shipment) Advance(tracking string) error {
to, ok := next[s.Status]
if !ok {
return fmt.Errorf("fulfilment: cannot advance from %s", s.Status)
}
if to == Dispatched {
if tracking == "" {
return fmt.Errorf("fulfilment: tracking reference required to dispatch")
}
s.TrackingRef = tracking
}
s.Status = to
return nil
}The anticorruption layer does the translation. Only Fulfilment's edge (this package and the module's inbound handler below) sees the Sales language; internal/domain never does, and the architecture test enforces that:
// Package acl translates the Sales published language into the Fulfilment
// model. Only Fulfilment's edge (this package and the module's inbound
// handler) sees salesapi; internal/domain never does.
package acl
import (
"academy/bounded-context/fulfilment/internal/domain"
"academy/bounded-context/sales/salesapi"
)
// ShipmentRequest is what Fulfilment needs from a placed order, in its own words.
type ShipmentRequest struct {
SalesOrder string
Recipient domain.Recipient
Items []domain.Item
}
// FromOrderPlaced maps Sales terms to Fulfilment terms. Prices and the
// customer ID are dropped on purpose: Fulfilment does not use them.
func FromOrderPlaced(e salesapi.OrderPlacedV1) ShipmentRequest {
req := ShipmentRequest{
SalesOrder: e.OrderID,
Recipient: domain.Recipient{
Name: e.ShipTo.Name, Line1: e.ShipTo.Line1, City: e.ShipTo.City,
PostalCode: e.ShipTo.PostalCode, Country: e.ShipTo.Country, Phone: e.ShipTo.Phone,
},
}
for _, l := range e.Lines {
req.Items = append(req.Items, domain.Item{SKU: l.SKU, Quantity: l.Quantity})
}
return req
}// Package fulfilment is the public face of the Fulfilment context.
package fulfilment
import (
"context"
"fmt"
"sync"
"academy/bounded-context/fulfilment/internal/acl"
"academy/bounded-context/fulfilment/internal/domain"
"academy/bounded-context/sales/salesapi"
)
// Module keeps shipments in memory for the example; a real one owns its own schema.
type Module struct {
mu sync.Mutex
shipments map[string]*domain.Shipment
seen map[string]bool // processed event IDs: delivery may repeat
}
// New returns an empty Fulfilment module.
func New() *Module {
return &Module{shipments: map[string]*domain.Shipment{}, seen: map[string]bool{}}
}
// OnOrderPlaced is the inbound edge: translate, then use the local model.
func (m *Module) OnOrderPlaced(_ context.Context, e salesapi.OrderPlacedV1) error {
m.mu.Lock()
defer m.mu.Unlock()
if m.seen[e.EventID] {
return nil
}
req := acl.FromOrderPlaced(e)
s, err := domain.NewShipment("shp-"+req.SalesOrder, req.SalesOrder, req.Recipient, req.Items)
if err != nil {
return fmt.Errorf("order %s: %w", e.OrderID, err)
}
m.shipments[s.ID] = s
m.seen[e.EventID] = true
return nil
}
// Status reports a shipment's state by sales order ID.
func (m *Module) Status(salesOrder string) (string, bool) {
m.mu.Lock()
defer m.mu.Unlock()
s, ok := m.shipments["shp-"+salesOrder]
if !ok {
return "", false
}
return string(s.Status), true
}Wiring as a modular monolith
// Command shop wires two bounded contexts in one process: a modular monolith.
// Swapping the bus for an outbox relay and a broker turns them into services
// without touching either model.
package main
import (
"context"
"fmt"
"log"
"time"
"academy/bounded-context/fulfilment"
"academy/bounded-context/sales"
"academy/bounded-context/sales/salesapi"
)
type bus struct {
handlers []func(context.Context, salesapi.OrderPlacedV1) error
}
func (b *bus) Publish(ctx context.Context, e salesapi.OrderPlacedV1) error {
for _, h := range b.handlers {
if err := h(ctx, e); err != nil {
return err
}
}
return nil
}
func main() {
ful := fulfilment.New()
b := &bus{handlers: []func(context.Context, salesapi.OrderPlacedV1) error{ful.OnOrderPlaced}}
s := sales.Module{Pub: b, Now: time.Now}
total, err := s.PlaceOrder(context.Background(), sales.PlaceOrderCmd{
OrderID: "ord-1", CustomerID: "cus-42", Segment: "b2b", Tier: 2,
Lines: []sales.LineInput{{SKU: "MUG-01", Quantity: 10, UnitPriceMinor: 900}},
ShipTo: salesapi.AddressV1{Name: "Acme BV", Line1: "Dock 4", City: "Rotterdam", PostalCode: "3011", Country: "NL"},
})
if err != nil {
log.Fatal(err)
}
st, _ := ful.Status("ord-1")
fmt.Printf("sales total=%d minor units, fulfilment status=%s\n", total, st)
}Tests per context, and a test for the lines
Each context tests its own model with no other context present:
package domain
import (
"testing"
"time"
)
func TestPlaceAppliesSegmentDiscount(t *testing.T) {
c := Customer{ID: "cus-42", Segment: B2B, DiscountTier: 2}
o, err := Place("ord-1", c, []Line{{SKU: "MUG-01", Quantity: 10, UnitPriceMinor: 900}}, time.Unix(0, 0))
if err != nil {
t.Fatal(err)
}
if o.TotalMinor != 7920 { // 9000 minus 12 %
t.Fatalf("want 7920, got %d", o.TotalMinor)
}
}
func TestPlaceRejectsEmptyOrder(t *testing.T) {
if _, err := Place("ord-2", Customer{Segment: Retail}, nil, time.Now()); err != ErrEmptyOrder {
t.Fatalf("want ErrEmptyOrder, got %v", err)
}
}package domain
import "testing"
func TestShipmentLifecycle(t *testing.T) {
r := Recipient{Name: "Sara", Line1: "Main St 1", City: "Utrecht", PostalCode: "3511", Country: "NL"}
s, err := NewShipment("shp-1", "ord-1", r, []Item{{SKU: "MUG-01", Quantity: 2}})
if err != nil {
t.Fatal(err)
}
for _, want := range []Status{Picking, Packed} {
if err := s.Advance(""); err != nil || s.Status != want {
t.Fatalf("want %s, got %s (%v)", want, s.Status, err)
}
}
if err := s.Advance(""); err == nil {
t.Fatal("dispatching without tracking must fail")
}
if err := s.Advance("TRK-9"); err != nil || s.Status != Dispatched {
t.Fatalf("want dispatched, got %s (%v)", s.Status, err)
}
}
func TestUndeliverableRecipient(t *testing.T) {
_, err := NewShipment("shp-2", "ord-2", Recipient{Name: "No Address"}, []Item{{SKU: "X", Quantity: 1}})
if err != ErrUndeliverable {
t.Fatalf("want ErrUndeliverable, got %v", err)
}
}package acl
import (
"testing"
"academy/bounded-context/sales/salesapi"
)
func TestFromOrderPlacedKeepsOnlyFulfilmentTerms(t *testing.T) {
e := salesapi.OrderPlacedV1{
OrderID: "ord-7", CustomerID: "cus-1",
Lines: []salesapi.LineV1{{SKU: "MUG-01", Quantity: 2}},
ShipTo: salesapi.AddressV1{Name: "Sara", Line1: "Main St 1", City: "Utrecht", PostalCode: "3511", Country: "NL"},
}
got := FromOrderPlaced(e)
if got.SalesOrder != "ord-7" || got.Recipient.City != "Utrecht" || got.Items[0].Quantity != 2 {
t.Fatalf("unexpected translation: %+v", got)
}
}internal/ stops imports of a context's private model; the architecture test adds the rules the compiler cannot express (direction, and "the published language must not depend on the model"):
package boundedcontext
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strconv"
"strings"
"testing"
)
const mod = "academy/bounded-context/"
// rule: a file under prefix may not import any package with a forbidden prefix.
type rule struct{ under, forbidden, why string }
var rules = []rule{
{"sales/", mod + "fulfilment", "sales is upstream and must not know fulfilment"},
{"fulfilment/internal/domain", mod + "sales", "the fulfilment model speaks only its own language"},
{"sales/salesapi", mod + "sales/internal", "the published language must not leak the sales model"},
}
func TestContextBoundaries(t *testing.T) {
fset := token.NewFileSet()
err := filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return err
}
f, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
if err != nil {
return err
}
p := filepath.ToSlash(path)
for _, imp := range f.Imports {
ip, _ := strconv.Unquote(imp.Path.Value)
for _, r := range rules {
if strings.HasPrefix(p, r.under) && strings.HasPrefix(ip, r.forbidden) {
t.Errorf("%s imports %s (forbidden: %s)", p, ip, r.why)
}
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}The Go angle
- Package tree = context. A top-level directory per context in one module keeps refactoring cheap (one
go build), whileinternal/gives a hard wall. Separate modules per context (go.work) are possible, but add versioning before you need it. - Published language as its own package.
salesapihas no imports fromsales/internal; it can later be generated from a schema (JSON Schema, Protobuf, AsyncAPI) without touching the model. - No shared
modelspackage. A rootmodels/imported by every context is the god model again, in Go syntax. - Translate in one place.
acl.FromOrderPlacedis the only function that knows both vocabularies; its test is the contract test for this edge. Contract tests across services are in Service Boundaries.
Laravel
The files are under docs/snippets/ddd/bounded-context/php (Laravel 13, PHP 8.4; reviewed, not run). Each context is a module folder with its own provider, models, migrations, routes and tests. Laravel 13 Eloquent attributes are used as the docs show them: #[Connection('mysql')], #[Table(...)], #[Fillable([...])].
Wrong: the god model with cross-context relationships
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
// The god model: one Customer for Sales, Fulfilment, Billing, Identity and
// Notifications. Every relationship below crosses a context boundary, so a
// change by any team ripples through this class and the `customers` table.
class Customer extends Model
{
protected $guarded = [];
protected $hidden = ['password'];
public function orders(): HasMany { return $this->hasMany(Order::class); } // Sales
public function shipments(): HasMany { return $this->hasMany(Shipment::class); } // Fulfilment
public function invoices(): HasMany { return $this->hasMany(Invoice::class); } // Billing
public function loginAudit(): HasMany { return $this->hasMany(LoginAttempt::class); } // Identity
public function preferences(): HasOne { return $this->hasOne(MailPreference::class); } // Notifications
// Rules of three contexts in one method; "address" means two things.
public function canOrder(int $totalMinor): bool
{
return $this->status === 'active' // Identity's word
&& ($this->segment !== 'b2b' || $this->vat_number) // Billing's rule
&& $totalMinor <= $this->credit_limit // Billing's rule
&& $this->address !== null; // Fulfilment's rule, or invoice address?
}
}Right: the Sales module
<?php
namespace App\Modules\Sales;
use Illuminate\Support\ServiceProvider;
// One provider per context: it owns its routes and migrations.
// Register it in bootstrap/providers.php.
class SalesServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->loadRoutesFrom(__DIR__.'/routes/api.php');
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
}
}<?php
namespace App\Modules\Sales\Domain;
use Illuminate\Database\Eloquent\Attributes\Connection;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
// Customer in Sales: someone we sell to. No address, no password, no credit
// limit: those words belong to Fulfilment, Identity and Billing.
#[Connection('sales')]
#[Table('customers')]
#[Fillable(['id', 'segment', 'discount_tier'])]
class Customer extends Model
{
public $incrementing = false;
protected $keyType = 'string';
private const TIERS = ['retail' => [0, 2, 5, 8], 'b2b' => [5, 10, 12, 15]];
public function discountPercent(): int
{
$tiers = self::TIERS[$this->segment] ?? null;
if ($tiers === null || ! array_key_exists($this->discount_tier, $tiers)) {
throw new InvalidArgumentException("Unknown discount tier for customer {$this->id}");
}
return $tiers[$this->discount_tier];
}
}<?php
namespace App\Modules\Sales\Domain;
use Illuminate\Database\Eloquent\Attributes\Connection;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
// Relationships stay inside the context: Order -> Sales Customer is fine,
// Order -> Fulfilment Shipment would cross the boundary and is not allowed.
#[Connection('sales')]
#[Table('orders')]
#[Fillable(['id', 'customer_id', 'lines', 'total_minor', 'placed_at'])]
class Order extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected function casts(): array
{
return ['lines' => 'array', 'placed_at' => 'immutable_datetime'];
}
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
}The published language is a readonly class. It implements ShouldDispatchAfterCommit, which (Laravel 13 events docs) "instructs Laravel to not dispatch the event until the current database transaction is committed":
<?php
namespace App\Modules\Sales\Contracts;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
// Published language of Sales: plain, versioned data. No Eloquent model
// crosses the boundary; only this shape does. Dispatched after COMMIT.
final readonly class OrderPlacedV1 implements ShouldDispatchAfterCommit
{
/**
* @param list<array{sku: string, quantity: int}> $lines
* @param array{name: string, line1: string, city: string, postal_code: string, country: string, phone: string} $shipTo
*/
public function __construct(
public string $eventId,
public string $orderId,
public string $customerId,
public array $lines,
public array $shipTo,
public string $placedAt,
) {}
}<?php
namespace App\Modules\Sales\Actions;
use App\Modules\Sales\Contracts\OrderPlacedV1;
use App\Modules\Sales\Domain\Customer;
use App\Modules\Sales\Domain\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use InvalidArgumentException;
final class PlaceOrder
{
/**
* @param list<array{sku: string, quantity: int, unit_price_minor: int}> $lines
* @param array{name: string, line1: string, city: string, postal_code: string, country: string, phone: string} $shipTo
*/
public function __invoke(string $customerId, array $lines, array $shipTo): Order
{
if ($lines === []) {
throw new InvalidArgumentException('An order needs at least one line.');
}
return DB::connection('sales')->transaction(function () use ($customerId, $lines, $shipTo) {
$customer = Customer::findOrFail($customerId);
$gross = array_sum(array_map(fn (array $l) => $l['quantity'] * $l['unit_price_minor'], $lines));
$total = $gross - intdiv($gross * $customer->discountPercent(), 100);
$order = Order::create([
'id' => (string) Str::ulid(),
'customer_id' => $customer->id,
'lines' => $lines,
'total_minor' => $total,
'placed_at' => now(),
]);
// Translation at the edge, outbound: prices stay in Sales.
event(new OrderPlacedV1(
eventId: (string) Str::uuid(),
orderId: $order->id,
customerId: $customer->id,
lines: array_map(fn (array $l) => ['sku' => $l['sku'], 'quantity' => $l['quantity']], $lines),
shipTo: $shipTo,
placedAt: $order->placed_at->toIso8601String(),
));
return $order;
});
}
}<?php
use App\Modules\Sales\Actions\PlaceOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('/sales/orders', function (Request $request, PlaceOrder $placeOrder) {
$data = $request->validate([
'customer_id' => ['required', 'string'],
'lines' => ['required', 'array', 'min:1'],
'lines.*.sku' => ['required', 'string'],
'lines.*.quantity' => ['required', 'integer', 'min:1'],
'lines.*.unit_price_minor' => ['required', 'integer', 'min:0'],
'ship_to' => ['required', 'array'],
]);
$order = $placeOrder($data['customer_id'], $data['lines'], $data['ship_to']);
return response()->json(['order_id' => $order->id, 'total_minor' => $order->total_minor], 201);
});<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Runs on the `sales` connection; in PostgreSQL that connection's search_path
// is the `sales` schema, so these tables never mix with Fulfilment's.
return new class extends Migration
{
protected $connection = 'sales';
public function up(): void
{
Schema::create('customers', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('segment'); // retail | b2b
$table->unsignedTinyInteger('discount_tier')->default(0);
$table->timestamps();
});
Schema::create('orders', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('customer_id')->index();
$table->foreign('customer_id')->references('id')->on('customers');
$table->json('lines');
$table->bigInteger('total_minor');
$table->timestamp('placed_at');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('orders');
Schema::dropIfExists('customers');
}
};Right: the Fulfilment module and its edge
<?php
namespace App\Modules\Fulfilment;
use App\Modules\Fulfilment\Listeners\StartShipment;
use App\Modules\Sales\Contracts\OrderPlacedV1;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
class FulfilmentServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
// The integration edge, written down in one place.
Event::listen(OrderPlacedV1::class, StartShipment::class);
}
}<?php
namespace App\Modules\Fulfilment\Domain;
use DomainException;
// Fulfilment's view of "the customer": who receives the parcel. A value
// object, not an Eloquent model; it lives inside the Shipment row.
final readonly class Recipient
{
public function __construct(
public string $name,
public string $line1,
public string $city,
public string $postalCode,
public string $country,
public string $phone = '',
) {
if ($name === '' || $line1 === '' || $city === '' || $postalCode === '' || strlen($country) !== 2) {
throw new DomainException('Recipient address is incomplete.');
}
}
public function toArray(): array
{
return get_object_vars($this);
}
}<?php
namespace App\Modules\Fulfilment\Domain;
use DomainException;
use Illuminate\Database\Eloquent\Attributes\Connection;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
// Fulfilment never says "customer": it ships to a recipient. sales_order_id
// is a plain reference, not a belongsTo() to a Sales model.
#[Connection('fulfilment')]
#[Table('shipments')]
#[Fillable(['id', 'sales_order_id', 'recipient', 'items', 'status', 'tracking_ref'])]
class Shipment extends Model
{
public $incrementing = false;
protected $keyType = 'string';
private const NEXT = ['released' => 'picking', 'picking' => 'packed', 'packed' => 'dispatched'];
protected function casts(): array
{
return ['recipient' => 'array', 'items' => 'array'];
}
public static function start(string $salesOrderId, Recipient $recipient, array $items): self
{
if ($items === []) {
throw new DomainException("Shipment for {$salesOrderId} has no items.");
}
return new self([
'id' => 'shp-'.$salesOrderId,
'sales_order_id' => $salesOrderId,
'recipient' => $recipient->toArray(),
'items' => $items,
'status' => 'released',
]);
}
public function advance(?string $trackingRef = null): void
{
$to = self::NEXT[$this->status] ?? throw new DomainException("Cannot advance from {$this->status}.");
if ($to === 'dispatched' && ! $trackingRef) {
throw new DomainException('A tracking reference is required to dispatch.');
}
$this->status = $to;
$this->tracking_ref = $trackingRef ?? $this->tracking_ref;
}
}<?php
namespace App\Modules\Fulfilment\Acl;
use App\Modules\Fulfilment\Domain\Recipient;
use App\Modules\Sales\Contracts\OrderPlacedV1;
// The only Fulfilment class that knows Sales' published language.
final class SalesOrderTranslator
{
/** @return array{sales_order_id: string, recipient: Recipient, items: list<array{sku: string, quantity: int}>} */
public function translate(OrderPlacedV1 $event): array
{
$to = $event->shipTo;
return [
'sales_order_id' => $event->orderId,
'recipient' => new Recipient($to['name'], $to['line1'], $to['city'], $to['postal_code'], $to['country'], $to['phone'] ?? ''),
'items' => $event->lines, // sku + quantity; Sales already dropped prices
];
}
}<?php
namespace App\Modules\Fulfilment\Listeners;
use App\Modules\Fulfilment\Acl\SalesOrderTranslator;
use App\Modules\Fulfilment\Domain\Shipment;
use App\Modules\Sales\Contracts\OrderPlacedV1;
use Illuminate\Contracts\Queue\ShouldQueue;
// Queued so a Fulfilment failure never rolls back or slows a Sales order.
final class StartShipment implements ShouldQueue
{
public function __construct(private SalesOrderTranslator $translator) {}
public function handle(OrderPlacedV1 $event): void
{
$req = $this->translator->translate($event);
// Idempotent: a redelivered event finds the shipment already there.
if (Shipment::whereKey('shp-'.$req['sales_order_id'])->exists()) {
return;
}
Shipment::start($req['sales_order_id'], $req['recipient'], $req['items'])->save();
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
protected $connection = 'fulfilment';
public function up(): void
{
Schema::create('shipments', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('sales_order_id')->unique(); // a reference, no foreign key into Sales
$table->json('recipient');
$table->json('items');
$table->string('status');
$table->string('tracking_ref')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('shipments');
}
};Tests: per context, and for the lines
<?php
use App\Modules\Fulfilment\Acl\SalesOrderTranslator;
use App\Modules\Fulfilment\Domain\Recipient;
use App\Modules\Sales\Contracts\OrderPlacedV1;
// A per-context test: no database, no Sales models, only the contract.
it('turns a placed order into fulfilment terms', function () {
$event = new OrderPlacedV1(
eventId: 'evt-1',
orderId: 'ord-7',
customerId: 'cus-1',
lines: [['sku' => 'MUG-01', 'quantity' => 2]],
shipTo: ['name' => 'Sara', 'line1' => 'Main St 1', 'city' => 'Utrecht', 'postal_code' => '3511', 'country' => 'NL', 'phone' => ''],
placedAt: '2026-11-25T10:00:00+00:00',
);
$req = (new SalesOrderTranslator)->translate($event);
expect($req['sales_order_id'])->toBe('ord-7')
->and($req['recipient'])->toBeInstanceOf(Recipient::class)
->and($req['items'][0]['quantity'])->toBe(2);
});
it('rejects an undeliverable address at the edge', function () {
$event = new OrderPlacedV1('evt-2', 'ord-8', 'cus-1', [['sku' => 'X', 'quantity' => 1]],
['name' => 'No Address', 'line1' => '', 'city' => '', 'postal_code' => '', 'country' => '', 'phone' => ''], '2026-11-25T10:00:00+00:00');
(new SalesOrderTranslator)->translate($event);
})->throws(DomainException::class);<?php
// Pest architecture tests: context boundaries fail the build.
arch('sales does not know fulfilment')
->expect('App\Modules\Sales')
->not->toUse('App\Modules\Fulfilment');
arch('fulfilment sees only the published language of sales')
->expect('App\Modules\Fulfilment')
->not->toUse([
'App\Modules\Sales\Domain',
'App\Modules\Sales\Actions',
]);
arch('the sales contract is used only by sales and the fulfilment edge')
->expect('App\Modules\Sales\Contracts')
->toOnlyBeUsedIn([
'App\Modules\Sales',
'App\Modules\Fulfilment\Acl',
'App\Modules\Fulfilment\Listeners',
'App\Modules\Fulfilment\FulfilmentServiceProvider',
]);
arch('no shared god model')
->expect('App\Modules')
->not->toUse('App\Models\Customer');The Laravel angle
- No cross-context Eloquent relationships.
Order::customer()is inside Sales and fine.Shipment::order()returning a Sales model would make Fulfilment depend on Sales' table, columns and connection. Keepsales_order_idas a plain string. - A connection per context. Add
salesandfulfilmentconnections inconfig/database.php(same server, differentsearch_pathor database). The Laravel database docs: you "may access each connection via the connection method provided by the DB facade". Migrations setprotected $connection. - A provider per context.
loadRoutesFromis in the 13.x package docs;loadMigrationsFromexists in the 13.xServiceProvidersource (the docs page now showspublishesMigrationsfor packages). Register both providers inbootstrap/providers.php. - Event discovery stays local. Laravel discovers listeners in
app/Listenersby default; module listeners are registered explicitly withEvent::listenin the module's provider, which also documents the edge in one line. Alternatively->withEvents(discover: [__DIR__.'/../app/Modules/*/Listeners']). - Queued listener.
StartShipment implements ShouldQueue, so a Fulfilment failure never rolls back a Sales order. Across processes, use the outbox and an idempotent consumer.
Solving the classic problems
The god model: one Customer for every context
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Split by context | One customer type per context, linked by id | Each team changes alone | Data copied; events needed |
| Keep one table, split classes | Several models map different columns of one table | Quick first step | Table still shared: writes collide |
| Extract one context at a time | Start with the context that changes most | Low risk, visible gain | Takes months |
Steps: list every field of the god model and its users; assign each field to the one context that owns its meaning; create per-context models reading the same table first (strangler inside the app); then move columns to per-context tables and publish events for the copies.
"UserContext", "ProductContext": entity-based contexts
A context named after an entity is a table with a fence. Every use case crosses several of them, as the sizing timeline shows, and the entity's rules end up nowhere in particular.
| Symptom | Fix |
|---|---|
UserContext owns login, profile, addresses, loyalty | Split by meaning: Identity (login), Sales (customer), Fulfilment (recipient), Notifications (contact) |
ProductContext serves catalog pages and warehouse bins | Catalog (listing, media, price) vs Fulfilment (SKU, location, weight) |
OrderContext from cart to delivery | Sales (until placed) and Fulfilment (after placed), cut at the pivotal event |
Layers as contexts
"UI context", "API context", "Data context" are layers, not models. Every feature crosses all of them. Layers belong inside each context (Domain, Application & Infrastructure Services). Fowler's remark that in-memory and relational models can be separate contexts is about representation of one model, not a reason to cut the domain by layer.
One context per table
| Why it happens | Why it fails | Fix |
|---|---|---|
| Database-first design | Invariants span tables (order + lines + totals) | Group tables by invariant and language; one context owns many tables |
| "Microservice per table" | Distributed transactions for every write | Merge to context level (Aggregates & Factories for the consistency unit) |
Two contexts write the same table
Pick the owner by meaning (who decides the value?), give the other a read model fed by events, and enforce with database roles (Mechanics). Migration steps with dual-writes and CDC are in Data Ownership in Microservices and Change Data Capture.
A use case needs a transaction across two contexts
First ask whether the invariant is real and immediate. If yes, the data belongs in one context: move it. If the business accepts a delay, use events and compensation (Saga). Two-phase commit across contexts couples them in time and failure; see Distributed SQL, Consensus & 2PC for where it is legitimate.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New product, one team, unclear domain | One or two broad contexts as modules | Glossary, canvas per context, arch tests | Lines are hypotheses; keep them cheap to move |
| Same word means different things to two groups | Two contexts | Translation at the edge | Fowler: "you need a different model when the language changes" |
| Two areas share one immediate invariant | One context | Aggregate boundary inside it | Splitting creates cross-context transactions |
| Core subdomain tangled with generic plumbing | Separate contexts | ACL to the generic part | Tune: decouple high and low value |
| Legacy system you cannot change | Treat it as its own context | Bubble context + ACL | Brandolini: legacy is "chances are high" a different context |
| Regulated data (cards, health) | Its own context | Separate schema/DB, narrow interface | Smaller audit scope |
| Contexts change together constantly | Merge | Change-coupling report | Line is wrong |
| A context needs to scale one part | More services in the same context | Same model, separate deployables | A service may be smaller than a context |
| Several teams in one context | Split the context or the team's scope | Canvas per new context | Evans: the model fragments as people are added |
| Notifications, email, SMS | Thin generic context or an adapter | Buy a provider | Generic subdomain |
In architecture: from a single process to a distributed system
The same six contexts at each stage. What changes is how expensive it is to cross a line and to move one.
Monolith: one process, one database
How it shows up: contexts are top-level folders and namespaces; crossing is a function call through a facade; one database, one schema per context if you can, a table prefix if you cannot.
Simplest correct usage: even in a ten-file app, name the contexts and keep one model per context. Do not create a shared models/ folder.
Example (simple): a small shop in one Laravel app with app/Modules/Sales and app/Modules/Fulfilment; PlaceOrder dispatches OrderPlacedV1 in-process; the listener runs synchronously at first.
Example (production-shaped): a 20-person company with six contexts as modules, Pest architecture tests in CI, one canvas per context in docs/contexts/, and a CODEOWNERS line per module. Change coupling between Sales and Billing is 8%: the line is real.
Modular monolith and multiple databases
How it shows up: modules own schemas and roles, publish events, and are tested alone. This is where contexts should be proven before they are distributed (Modular Monolith).
Modular monolith, one deployable, schemas per context
1 PlaceOrder: BEGIN (sales conn) -> INSERT sales.orders -> COMMIT
2 After commit: OrderPlacedV1 dispatched; StartShipment queued
3 Worker: SalesOrderTranslator -> Recipient, items -> INSERT fulfilment.shipments (fulfilment conn)
4 Fulfilment worker down: orders still accepted; shipments catch up from the queueExample: the Go cmd/shop and the Laravel modules on this page. The Catalog context reads nothing from Sales; Notifications listens to OrderPlaced and ParcelDispatched only.
Microservices: a context becomes one or more services
What survives: the models, the published language, the translation code, the per-context tests. Only the transport changes: the event goes through an outbox to a broker topic sales.order.placed.v1.
What breaks: anything that relied on one process: an Eloquent relationship across contexts, a join across schemas, a facade call in a loop, one transaction over two contexts. If the modular stage had architecture tests, none of these exist.
sales-svc, fulfilment-svc, billing-svc, notifications-svc
1 POST /sales/orders -> sales-svc commits order + outbox row (sales DB)
2 Relay publishes sales.order.placed.v1 (event_id = idempotency key)
3 fulfilment-svc: inbox dedup -> ACL -> Shipment released (fulfilment DB)
4 billing-svc: ACL -> Invoice draft (billing DB); notifications-svc: "Thanks for your order"
5 Sales could also run sales-pricing as a second service: same context, same team, same modelExample: the running example after Sales grows to two services (API and pricing batch), both inside the Sales context; Identity is a bought IdP speaking OpenID Connect, so "Identity context" is now an external system with an ACL in each consumer.
Distributed data: replicas, caches and multi-region
| Where the context line is tested | What breaks | Design response |
|---|---|---|
| Fulfilment's copy of the ship-to address | Customer edits address after placement | Business rule: address frozen at placement; change via support |
| Sales caches Catalog prices | Price changed between page view and order | Sales owns "price at placement"; Catalog price is a hint |
| Read replica of Sales DB used by Billing reports | Billing couples to Sales' schema | Publish events into Billing's or a warehouse's own store |
| Multi-region Sales | Duplicate or reordered events at Fulfilment | Idempotent consumer, per-order ordering (Ordering & Partitioning) |
| Search index of Catalog | Index lags Catalog | Index is Catalog's read model, not a new context |
Scaling path: 1×, 10×, 100×
| Scale | Contexts | Practices |
|---|---|---|
| 1× (one team) | 2-6 contexts as modules in one app | Glossary, canvas, internal/ or Pest arch tests, schema per context |
| 10× (3-8 teams) | Each context owned by one team; some as services | Context map maintained, published languages versioned, outbox, change-coupling reviews |
| 100× (dozens of teams) | Large contexts split (Fulfilment → Warehouse, Delivery); platform contexts | Canvas reviews on contract changes, contract tests per edge, quarterly boundary health review |
Lab
Everything runs offline with Go installed (PostgreSQL optional for step 5).
Setup.
cd docs/snippets/ddd/bounded-context/go
go vet ./...
go test ./...
# ok academy/bounded-context
# ok academy/bounded-context/fulfilment/internal/acl
# ok academy/bounded-context/fulfilment/internal/domain
# ok academy/bounded-context/sales/internal/domain
go run ./cmd/shop
# sales total=7920 minor units, fulfilment status=releasedStep 1: find the contexts in the god model. Open wrong/customer.go. For each field, write the context that owns its meaning. Expected: PasswordHash Identity; Segment, DiscountTier Sales; CreditLimit, VATNumber Billing; Address, Phone ambiguous (Fulfilment or Billing); OptedOut Notifications; Status two meanings.
Step 2: hit the compiler wall. Add _ "academy/bounded-context/sales/internal/domain" to the imports of fulfilment/fulfilment.go and run go build ./.... Expected:
package academy/bounded-context/fulfilment
fulfilment/fulfilment.go:12:2: use of internal package academy/bounded-context/sales/internal/domain not allowedRevert.
Step 3: break the direction. Add _ "academy/bounded-context/fulfilment" to sales/sales.go and run go test .. Expected:
--- FAIL: TestContextBoundaries (0.00s)
arch_test.go:39: sales/sales.go imports academy/bounded-context/fulfilment (forbidden: sales is upstream and must not know fulfilment)Revert. The compiler would not complain here: fulfilment imports only sales/salesapi, so there is no import cycle. Direction is a rule only the test knows.
Step 4: change one context alone. Change the top B2B discount from 15 to 16 in sales/internal/domain/customer.go (and the expected total in order_test.go only if you change tier 2) and run go test ./.... Expected: only Sales code changed; Fulfilment tests untouched and green. Now add Weight int to fulfilment/internal/domain.Item. Expected: no Sales file changes.
Step 5: enforce the data line. In a local PostgreSQL, run the SQL from Mechanics, connect as fulfilment_ctx and run SELECT * FROM sales.orders;. Expected: ERROR: permission denied for schema sales. The grants query shows one writer per schema.
Step 6: canvas your own system. Take one module of a system you know, fill the eleven canvas sections, then count its inbound and outbound messages. Expected: if you cannot write a purpose without the word "and" three times, or the outbound list is longer than ten, it is probably two contexts.
Common misconceptions
| Belief | Reality |
|---|---|
| A bounded context is a microservice | It is a model boundary; a service sits inside one context; a context can be a module |
| Bounded context = subdomain | Problem space vs solution space; 1 : 1 is common, not required |
| One Customer class for everyone avoids duplication | It couples every context; per-context models linked by id are intended |
| Smaller contexts are better | Too small splits invariants and creates chatty calls |
| One team per context, always | One team can own several; a context should not have several owners |
| Contexts are found by clustering tables | They are found where language, events and rules change |
| The context map is designed once | Map what exists first; split and merge as you learn |
| A shared database is fine if each context has its own tables | Only if roles enforce one writer; otherwise joins and writes creep in |
| Name contexts after entities (UserContext) | Name them after a capability or language area (Sales, Fulfilment) |
| Layers (UI, API, data) can be contexts | Layers live inside each context |
| Translation is overhead | Translation at the edge keeps foreign words out of the model |
| Continuous Integration is a CI server | Evans: merge code and language often inside a context |
| Eloquent relationships across modules are harmless | They couple tables, columns and connections across the line |
Cheat sheet
| Topic | Remember |
|---|---|
| Definition | Explicit boundary within which one model is defined and applicable; one language inside |
| vs subdomain | Problem (found) vs solution (designed); 1:1, n:1, 1:n all occur |
| vs service | Context = upper limit for a service; a service never spans contexts |
| vs team | One owner per context; a team may own several |
| Heuristics | Language, pivotal events, rate of change, data owner, capability, value, team, consistency, legacy, compliance, UX |
| Canvas | Name, purpose, classification, roles, inbound, outbound, language, decisions, assumptions, metrics, open questions |
| Duplication | Same person, different models, linked by id; copy at the moment of need |
| Sizing | Large enough for one language and its invariants, no larger |
| Wrong-line signals | Cross-context transactions, shared tables, synonyms, same team in two contexts, chatty calls |
| Evolution | Split in-process first; merge when coupled; bubble + ACL next to legacy; strangler fig |
| Go | Package tree per context, internal/ model, published-language package, ACL package, arch test |
| Laravel | Module per context, provider, #[Connection] models, migrations and routes per module, Pest arch tests |
| Data | Schema + role per context, no FK across contexts, then database per context |
| Anti-patterns | Entity contexts, layer contexts, context per table, god model |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — State Evans's definition of a bounded context and name its three parts. Must-know
Answer
Answer: "A description of a boundary (typically a subsystem, or the work of a particular team) within which a particular model is defined and applicable." A boundary, one particular model, valid only inside. See definition.
2 — Give one example each of n subdomains : 1 context and 1 subdomain : n contexts from the running example. Important
Answer
Answer: Ordering + Pricing & Promotions → Sales (shared language and invariant). Fulfilment → later Warehouse + Delivery (different experts and words). See vs subdomain.
3 — Why is "a bounded context is a microservice" wrong, and what does Khononov say instead? Must-know
Answer
Answer: A context is a model boundary; it can be a module or several services. Khononov: "A Microservice is a Bounded Context, but not vice versa"; contexts give "the boundaries of the biggest services possible". See vs service.
4 — What is a pivotal event and why does it hint at a boundary? Important
Answer
Answer: One of "the few most significant events in the flow" (e.g. Order Placed). Work before and after it is usually done by different people with different words, so a context line often sits there. See heuristics.
5 — Name the canvas sections. Good to know
Answer
Answer: Name, purpose, strategic classification, domain roles, inbound communication, outbound communication, ubiquitous language, business decisions, assumptions, verification metrics, open questions. See canvas.
6 — Sales has Customer{segment, tier}, Fulfilment has Recipient{address, phone}. Is this duplication a problem? Must-know
Answer
Answer: No. They are different knowledge about the same person, linked by id. A shared class would couple both contexts. See duplication.
7 — List three signals of a wrongly drawn line. Important
Answer
Answer: Cross-context transactions, shared writable tables, synonyms inside one context, the same team always touching two contexts, chatty sync calls. See signals.
8 — A rule needs Sales orders and Billing credit limits in one transaction. What do you do? Important
Answer
Answer: Ask which context owns the rule. If it must be immediate, move the data into that context; if the business accepts a delay, Billing decides asynchronously with compensation. See cross-context transaction.
9 — How does Go enforce the model boundary, and what does it not enforce? Must-know
Answer
Answer: internal/ packages cannot be imported from outside their subtree (compiler error). It does not enforce direction between public packages; an architecture test does. See Go.
10 — Why are cross-context Eloquent relationships forbidden? Must-know
Answer
Answer: They couple one context to another's table, columns and connection, and they break as soon as the contexts get separate databases. Keep the id as a plain value. See Laravel angle.
11 — What does Evans mean by Continuous Integration inside a bounded context? Important
Answer
Answer: Merging code and artifacts frequently with tests "to flag fragmentation quickly" and exercising the language so the model does not split among people. See continuous integration.
12 — Why is "UserContext" an anti-pattern? Important
Answer
Answer: It is an entity with a fence: login, profile, addresses and loyalty have different meanings and owners, and every use case crosses it. Split by meaning: Identity, Sales, Fulfilment, Notifications. See entity contexts.
Glossary
| Term | Meaning |
|---|---|
| Bounded context | Explicit boundary within which one model is defined and applicable |
| Model | The chosen set of concepts, rules and words that solves a domain problem |
| Ubiquitous language | The team's language inside one context, used in speech and code |
| Subdomain | A part of the business problem; core, supporting or generic |
| Problem space / solution space | The business as it is / the software we design for it |
| Core / supporting / generic | Differentiating / needed but not differentiating / solved everywhere |
| Context map | Drawing of all contexts and their relationships |
| Polyseme | A word with several related meanings (meter, customer, product) |
| Homonym / synonym | One word for two things / two words for one thing |
| Pivotal event | One of the few most significant events in a flow; often a seam between contexts |
| EventStorming | Brandolini's workshop for exploring a domain with events on a timeline |
| Emerging bounded contexts | Candidate contexts visible after a Big Picture EventStorming |
| Bounded Context Canvas | DDD-crew one-page tool for designing a single context |
| Strategic classification | Domain type, business-model role and evolution stage of a context |
| Domain role | A context's behaviour type: execution, analysis, approver, gateway, bubble... |
| Inbound / outbound communication | Messages (commands, queries, events) received / sent by a context |
| Business decision | A rule or policy owned by a context |
| Verification metric | A measurement that tells whether the boundary is a good fit |
| Published language | A documented, versioned shape other contexts may depend on |
| Anticorruption layer (ACL) | Translation code at the edge that protects a model from another |
| Open host service | A context's public protocol offered to many consumers |
| Translation at the edge | Converting foreign terms into local ones at the boundary |
| Bubble context | A small clean context next to legacy, protected by an ACL |
| Strangler fig | Gradual replacement of a legacy system capability by capability |
| God model | One class or table used by every context |
| Anemic model | A model with data and no behaviour |
| Distributed monolith | Services that must still change and deploy together |
| Continuous Integration (Evans) | Frequent merging of code and language inside one context |
| Modular monolith | One deployable with enforced module (context) boundaries |
| Schema per context | One database schema and role per context, one writer |
internal package | Go directory whose packages only its parent subtree may import |
| Service provider | Laravel class that boots a module's routes, migrations and listeners |
| Architecture test | Automated check of dependency rules (Go parser test, Pest arch()) |
| Change coupling | Files or modules that change in the same commits over time |
References
- Eric Evans, Domain-Driven Design Reference, 2015: glossary "bounded context"; patterns Bounded Context, Ubiquitous Language, Continuous Integration, Context Map, Core Domain, Generic Subdomains
- Martin Fowler, "Bounded Context", 15 January 2014
- Martin Fowler, "Strangler Fig"
- Vaughn Vernon, "Getting Started with Domain-Driven Design", InformIT, 9 November 2012 (excerpt of Implementing Domain-Driven Design, chapter 1; pages 3, 4 and 6)
- Alberto Brandolini, "Strategic Domain Driven Design with Context Mapping", InfoQ, 25 November 2009
- DDD-crew, EventStorming Glossary & Cheat Sheet (pivotal events and emerging bounded contexts, citing Brandolini's Discovering Bounded Contexts with EventStorming)
- DDD-crew, The Bounded Context Canvas (v5) and its Model Traits worksheet
- DDD-crew, DDD Starter Modelling Process
- Nick Tune, "Strategic Domain-Driven Design", Agile India 2019 slides (five bounded context design heuristics)
- Team Topologies, Independent Service Heuristics
- Vladik Khononov, "Bounded Contexts are NOT Microservices", 21 January 2018; "Tackling Complexity in Microservices", 28 February 2018; "Revisiting the Basics of Domain-Driven Design", 26 January 2018
- Jan Stenberg, "Strategies for Decomposing a System into Microservices", InfoQ, 21 June 2018 (reporter's summary of Khononov's DDD eXchange 2018 talk)
- Chris Richardson, microservices.io, Decompose by subdomain, Decompose by business capability, Database per service
- Go 1.4 release notes, Internal packages
- Laravel 13 docs: Eloquent (Connection, Table, Fillable attributes), Events (ShouldDispatchAfterCommit, manual registration, discovery), Database (multiple connections), Package development (
loadRoutesFrom), Service providers;ServiceProvider.phpon 13.x (loadMigrationsFrom)