Domain-Driven Design: Bounded Contexts—how to define domain boundaries and build independent models.
Learn to define model and vocabulary boundaries across catalog, sales, inventory, and billing. Distinguish contexts, subdomains, and modules, design explicit contracts, and use these boundaries to guide AI-generated code without requiring microservices.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
When “product” starts to mean four things
Imagine a store selling a backpack. For catalog, the product needs a description, photographs, and a publication status. For sales, what matters is what can be purchased and under what conditions. Inventory works with available units and reservations. Billing needs to describe what was sold and retain the amounts and tax details of the issued document.
At first, everything fits in a Product class. Then optional fields, conditional validations, and methods that ask who is calling them start appearing. Changing the backpack's commercial name ends up changing what a historical invoice displays. The problem is no longer a missing folder: several interpretations of the business are competing within the same model.
In this article, we will separate those interpretations. We will keep catalog, sales, inventory, and billing within a Node.js application, without introducing microservices. The result will be proposed boundaries, small models, and an explicit contract that enables collaboration without sharing every class.
What a Bounded Context defines
A Bounded Context establishes where a model is valid and what its terms mean. Within that boundary, people and code should be able to use the model's language without contradictions. Outside it, the same word may have another meaning. This delineation and the explicit relationship between models are part of DDD's strategic design. Martin Fowler: Bounded Context.
For our store, “available” needs a qualifier:
Catalog: visible to visitors.
Sales: enabled to accept new purchases.
Inventory: with units that can be reserved.
Billing: this is not a relevant product status; what matters is the documented transaction.
A backpack can be published, temporarily blocked for new sales, and still have physical units in stock. None of those situations, by itself, invalidates previous invoices.
A context is not defined by counting tables or screens. It is recognized by providing a coherent interpretation of a set of decisions. The aggregates you already know protect rules within that model; they do not automatically turn each aggregate into a separate context.
Nor is it an isolated bubble. Separating models requires deciding what information crosses the boundary, what it means, and who is responsible for it.
Domain, Subdomain, Bounded Context, and Module
These four questions help distinguish them:
Domain: what activity or problem are we addressing? In this example, running an e-commerce business. The scope depends on the project: the same organization might be studying only its returns operation.
Subdomain: which part of the business problem are we analyzing? Managing stock or issuing billing documents are capabilities we can study within that domain. They do not appear because someone created a folder.
Bounded Context: where does a particular model apply? Our inventory context decides how to represent stock and reservations. This is a modeling and responsibility decision, informed by the business, the people, and the existing system.
Module: how do we organize concepts within that model? Inventory might contain reservation and adjustment modules. They would share the meaning of their concepts, even while grouping different behaviors.
The practical distinction is between the problem we observe and the model we use to address it. Do not force a permanent one-to-one correspondence between a subdomain and a context: a legacy system may mix capabilities you want to separate, and the same capability may be represented in several systems.
That is why src/modules/product does not demonstrate that a product context exists. It may simply concentrate operations from four incompatible models. Likewise, two directories do not prove that their models are independent if both modify the same global entity.
How to propose boundaries based on evidence
Before writing interfaces, bring together the people who make the process decisions. As a design exercise for this store, we will work through four steps.
1. Walk through a specific transaction
A customer opens the backpack's product page, confirms a purchase, obtains a reservation for units, and requests an invoice. Record what decision occurs at each step and who can explain its rules.
Avoid starting with “we need four services.” We do not yet know whether four models make sense.
2. Look for changes in meaning and authority
Ask what happens when someone changes a description, cancels an order, or corrects their address. In our example, we agree that:
Catalog maintains the product's current presentation.
Sales retains the terms accepted in the order.
Inventory decides whether it can reserve a quantity.
Billing retains the representation of the issued document according to its rules.
These are decisions for the example, not a universal division for every store.
3. Test awkward situations
An issued invoice should not change because catalog updates a title. A reservation should not be approved simply because the product page is visible. If you need to inspect every other model's internal state to explain each decision, revisit the boundary or the contract.
Also ask whether two responsibilities share a rule that must be resolved atomically. Do not split it without designing how it will be preserved. Conceptual independence alone does not solve transaction coordination.
4. Write a brief description for each context
For example:
Inventory. Makes decisions about reservable stock. Uses SKU, location, quantity, and reservation. Does not determine prices or write commercial descriptions. Exposes a reservation request and its result. The rules belong to the team responsible for warehouse operations.
This description lets you discuss the boundary before investing in infrastructure. Review it against real cases and exceptions; an organizational chart or a list of nouns is not enough to validate it.
Microsoft's documentation proposes an iterative analysis of capabilities and models, and shows how different representations can serve different needs. It supports the conversation; it is not an algorithm that discovers boundaries automatically. Domain analysis.
Main example: separating models while preserving collaboration
The function takes the current price to describe an earlier sale. In addition, the single name forces a decision about whether it is the advertising title or the document's description.
Adding more optional properties may hide the conflict, but it does not clarify who decides each value or when that value becomes fixed.
Four representations with different purposes
The following block is a design snippet: it defines independent types; it does not implement persistence or the full purchase workflow.
These are not four copies that must synchronize all their fields. Each answers a different question. Sales stores what was accepted; catalog continues evolving. Inventory does not need the price to decide how many units it can reserve.
Do not assume that productId and SKU are interchangeable either. A size variant may have its own SKU; a commercial bundle might require several different units. That mapping deserves an explicit agreement.
Customer and Order also change meaning
In sales, Customer might represent the person making purchases and their commercial terms. In billing, the document's recipient requires the details relevant to issuing it. Sharing an identifier does not require sharing a class or all personal data.
The same caution applies to Order. A sales order expresses commercial commitments. Inventory can work with a reservation linked to its reference; billing can issue one or more related documents. It does not need to import the sales aggregate to understand those facts.
When information is missing, ask what decision the consumer needs to make. Sending the whole object “just in case” creates coupling to its internal structure and may expose unnecessary data.
The boundary becomes visible in a contract
Suppose we have a limited need: preparing a billing preview from the terms confirmed in sales. We are not calculating taxes or issuing a tax document.
In this contract, EUR amounts are expressed in cents: 3500 represents 35 euros. In a real system, explicitly define units and rounding for each currency; do not infer that all currencies use two decimal places operationally.
The contract promises the terms of a confirmed sale. It does not promise the structure of Order, the current catalog price, or how the order is stored.
Billing defines its own read port. This block is self-contained as a TypeScript example; it uses an in-memory test double and its own assertions, without external libraries. It does not make HTTP requests or constitute a production-ready integration.
The relevant decision is what prepareBillingPreview knows: a consumer representation, without importing internal sales classes. The double demonstrates what it needs to work and what result we expect; it does not test HTTP compatibility.
In a real implementation, an HTTP adapter translates and validates the external response before returning ConfirmedSaleSnapshot. It must check structure, identity, quantities, currency, and amounts, as well as handle errors. That translation is an initial example of protecting the consumer model.
Here we assume safe integer amounts and valid inputs supplied by the double. Before production, we need numeric limits, contract validation, and adapter tests. We have not implemented tax document issuance, taxes, persistence, or stock reservations.
The directory communicates an intention; independence is verified through dependencies. In this proposal, billing uses its port and an HTTP adapter with a consumer contract. It does not import the repository, aggregate, or internal sales entities. That HTTP call may target the same application.
This is a deliberate choice in the example to make the contract visible. It does not mean every monolith needs internal HTTP calls. Other designs use public in-process interfaces, provided the collaboration does not allow bypassing the other model's rules.
A Bounded Context can live within a modular monolith. Extracting it into a service adds operational and communication decisions that must be justified. Having four processes with the same global class and unrestricted access to the same tables does not produce four independent models either.
If they share a database instance, agree on data ownership: billing should not update sales tables directly. An HTTP call does not automatically participate in the consumer's local transaction.
For our preview, we only read a confirmed sale. If we later wanted to coordinate payment collection, reservation, and issuance, we would need to design their failures and commitments separately. The contract does not guarantee that everything happens or rolls back together.
From Domain Event to integration contract
Sales can record an internal OrderConfirmed. Its structure may be useful to its own model without being suitable for external consumers.
If billing needs to know about that fact, define what information it needs and agree on an integration contract. It can contain identifiers and accepted terms, with an explicit version and meaning. Translating the event avoids accidentally publishing all the aggregate's internal details.
An internal change should not automatically force all consumers to modify their code. Conversely, a public contract is not immutable forever: it requires compatibility and coordination as it evolves.
What matters here is recognizing the boundary. Transport, publication, and failure recovery belong to another level of design.
A Context Map that supports discussion
A Context Map shows contexts, their relationships, and the agreements that shape their collaboration. It is more than a drawing of network requests. It can reflect who provides information and who must adapt.
Each arrow represents a contract to discuss. For the first, we must clarify whether the price comes from catalog or another owner. For the second, how commercial lines relate to SKUs. For the last, which terms become fixed for billing.
The arrows show information, not a complete timeline. For each relationship, it is useful to record ownership, meaning, and negotiating power.
These names introduce alternatives without implementing them yet:
Anti-Corruption Layer: translation that protects the consumer model from external concepts.
Shared Kernel: a small part of the model deliberately shared, with coordinated changes.
Customer/Supplier: a relationship where the consumer team participates in the supplier's planning.
Published Language: a documented exchange language that both sides can interpret.
These are not four mutually exclusive arrow types: they describe different aspects and can be combined. A supplier can offer a published language while the consumer maintains its own translation. Sharing a utility package does not, by itself, amount to sharing a model. Eric Evans: DDD Reference, Context Mapping section.
Two situations that change the decision
Education: enrolled student and assessed person
An educational platform needs to enable access to a course and record grades. If academic rules and their owners differ from those of enrollment, we can propose separate models: an enrollment enables participation; an academic record stores results.
The integration transmits the enrollment reference and the course, not a Student entity with unrestricted access to all grades. This example teaches separation based on decisions and confidentiality, not people's names.
But if the platform merely lists courses and records enrollments, creating an assessment context without that need would introduce complexity prematurely.
Reservations: when splitting makes a rule harder
A small application reserves rooms by time slot. If availability and reservation are two sides of the same rule—do not accept two overlapping reservations—starting with a single model may be clearest.
Separating them into contexts simply because there are two screens creates additional coordination work. The lesson is to retain a unified decision when there is not yet evidence of distinct models.
If an external scheduling system later appears with a different interpretation of availability, that new problem may indeed justify a boundary and translation.
How to keep AI from erasing boundaries
Giving an AI a folder named billing does not explain what billing means. Specify which decisions belong to the context, which contracts it consumes, and which concepts it must not import.
You can use these prompts as starting points:
To analyze boundaries:
Analyze this purchase workflow and these examples of exceptions. Propose contexts based on vocabulary, rules, and owners. Distinguish observed facts from hypotheses. Provide a description for each context and three questions for validating the boundaries with the business. Do not propose microservices or turn every entity into a context.
To implement collaboration:
Work only on billing. Consume the confirmed sale through the consumer's port and an HTTP adapter. Do not import sales entities or repositories. Define monetary units and contract errors. Provide small snippets and separate external validation from local decisions; do not implement tax document issuance.
To review:
Review this diff for global models, cross-context imports, writes to data owned by others, and confusion between current price and accepted price. Point to concrete evidence and the affected behavior. Propose the smallest correction; do not recommend distributing services without justification.
A person must then verify that the contract represents the real agreement, that the shared information is necessary, and that dependencies respect the boundary. Generated code does not replace that conversation.
Exercises for applying boundaries
1. Changing the description
Catalog renames “Mochila urbana” to “Mochila urbana 2027.” A previous invoice changes too because it reads the current title. What would you review?
2. The product warehouse
A team proposes a separate context for each entity: Product, Customer, and Order. What information is missing before accepting that division?
3. The quick integration
Billing imports SalesOrderRepository to calculate a preview. Another developer proposes replacing the import with HTTP, sending the entire serialized aggregate. Does the second solution solve the problem?
Reasoned solutions
1. I would review which representation the document retains and what description was accepted for that transaction. The invoice must not accidentally depend on a presentation that changes. This may require retaining historical data in the owning model and translating the sale terms when preparing the document; it does not require copying the entire catalog.
2. Decisions, meanings, shared rules, and owners are missing. Entities can collaborate within the same context. I would test the purchase workflow and its exceptions to discover where the model truly changes, including which rules need to stay together.
3. HTTP avoids the direct import, but transporting the entire aggregate maintains a dependency on its structure. The correction is to define what billing needs, agree on the contract, and translate it into the consumer model. The response must also be validated, and we must recognize that the call does not create a shared transaction.
What to check before adopting a boundary
A useful boundary lets you explain what each context decides, what its words mean, and what it needs from the others. Test the proposal with a normal transaction and an exception: can you change a local rule without reinterpreting every model?
If separation only adds folders, empty contracts, or remote steps around the same decision, simplify it. If it prevents commercial presentation, stock, and historical documents from competing inside a global class, it is adding clarity.
The goal is to preserve coherent models and make their collaboration explicit. Deployment can remain a single unit for as long as that is the appropriate option.
Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.