Skip to content

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 forGo to
The page in three tablesEverything in one minute
Why one big model failsWhy bounded contexts exist
Evans 2003 to the canvas and KhononovWhere it comes from
The precise definitionWhat a bounded context is
Problem space vs solution spaceBounded context vs subdomain
Module, microservice, teamContext vs module vs service vs team
How to find the linesDiscovery heuristics
Purpose, classification, roles, messages, language, decisionsThe Bounded Context Canvas
Two Customer classes on purposeModel duplication is fine
Too big, too smallSizing
Symptoms of a wrong lineSignals you got it wrong
Split, merge, strangler, bubbleEvolving boundaries
Evans's "Continuous Integration" inside a contextKeeping one context sound
Packages, providers, schemas, testsMechanics, Go, Laravel
UserContext, layers as contexts, one per tableSolving the classic problems
Which shape for which situationChoosing
Monolith to distributed dataIn architecture
Hands-onLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
Bounded contextThe fence inside which one model and one language holdInside Sales, "customer" = someone we sell toOne model with contradictory meanings
ModelThe concepts, rules and words we chose to solve a problemSales: Customer, Segment, Order, QuoteCode that matches nobody's way of thinking
Ubiquitous languageThe team's words, used in talk and in code, inside one context"Place order", "discount tier"Translation in every meeting
SubdomainA part of the business problem (found, not designed)Ordering, Fulfilment, PaymentsEffort spread evenly over core and commodity
Context mapThe drawing of all contexts and how they relateSales → Fulfilment via sales.order.placed.v1Hidden coupling between models
Translation at the edgeConverting another context's terms into ours at the boundarySales ShipTo → Fulfilment RecipientForeign words leak into our model
Bounded Context CanvasOne page that designs and documents a single contextPurpose, roles, messages, decisionsBoundaries that live only in heads

Bounded context vs its neighbours.

Is it the same as a bounded context?Relationship
SubdomainNo: problem space vs solution space1 : 1 is common; 1 subdomain : n contexts and n subdomains : 1 context both happen
MicroserviceNoA service should not span contexts; a context may be 1 or several services, or none (a module)
Module / packageCan beIn a modular monolith a context is often one top-level module
TeamNoOne team may own several contexts; one context should have one owning team
Database schemaUsually followsOne schema (or database) per context; never two contexts writing one table

Signals at a glance.

You seeIt suggestsMove
Same word, different attributes or rulesTwo contexts in one modelSplit the model, translate at the edge
Two words for one thing inside one contextSynonyms, a language that was never agreedPick one word, rename in code
Every change touches the same two contextsLine in the wrong placeMerge, or move the concept
Transaction that must cover two contextsInvariant split across the lineMove the invariant's data into one context
Two contexts write one tableThe boundary exists only on paperOne 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 modelOne model per bounded context
One Customer table with every field any team ever neededEach context keeps the customer attributes it uses
A meeting to add a columnA 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 classEach rule lives with the model that owns it
Integration is "just a join"Integration is explicit: messages, translation
Simple to startMore 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.

Sales"customer": segment, tiersales.order.placed.v1Catalog"product": title, media, SKUProductRepricedIdentity"user": login, MFA, rolescustomer_registeredBilling"account": credit, VATinvoices, paymentsFulfilment"recipient": address, phoneparcel.dispatched.v1Notifications"contact": channel, opt-outsOrderPlacedOrderPlacedOrderPlacedproduct dataregistereddispatched

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 ​

  1. "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.
  2. "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.
  3. "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.

text
     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 context

What 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:

PartMeaningConsequence
"a boundary"A line that has an inside and an outsideYou must be able to say whether a class, table or word is inside
"a particular model"One consistent set of concepts and rulesNo two meanings for one word inside
"defined and applicable"The model is valid only insideOutside, 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.

ContextWhy it is its own contextHeuristics that draw the lineIts word for the person
SalesOrdering and pricing share one language and the invariant "price fixed at placement"Language, consistency, business value (core)Customer
FulfilmentPickers and dispatchers talk about shipments, bins and parcels, never prices; their work starts after the pivotal event OrderPlacedPivotal event, language, rate of changeRecipient
BillingInvoices, tax and payment providers change with law, not with checkout; payment data is regulatedCompliance, data ownership, external system edgeAccount
CatalogMerchandisers curate listings, media and copy on their own scheduleBusiness capability, team ownership, rate of change(none; it talks about products)
IdentityLogin, MFA and roles are a solved problem, bought as a product, with security rules of their ownBusiness value (generic), complianceUser
NotificationsChannels, templates and opt-outs; it reacts to others' events and owns none of their decisionsBusiness 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."

text
     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 fence

Real 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.

ElementInside the contextOutside
WordsOne meaning eachMay mean something else
Classes / typesFree to useNot imported; use published shapes
TablesOwned and writtenNot read directly
Rules (invariants)Enforced hereNot duplicated elsewhere
TeamOne ownerOthers 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:

ShapeRunning exampleWhy it happens
1 subdomain : 1 contextCatalog subdomain → Catalog contextSimplest; same experts, same language
n subdomains : 1 contextOrdering + Pricing & Promotions → SalesOne language and one invariant ("the price is fixed when the order is placed") span both
1 subdomain : n contextsFulfilment → later Warehouse and DeliveryTwo groups of experts use different words (bin, pick list vs route, slot, proof of delivery)
Subdomain with no context of oursPayments → external provider wrapped by BillingGeneric: buy it, translate at the edge
Problem space: subdomains (discovered in the business)Solution space (above): bounded contexts, designed by usOrderingcorePricing &PromotionscoreFulfilmentcore or supportingCatalogsupportingBilling &InvoicingsupportingPaymentsgenericIdentity &AccessgenericNotificationsgenericSales1 context, 2 subdomains:same language, one invariant(price fixed at placement)Fulfilment1 subdomain,WarehouseDelivery(future split)Catalog1 : 1Billing2 subdomains;payments viaprovider + ACLIdentitybought IdP(OIDC)Notificationsthin context foremail, SMSpayment provider(external)

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.

text
     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 did

Real 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:

UnitWhat it boundsRule against a context
Module (package, namespace)Code visibilityA context is usually one top-level module; a module never spans two contexts
Microservice (deployable)Process, deploy, failureA service sits inside one context; a context may have 1..n services
TeamOwnership, communicationA team owns 1..n contexts; a context has one owning team
Database schemaData and its writerOne schema per context; split further per service if needed
text
     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:

HeuristicAskSuggests a line whenSource
Language changesDoes the word mean something else here?Same word, different attributes or rules; different expertsEvans, Fowler, Tune ("Align with domain language")
Pivotal eventsWhich few events change the phase of the process?Before/after a pivotal event, different people careBrandolini via DDD-crew glossary
Lifecycle / rate of changeDoes this part change weekly while that one is stable?Promotions rules weekly vs order capture yearlyBrandolini: "different evolutionary forces"
Data ownershipWho is the single writer of this record?Two groups write the same data for different reasonsmicroservices.io database per service; Data Ownership
Business capabilityWhat does the business do, as a verb?Distinct capabilities with distinct ownersmicroservices.io decompose by business capability
Business valueIs this core, supporting or generic?Core logic tangled with commodityTune ("Align with business value"; "Decouple high value and low value parts")
Team ownershipWho would own it? Can one team hold it in its head?A model needs two teams to changeTune ("Optimise for social needs"), Team Topologies
Consistency requirementsWhich data must change atomically together?Data that need not be consistent at onceKhononov via InfoQ ("Use consistency requirements ...")
Legacy system edgesIs there a system whose model we cannot change?Always: the legacy model is a contextBrandolini: "chances are high that this will be in a different bounded context"
Compliance / securityIs this data regulated?Card data, health data, personal data with its own rulesTune ("Respect technical constraints": legacy, security, storage)
UXWill the user see seams?A split would fragment one screen into five callsTune ("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.

text
     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 it

Real 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.

text
     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?
1. Name: Sales2. Purpose: turn shoppers into confirmed, correctly priced orders (business language, no tech).3. Strategic classificationDomain: coreBusiness model: revenue generatorEvolution: custom built4. Domain rolesExecution model (runs checkout)Approver (accepts or rejectsan order against price rules)7. Ubiquitous languageCustomer = someone we sell toSegment, Discount Tier, QuoteOrder, Order Line, Cart(no Address, no Shipment, no Invoice)5. Inbound communicationStorefront: PlaceOrder, Quote (cmd)Catalog: ProductRepriced (event)Identity: CustomerRegistered (event)relationships: customer/supplier,conformist to IdentitySales modelCustomer {id, segment, tier}Order {lines, total}Quote {expiresAt}owns schema sales;team: Checkout6. Outbound communicationsales.order.placed.v1 (event) toFulfilment, Billing, Notificationssales.order.cancelled.v1 (event)open host service +published language8. Business decisionsDiscount by segment and tierAn order needs 1+ linesA quote expires after 15 minPrice is fixed at placement9. AssumptionsB2B stays under 30% of ordersFulfilment never needs pricesOne currency per order10. Verification metrics% of PRs touching only salessync cross-context calls per checkoutcontract changes per month11. Open questionsWho owns returns: Sales or Fulfilment?

Sales and Fulfilment, side by side (the Sales card is the diagram above):

SectionSalesFulfilment
PurposeTurn shoppers into confirmed, correctly priced ordersGet every placed order to the recipient complete and on the promised day
Classification: domainCore (ordering, pricing)Core or supporting (the delivery promise; see Domains & Subdomains)
Classification: business modelRevenue generatorEngagement creator (the promise brings customers back)
Classification: evolutionCustom builtCustom built (warehouse software for parts is a product)
Domain rolesExecution model, approverExecution model
InboundPlaceOrder, Quote (commands from Storefront); ProductRepriced (Catalog); CustomerRegistered (Identity)sales.order.placed.v1, sales.order.cancelled.v1 (events from Sales); SkuCreated (Catalog)
Outboundsales.order.placed.v1, sales.order.cancelled.v1fulfilment.parcel.dispatched.v1, fulfilment.order.delivered.v1
Ubiquitous languageCustomer, Segment, Discount Tier, Quote, Order, Order LineShipment, Recipient, Pick List, Parcel, Tracking Ref, released / picking / packed / dispatched
Business decisionsDiscount by segment and tier; an order needs at least one line; quote valid 15 minutes; price fixed at placementA shipment needs a deliverable recipient; dispatch needs a tracking reference; cut-off 16:00 for same-day
AssumptionsB2B stays under 30% of orders; Fulfilment never needs pricesOne 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 questionsWho 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 questionBad answerGood answer
Purpose"CRUD for orders"Business outcome in business words
Outbound25 message typesA handful of coarse, named events
LanguageGeneric nouns: Data, Item, InfoWords the experts use
MetricsNoneSomething 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."

ConceptSalesFulfilmentBillingIdentityNotifications
The personCustomer {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 bycustomer_idsales_order_id → address copied at placementcustomer_iduser_id = customer_idcustomer_id
Changes whenSegment rules changeCourier needs changeTax law changesSecurity policy changesMessaging law changes
text
     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 silently

Real 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 bigAbout rightToo smallOne model for the whole shopGod Customer with 40 fields"Order" means 3 thingsEvery team edits the modelMerge conflicts, slow reviewsRules leak between areasEvans: the model fragmentsOne consistent languageInvariants kept insideOne owning teamMost changes stay insideSmall published interfaceFew, coarse messages outVernon: "large enough only ... and no larger"One context per entity/tableChatty sync calls per use caseAnemic CRUD modelsOne invariant split in twoDistributed transactionsSame team touches 3 contextsKhononov: distributed monolithfewer, larger contextsmore, smaller contextsAmbiguity, synonyms, unrelated rules in one place: split.Lockstep changes, cross-context transactions, chatty calls: merge.
text
     "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
SymptomToo bigToo small
LanguageWords with several meaningsSame word, same meaning, in several contexts
ChangeMany teams edit one modelOne change edits several contexts
CallsIn-process, unboundedMany sync calls per use case
ModelsGod classesAnemic data holders
TransactionsHuge, cover unrelated rulesNeeded across contexts
TeamToo many people per modelOne 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:

SignalHow to see itUsual causeMove
Constant cross-context transactionsA use case needs both contexts' tables in one COMMITAn invariant was splitMove the invariant's data into one context
Shared tablesMore than one context's role can write a tableLine drawn on paper onlyOne writer; others read events or copies
Synonyms inside one contextCode says client, customer and buyer for one thingLanguage never agreedPick one word (Ubiquitous Language)
Homonyms inside one contextstatus means two state machinesTwo models in oneSplit
Same team always touches two contextsChange coupling in git > 30%Line in the wrong place or a missing conceptMerge or move the concept
A context imports another's internalsArchitecture test fails, internal errorShortcut takenPublish a contract, translate
Long chains of sync callsTrace depth per requestContexts too smallMerge, or replicate data
text
     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 needed

Real 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:

MoveWhenHow, safely
SplitNew language appears inside one context; two teams fight over one modelSplit the model in-process first (two modules, translation between them), then the schema, then deployment
MergeChange coupling high, cross-context transactions, one team owns bothMerge the modules; keep one language; drop the translation
Bubble contextA clean model is needed next to a legacy systemA small new context with its own model and an anticorruption layer to legacy (Fowler links Evans's "bubble context")
Strangler figReplace a legacy context graduallyRoute capability by capability to the new context (Strangler Fig)
text
     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 step

Real 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."

text
     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
PracticeProtects against
Trunk-based or short-lived branchesParallel models in long branches
Tests named in the domain languageRules changing meaning unnoticed
Glossary in the repo, reviewed in PRsSynonyms 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 ​

text
     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 transactions

Code layout: one tree per context Must-know ​

ConcernGoLaravel 13
Context rootsales/, fulfilment/ top-level packages in one moduleapp/Modules/Sales, app/Modules/Fulfilment
Private modelsales/internal/domain: the go command refuses imports from outside sales/Domain/ namespace; Pest arch() forbids use from other modules
Published languagesales/salesapi: plain structs, versioned namesContracts/OrderPlacedV1 readonly class
Translation at the edgefulfilment/internal/aclFulfilment/Acl/SalesOrderTranslator
Wiringcmd/shop/main.goSalesServiceProvider, FulfilmentServiceProvider in bootstrap/providers.php
PersistenceRepository per context, own schema#[Connection('sales')] models, migrations per module via loadMigrationsFrom
Routeshttp.ServeMux patterns per contextloadRoutesFrom per module
Testsgo 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.

sql
-- 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 ​

WhereMessageMeaning
Go builduse of internal package academy/bounded-context/sales/internal/domain not allowedFulfilment 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
PostgreSQLERROR: permission denied for schema sales (SQLSTATE 42501)Fulfilment's role read Sales tables
MySQLERROR 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 namespaceModule 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:

go
// 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:

go
// 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
}
go
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:

go
// 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"`
}
go
// 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:

go
// 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
}
go
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:

go
// 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
}
go
// 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 ​

go
// 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:

go
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)
	}
}
go
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)
	}
}
go
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"):

go
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), while internal/ 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. salesapi has no imports from sales/internal; it can later be generated from a schema (JSON Schema, Protobuf, AsyncAPI) without touching the model.
  • No shared models package. A root models/ imported by every context is the god model again, in Go syntax.
  • Translate in one place. acl.FromOrderPlaced is 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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. Keep sales_order_id as a plain string.
  • A connection per context. Add sales and fulfilment connections in config/database.php (same server, different search_path or database). The Laravel database docs: you "may access each connection via the connection method provided by the DB facade". Migrations set protected $connection.
  • A provider per context. loadRoutesFrom is in the 13.x package docs; loadMigrationsFrom exists in the 13.x ServiceProvider source (the docs page now shows publishesMigrations for packages). Register both providers in bootstrap/providers.php.
  • Event discovery stays local. Laravel discovers listeners in app/Listeners by default; module listeners are registered explicitly with Event::listen in 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 ​

SolutionHowAdvantageCost
Split by contextOne customer type per context, linked by idEach team changes aloneData copied; events needed
Keep one table, split classesSeveral models map different columns of one tableQuick first stepTable still shared: writes collide
Extract one context at a timeStart with the context that changes mostLow risk, visible gainTakes 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.

SymptomFix
UserContext owns login, profile, addresses, loyaltySplit by meaning: Identity (login), Sales (customer), Fulfilment (recipient), Notifications (contact)
ProductContext serves catalog pages and warehouse binsCatalog (listing, media, price) vs Fulfilment (SKU, location, weight)
OrderContext from cart to deliverySales (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 happensWhy it failsFix
Database-first designInvariants span tables (order + lines + totals)Group tables by invariant and language; one context owns many tables
"Microservice per table"Distributed transactions for every writeMerge 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 ​

SituationRecommendationExtra techniqueReason
New product, one team, unclear domainOne or two broad contexts as modulesGlossary, canvas per context, arch testsLines are hypotheses; keep them cheap to move
Same word means different things to two groupsTwo contextsTranslation at the edgeFowler: "you need a different model when the language changes"
Two areas share one immediate invariantOne contextAggregate boundary inside itSplitting creates cross-context transactions
Core subdomain tangled with generic plumbingSeparate contextsACL to the generic partTune: decouple high and low value
Legacy system you cannot changeTreat it as its own contextBubble context + ACLBrandolini: legacy is "chances are high" a different context
Regulated data (cards, health)Its own contextSeparate schema/DB, narrow interfaceSmaller audit scope
Contexts change together constantlyMergeChange-coupling reportLine is wrong
A context needs to scale one partMore services in the same contextSame model, separate deployablesA service may be smaller than a context
Several teams in one contextSplit the context or the team's scopeCanvas per new contextEvans: the model fragments as people are added
Notifications, email, SMSThin generic context or an adapterBuy a providerGeneric 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).

text
     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 queue

Example: 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.

text
     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 model

Example: 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 testedWhat breaksDesign response
Fulfilment's copy of the ship-to addressCustomer edits address after placementBusiness rule: address frozen at placement; change via support
Sales caches Catalog pricesPrice changed between page view and orderSales owns "price at placement"; Catalog price is a hint
Read replica of Sales DB used by Billing reportsBilling couples to Sales' schemaPublish events into Billing's or a warehouse's own store
Multi-region SalesDuplicate or reordered events at FulfilmentIdempotent consumer, per-order ordering (Ordering & Partitioning)
Search index of CatalogIndex lags CatalogIndex is Catalog's read model, not a new context

Scaling path: 1×, 10×, 100× ​

ScaleContextsPractices
1× (one team)2-6 contexts as modules in one appGlossary, canvas, internal/ or Pest arch tests, schema per context
10× (3-8 teams)Each context owned by one team; some as servicesContext map maintained, published languages versioned, outbox, change-coupling reviews
100× (dozens of teams)Large contexts split (Fulfilment → Warehouse, Delivery); platform contextsCanvas 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.

bash
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=released

Step 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:

text
package academy/bounded-context/fulfilment
	fulfilment/fulfilment.go:12:2: use of internal package academy/bounded-context/sales/internal/domain not allowed

Revert.

Step 3: break the direction. Add _ "academy/bounded-context/fulfilment" to sales/sales.go and run go test .. Expected:

text
--- 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 ​

BeliefReality
A bounded context is a microserviceIt is a model boundary; a service sits inside one context; a context can be a module
Bounded context = subdomainProblem space vs solution space; 1 : 1 is common, not required
One Customer class for everyone avoids duplicationIt couples every context; per-context models linked by id are intended
Smaller contexts are betterToo small splits invariants and creates chatty calls
One team per context, alwaysOne team can own several; a context should not have several owners
Contexts are found by clustering tablesThey are found where language, events and rules change
The context map is designed onceMap what exists first; split and merge as you learn
A shared database is fine if each context has its own tablesOnly 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 contextsLayers live inside each context
Translation is overheadTranslation at the edge keeps foreign words out of the model
Continuous Integration is a CI serverEvans: merge code and language often inside a context
Eloquent relationships across modules are harmlessThey couple tables, columns and connections across the line

Cheat sheet ​

TopicRemember
DefinitionExplicit boundary within which one model is defined and applicable; one language inside
vs subdomainProblem (found) vs solution (designed); 1:1, n:1, 1:n all occur
vs serviceContext = upper limit for a service; a service never spans contexts
vs teamOne owner per context; a team may own several
HeuristicsLanguage, pivotal events, rate of change, data owner, capability, value, team, consistency, legacy, compliance, UX
CanvasName, purpose, classification, roles, inbound, outbound, language, decisions, assumptions, metrics, open questions
DuplicationSame person, different models, linked by id; copy at the moment of need
SizingLarge enough for one language and its invariants, no larger
Wrong-line signalsCross-context transactions, shared tables, synonyms, same team in two contexts, chatty calls
EvolutionSplit in-process first; merge when coupled; bubble + ACL next to legacy; strangler fig
GoPackage tree per context, internal/ model, published-language package, ACL package, arch test
LaravelModule per context, provider, #[Connection] models, migrations and routes per module, Pest arch tests
DataSchema + role per context, no FK across contexts, then database per context
Anti-patternsEntity contexts, layer contexts, context per table, god model

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Bounded contextExplicit boundary within which one model is defined and applicable
ModelThe chosen set of concepts, rules and words that solves a domain problem
Ubiquitous languageThe team's language inside one context, used in speech and code
SubdomainA part of the business problem; core, supporting or generic
Problem space / solution spaceThe business as it is / the software we design for it
Core / supporting / genericDifferentiating / needed but not differentiating / solved everywhere
Context mapDrawing of all contexts and their relationships
PolysemeA word with several related meanings (meter, customer, product)
Homonym / synonymOne word for two things / two words for one thing
Pivotal eventOne of the few most significant events in a flow; often a seam between contexts
EventStormingBrandolini's workshop for exploring a domain with events on a timeline
Emerging bounded contextsCandidate contexts visible after a Big Picture EventStorming
Bounded Context CanvasDDD-crew one-page tool for designing a single context
Strategic classificationDomain type, business-model role and evolution stage of a context
Domain roleA context's behaviour type: execution, analysis, approver, gateway, bubble...
Inbound / outbound communicationMessages (commands, queries, events) received / sent by a context
Business decisionA rule or policy owned by a context
Verification metricA measurement that tells whether the boundary is a good fit
Published languageA documented, versioned shape other contexts may depend on
Anticorruption layer (ACL)Translation code at the edge that protects a model from another
Open host serviceA context's public protocol offered to many consumers
Translation at the edgeConverting foreign terms into local ones at the boundary
Bubble contextA small clean context next to legacy, protected by an ACL
Strangler figGradual replacement of a legacy system capability by capability
God modelOne class or table used by every context
Anemic modelA model with data and no behaviour
Distributed monolithServices that must still change and deploy together
Continuous Integration (Evans)Frequent merging of code and language inside one context
Modular monolithOne deployable with enforced module (context) boundaries
Schema per contextOne database schema and role per context, one writer
internal packageGo directory whose packages only its parent subtree may import
Service providerLaravel class that boots a module's routes, migrations and listeners
Architecture testAutomated check of dependency rules (Go parser test, Pest arch())
Change couplingFiles or modules that change in the same commits over time

References ​

Built by Morteza Negahi