Context Maps & Integration Patterns: Partnership, Shared Kernel, Customer-Supplier, Conformist, ACL, OHS/PL, Separate Ways
"Describe the points of contact between the models, outlining explicit translation for any communication, highlighting any sharing, isolation mechanisms, and levels of influence. Map the existing terrain. Take up transformations later." — Eric Evans, Domain-Driven Design Reference (2015), "Context Map"
Summary: A context map is a drawing of today's reality: which bounded contexts exist, who depends on whom, whose model wins at each edge, and who pays for translation. The patterns (Partnership, Shared Kernel, Customer-Supplier, Conformist, Anticorruption Layer, Open Host Service, Published Language, Separate Ways, Big Ball of Mud) are names for those relationships. Focus: Upstream and downstream as power, each of the nine patterns in depth (when it happens, team dynamics, cost, code shape, risks, how to leave it), the U/D notation from the DDD-crew cheat sheet and Context Mapper, communication types on the map, the team overlay, evolving a map, maps inside a modular monolith, and the running example's map with Go and Laravel code: an ACL in front of a legacy ERP, an Open Host Service with a published event contract, a conformist consumer, a versioned shared kernel and contract tests across the edge. Learning goal: Draw the context map of a real system with correct notation, name the relationship and its cost on every edge, choose the right pattern for a new integration, and implement the ACL, OHS/PL and shared kernel so the choice is enforced by code and tests, not by good intentions.
This chapter closes group DD 01 (Strategic Design). It assumes you can find a bounded context and know why each one has its own ubiquitous language; it uses the subdomain types (core, supporting, generic) to decide where to invest. It owns the question how do two contexts relate, and on whose terms? Neighbours own the rest: where service lines go and what they cost (Service Boundaries), how bytes travel (Service Communication), who owns which tables (Data Ownership in Microservices), reliable publishing (Transactional Outbox), event vs integration event (Domain Events vs Integration Events), and schema evolution (Message Design & Schema Evolution).
Page map
| If you are looking for | Go to |
|---|---|
| The whole chapter in three tables | Everything in one minute |
| Why a map, and why "today, not the ideal" | Why context maps exist |
| Evans 2003 to DDD-crew and Context Mapper | Where it comes from |
| What a context map is and is not | The context map |
| Who sets the model, who pays translation | Upstream, downstream and power |
| The nine patterns, one block each | Partnership, Shared Kernel, Customer-Supplier, Conformist, Anticorruption Layer, Open Host Service, Published Language, Separate Ways, Big Ball of Mud |
| U/D, OHS, PL, ACL, CF, SK, P on a drawing | Notation |
| Sync API, async events, shared DB on the map | Communication types |
| Mutually dependent, upstream/downstream, free | Team relationships overlay |
| ACL to OHS, shared kernel to separate ways | Evolving the map |
| Sales, Fulfilment, Billing, Catalog, Identity, ERP | The running example's map |
| Workshop steps, CML file, versioning rules | Mechanics |
| ACL, OHS/PL, conformist, shared kernel, contract tests | Go, Laravel |
| Legacy ERP, SaaS, breaking contract, creeping kernel | Solving the classic problems |
| Which pattern when | Choosing |
| Monolith to distributed data | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The patterns. Every row is unpacked in the concept catalogue. "Who pays" means who carries the cost of translation and change.
| Pattern | Notation | In plain words | Who pays | Typical edge in our shop |
|---|---|---|---|---|
| Partnership | P (symmetric) | Two teams that succeed or fail together plan and release jointly | Both, in meetings | Sales and Fulfilment during the click-and-collect launch |
| Shared Kernel | SK (symmetric) | A small piece of model and code both teams co-own | Both, in coordination | Money, Currency, the rounding rule (Sales, Billing) |
| Customer-Supplier | U/S, D/C | Downstream's needs go into upstream's planning | Upstream, in planning; downstream, in asking | Sales (supplier) to Fulfilment (customer) |
| Conformist | D, CF | Downstream adopts upstream's model as is | Downstream, in model quality | Sales uses Catalog's product model |
| Anticorruption Layer | D, ACL | Downstream translates at its own edge | Downstream, in code it owns | Sales reading the legacy ERP |
| Open Host Service | U, OHS | One open protocol for every consumer | Upstream, in API stewardship | Sales events, Identity's OIDC |
| Published Language | U, PL | A documented exchange format, not the internal model | Upstream, in schema governance | sales.order.placed.v1 JSON Schema |
| Separate Ways | none | No integration; duplicate a little instead | Nobody, until needs change | Billing and Catalog |
| Big Ball of Mud | BBoM (boundary) | A mess with no internal boundaries; wall it off | Whoever touches it | The legacy ERP |
Power and cost on an edge.
| Question | Upstream answers | Downstream answers |
|---|---|---|
| Whose model is used on the wire? | Mine (OHS/PL), unless we negotiate | Theirs (CF) or mine behind a translator (ACL) |
| Who must change when the other changes? | Nobody, by definition | Me, at the ACL or everywhere (CF) |
| What can I ask for? | Nothing; I decide | Priorities (C/S), nothing (CF/ACL), joint plan (P) |
| What protects me? | Versioning, deprecation policy | Contract tests in upstream CI, an ACL |
Communication on the map.
| Mark on the edge | Meaning | Healthy for | Smell when |
|---|---|---|---|
| Sync API (REST, gRPC) | Downstream calls upstream at request time | Queries that need fresh data | The call is on every request and upstream is slow |
| Async events (broker) | Upstream publishes, downstream reacts | Facts other contexts react to | Downstream needs an answer now |
| File / batch export | Periodic dump | Legacy, analytics | Business decisions wait for the nightly job |
| Shared database | Both read or write the same tables | Never across contexts | Always: mark it red |
Why context maps exist
A system with more than one bounded context has edges, and every edge carries a relationship whether anyone named it or not. When it is unnamed, the downstream team discovers it the hard way: an upstream rename breaks production, a request for one extra field sits in a backlog for three months, a legacy record format leaks into the core model one if at a time. Evans states the problem in the Reference: "People on other teams won’t be very aware of the context boundaries and will unknowingly make changes that blur the edges or complicate the interconnections. When connections must be made between different contexts, they tend to bleed into each other."
A context map makes three things explicit for each edge: the direction of influence (upstream or downstream), the technical mechanism (API, events, shared code, translator), and the social contract (partners, customer and supplier, or "take it or leave it"). Vaughn Vernon's Implementing DDD puts it this way in its preface: "Context Maps are a powerful tool to help a team understand their business domain, the boundaries between distinct models, and how they are currently, or can be, integrated."
| Without a map | With a map |
|---|---|
| "We just call their API" for every integration | Each edge has a named pattern and an owner of the translation |
| Upstream changes surprise downstream teams | Customer-supplier edges have contract tests in upstream CI |
| Legacy terms leak into the core model | An ACL stops them at the edge |
| A shared library grows into a shared domain | A shared kernel has a size limit and a versioning policy |
| The architecture diagram shows the wish | The map shows today; the target is a second map |
| Good for: nothing beyond one team | Good for: any system with two or more teams or contexts |
The analogy we reuse on this page: a city's rivers and bridges. Evans's own image for upstream and downstream is two cities on a river: "the upstream city’s pollution primarily affects the downstream city." A context map is the city map that marks every bridge and every river. Some bridges are joint projects (partnership), some towns share one water treatment plant (shared kernel), some downstream towns can petition the upstream council (customer-supplier), some simply drink what comes (conformist), some build their own filtration plant (anticorruption layer), the biggest upstream town runs a public water utility with a published quality standard (open host service with a published language), some towns dig their own wells (separate ways), and one district is an unplanned shanty town you fence off (big ball of mud).
The picture is the whole catalogue in DDD-crew style: symmetric patterns (Partnership, Shared Kernel) drawn without direction, asymmetric ones with an arrow from upstream (U) to downstream (D) and role tags at each end.
Three common misunderstandings, up front
- "A context map is the target architecture." Evans: "Map the existing terrain. Take up transformations later." Draw what is true today, including the ugly edges; draw the target as a second map (Context Mapper even has a
stateattribute withAS_ISandTO_BE). - "The patterns are technical integration styles." Most of them are about people: who can ask whom for what. Customer-Supplier and Conformist can use exactly the same REST call; the difference is whether the upstream team will listen.
- "An ACL is always the safe choice." It has a price: Microsoft's pattern page warns that "The anti-corruption layer adds latency to calls between the two systems" and "adds an extra service that you must manage and maintain". Conforming to a good published language is often the cheaper and better choice.
Where it comes from
Evans, 2003. Domain-Driven Design introduced the bounded context, the context map and the relationship patterns in Part IV (Strategic Design). Fowler's bliki entry on bounded contexts notes that "Bounded Context opens part IV (Strategic Design)" and that DDD's strategic design "goes on to describe a variety of ways that you have relationships between Bounded Contexts. It's usually worthwhile to depict these using a context map."
Foote and Yoder, 1997/1999. Big Ball of Mud (the paper Evans cites; our copy is dated 26 June 1999) defined the term: "A BIG BALL OF MUD is a casually, even haphazardly, structured system. Its organization, if one can call it that, is dictated more by expediency than design."
Vernon, 2013. Implementing Domain-Driven Design, chapter 3 "Context Maps" (pages 87 to 111), made drawing maps a practice. Fowler calls that chapter "the best source on drawing context maps". We read the book's preface and guide pages (publisher's sample), not chapter 3 itself.
Evans, 2015. The free DDD Reference restated every pattern in a short "Therefore:" form. Partnership and Big Ball of Mud carry its asterisk, whose legend reads "New term introduced since the 2004 book". It also defines three relationship words: upstream-downstream, mutually dependent, free. This page quotes the Reference throughout.
Khononov, 2021. Learning Domain-Driven Design, chapter 4 "Integrating Bounded Contexts", groups the patterns by the kind of team relationship: cooperation (Partnership, Shared Kernel), customer-supplier, and separate ways. We did not read the chapter; the grouping comes from search results showing the publisher's table of contents, and we use it here only as a teaching device.
DDD-crew. The community repository context-mapping published a cheat sheet and a Miro starter kit: "There are nine context map patterns and three different team relationships."
Context Mapper. A DSL (CML) and tooling that turns context maps into text files you can version and validate, with explicit semantic rules (for example, "The patterns ACL and CF cannot be applied jointly").
Year Idea What it changed
1 1997/1999 Foote & Yoder: Big Ball of Mud A name for the system with no boundaries
2 2003 Evans: context map + relationship patterns Integration becomes a modelling decision
3 2013 Vernon IDDD ch. 3: drawing context maps Maps become a team practice
4 2015 Evans DDD Reference: Partnership, BBoM Nine patterns, three relationship words
5 later DDD-crew cheat sheet, Context Mapper CML Shared notation; maps as code
6 2021 Khononov: cooperation / C-S / separate ways Patterns grouped by team relationshipThe concept catalogue
Each block: plain words, the usual wrong belief, a precise definition, a timeline on the running example, real scenarios, a comparison table, the fix in code or practice.
The context map Must-know
In plain words: a context map is a drawing (or a text file) that shows every bounded context you deal with, every line between them, and on each line who adapts to whom.
Common misunderstanding: "It is our architecture diagram with DDD names." An architecture diagram shows deployables and protocols; a context map shows models and influence. Vernon's index has the entry "Context Maps are not EA diagrams". Two services can sit in one context; one legacy system can hold three implicit models.
Definition: Evans (Reference, "Context Map"): "Identify each model in play on the project and define its bounded context. This includes the implicit models of non-object-oriented subsystems. Name each bounded context, and make the names part of the ubiquitous language." Then: "Describe the points of contact between the models, outlining explicit translation for any communication, highlighting any sharing, isolation mechanisms, and levels of influence." The DDD-crew README adds that maps "can be used to analyze existing systems or application landscapes, but they are also suitable for upfront design considerations".
Drawing the first map for the shop (90-minute session, people from every team)
1 List contexts by name: Sales, Fulfilment, Billing, Catalog, Identity, "the ERP"
2 For each pair that talks: draw a line; write the mechanism (REST, events, DB, file)
3 For each line: who is upstream? ask "whose change breaks whom?"
4 Tag the relationship: Sales->Fulfilment C/S; Sales->Billing OHS/PL + CF; Billing->Sales OHS/PL + ACL; ERP->Sales ACL
5 Mark smells in red: BI reads Sales tables directly
6 Save as AS_IS; draw TO_BE separately (ERP retired, BI reads events)Real scenario: a retailer discovering that "Customer" exists in five systems with three numbering schemes; a bank finding that its "core" depends conformist-style on a vendor's data model it cannot change; a scale-up whose map shows one team upstream of eleven others, which explains why that team is always the bottleneck.
| A context map shows | It does not show |
|---|---|
| Bounded contexts (including implicit models in legacy systems) | Servers, pods, regions |
| Direction of influence (U/D) on each edge | Call latency or throughput |
| The pattern on each edge (P, SK, C/S, CF, ACL, OHS, PL) | Class diagrams |
| Where translation happens and who owns it | The whole domain model |
| Smells: shared DB, big ball of mud | The ideal future (that is a second map) |
Fix / how to use it: keep the map small and question-driven. DDD-crew's first best practice: "Prefer small context maps for explicit questions", and "Work with different perspectives and multiple context maps for those perspectives". Store it as CML or a diagram file in the repository, review it when a new integration is proposed, and re-draw it when teams change.
Upstream, downstream and power Must-know
In plain words: upstream is the side whose changes hit the other side; downstream is the side that gets hit. It is about influence, not about which way the data flows.
Common misunderstanding: "Upstream is the producer of the message, downstream the consumer." Usually, but not by definition. If Billing calls a Fulfilment API to ask for delivery dates, data flows Fulfilment to Billing, and Fulfilment is upstream because a change in Fulfilment's API breaks Billing. If Fulfilment had to change whenever Billing changed, the arrow would flip.
Definition: Evans (Reference): upstream-downstream is "A relationship between two groups in which the “upstream” group’s actions affect project success of the “downstream” group, but the actions of the downstream do not significantly affect projects upstream." and "The upstream team may succeed independently of the fate of the downstream team." The other two relationship words: mutually dependent, "A situation in which two software development projects in separate contexts must both be delivered in order for either to be considered a success", and free, "A software development context in which the direction, success or failure of development work in other contexts has little effect on delivery." Context Mapper encodes the direction: "the arrow -> always points from the upstream to the downstream and thus expresses an influence flow".
Who is upstream? Ask "if they change, do we break?"
1 Catalog renames "price" to "list_price" -> Sales breaks => Catalog upstream of Sales
2 Sales adds delivery_window to OrderPlaced -> Fulfilment gains => Sales upstream of Fulfilment
3 Fulfilment changes its warehouse codes -> Sales unaffected => no edge needed from Fulfilment
4 Billing changes invoice numbering -> Sales unaffected => no edge for invoices
5 Billing renames a field in payment.captured.v1 -> Sales ACL breaks => Billing upstream of Sales for payments
6 ERP vendor ships a new export format -> Sales ACL breaks => ERP upstream, Sales downstreamReal scenario: a payments provider (upstream) that deprecates an API version on its own schedule; an internal identity team serving forty services, each downstream; two teams who are each upstream of the other on different edges (Sales upstream of Billing for orders, Billing upstream of Sales for payment status), which is fine as long as each edge is named separately.
Power and who pays:
| Relationship | Model on the wire | Downstream's say | Translation cost sits with |
|---|---|---|---|
| Partnership | Agreed jointly | Equal | Both, as coordination |
| Shared Kernel | The kernel | Equal for the kernel | Both, as consultation |
| Customer-Supplier | Supplier's, shaped by customer requests | Priorities, acceptance tests | Supplier (planning), customer (requests) |
| OHS + PL | The published language | Requests may be accepted for everyone | Upstream builds it once; downstream maps to it |
| Conformist | Upstream's | None | Downstream, as a weaker own model |
| ACL | Upstream's, translated | None needed | Downstream, as code it maintains |
| Separate Ways | None | Not applicable | Nobody (some duplication instead) |
Fix / how to use it: for every edge write U and D. If you cannot decide, ask both teams "who has to change when the other changes?" If the answer is "both, always", you have a mutually dependent pair: either make it a Partnership on purpose, or move the boundary.
Partnership Important
In plain words: two teams who will succeed or fail together agree to plan, change and release their interface together.
Common misunderstanding: "Partnership means we are friends and talk a lot." It is a process commitment, not a mood. Evans: "Institute a process for coordinated planning of development and joint management of integration." Without the process, "partnership" is just two teams blocking each other.
Definition: Evans (Reference): "Where development failure in either of two contexts would result in delivery failure for both, forge a partnership between the teams in charge of the two contexts." "The teams must cooperate on the evolution of their interfaces to accommodate the development needs of both systems. Interdependent features should be scheduled so that they are completed for the same release." He also gives the integration mechanism: "a special test suite can be defined that proves the interface meets the expectations of the client system, which can be run as part of continuous integration on the server system."
Click-and-collect launch (6 weeks, Sales + Fulfilment as partners)
1 Week 0 Joint planning: Sales adds pickup_store_id; Fulfilment adds store picking
2 Week 1 Shared interface draft (event + API) reviewed by both teams
3 Week 3 Fulfilment hits a store-stock gap; joint session; Sales adds stock check
4 Week 5 Joint integration suite green in both CIs
5 Week 6 Release together
6 Week 10 Feature stable -> relationship downgraded to Customer-Supplier (see Evolution)Real scenario: a mobile app team and its backend-for-frontend team shipping a new checkout together; a payments context and a fraud context launching 3-D Secure in one release; a regulator-driven change (new tax rule) that must land in Sales and Billing on the same date.
| Aspect | Partnership |
|---|---|
| Team dynamics | Joint planning, shared rituals, mutual veto in practice |
| Cost | High coordination; slowest team sets the pace |
| Code shape | Shared interface definition reviewed by both; joint integration tests in both CIs |
| Risk | Becomes permanent lockstep: a distributed monolith by agreement |
| How to leave | When the interface stabilises, pick a direction: Customer-Supplier or OHS/PL |
Fix / how to use it: time-box it ("partnership until the launch, then customer-supplier"), write the joint test suite first, and put the end date on the map. Context Mapper models it as Sales [P]<->[P] Fulfilment, a symmetric relationship that cannot carry OHS, PL, ACL or CF roles (its rule #4).
Shared Kernel Must-know
In plain words: two teams agree to own a small, explicitly bounded piece of model and code together, and change it only by mutual agreement.
Common misunderstanding: "Put the common domain classes in a shared library." That is how a shared kernel becomes a shared domain: Order, Customer and Invoice in a common package imported by every service is the opposite of what Evans describes. The kernel is tiny and co-owned; a big library owned by nobody is implementation coupling.
Definition: Evans (Reference): "Sharing a part of the model and associated code is a very intimate interdependency, which can leverage design work or undermine it." "Therefore: Designate with an explicit boundary some subset of the domain model that the teams agree to share. Keep this kernel small." "This explicitly shared stuff has special status, and shouldn’t be changed without consultation with the other team." "Define a continuous integration process that will keep the kernel model tight and align the ubiquitous language of the teams."
What may be shared, and what may not:
| Good kernel content | Why it is safe | Bad kernel content | Why it is not |
|---|---|---|---|
Money, Currency (ISO 4217) | Stable, value objects, no behaviour that differs by context | Order, Customer entities | Each context models them differently |
| A rounding or tax-rounding rule both must apply | Divergence is a real bug (one-cent differences) | Persistence models, ORM classes | Couple schemas |
Identifier types (OrderId format) | Must match on both sides | Workflow or status enums | Each side has its own life cycle |
| Error codes of a shared protocol | Part of the agreed contract | Utility grab-bags (StringUtils) | Not domain; just use a library |
A change request to the kernel (Sales wants Money.Split for instalments)
1 Sales opens PR on kernel; CODEOWNERS requires one Sales + one Billing reviewer
2 Billing asks: does Split round like PercentOf? Agree: same half-away-from-zero rule
3 Version 1.2.0 -> 1.3.0 (MINOR: additive)
4 Candidate tag built; both contexts' CI run against it; both green
5 Tag 1.3.0; Billing upgrades in its own time (nothing changed for it)
A rounding change would be MAJOR: both teams approve, both upgrade in the same cycleReal scenario: two teams that kept getting one-cent differences between cart totals and invoices until they shared one Money type and one rounding test table; a set of .proto common types (google.type.Money-style) used by a group of services; a reporting and a billing context sharing one tax-code value list mandated by law.
| Aspect | Shared Kernel |
|---|---|
| Team dynamics | Two (rarely three) teams, high trust, a named reviewer from each |
| Cost | Every change needs consultation; release coupling for MAJOR versions |
| Code shape | A versioned package (Go module, Composer package) with its own tests both teams run |
| Risk | Growth ("just add Address too"), a third and fourth team joining, nobody owning it |
| How to leave | Copy the code into each context and stop sharing (separate ways for that concept), or turn it into a published language |
Fix / how to use it: write the size limit and the versioning policy into the package (our Go kernel and the Laravel shared-kernel package carry them in a doc comment and composer.json), run the kernel's test table in both CIs, and review the kernel's contents every quarter: anything one side no longer needs leaves.
Customer-Supplier Must-know
In plain words: the upstream team (supplier) treats the downstream team as a customer whose needs go into its planning, but the supplier still decides.
Common misunderstanding: "The customer can veto upstream changes." Evans warns about exactly that: "the freewheeling development of the upstream team will stop if the downstream team has veto power over changes." The customer gets a voice in planning and automated tests in the supplier's CI, not a veto.
Definition: Evans (Reference): "Establish a clear customer/supplier relationship between the two teams, meaning downstream priorities factor into upstream planning. Negotiate and budget tasks for downstream requirements so that everyone understands the commitment and schedule." And the mechanism: "Jointly developed automated acceptance tests can validate the expected interface from the upstream. Adding these tests to the upstream team’s test suite, to be run as part of its continuous integration, will free the upstream team to make changes without fear of side effects downstream." Context Mapper: "A generic upstream-downstream relationship is not necessarily a customer-supplier relationship!"
Fulfilment (customer) needs a delivery window on OrderPlaced
1 Fulfilment files the request at Sales' planning session with a reason (route planning)
2 Sales budgets it for the next sprint; adds optional delivery_window (v1.1, additive)
3 Fulfilment adds "delivery_window.from/to" to consumers/fulfilment.expects.json
4 Sales CI runs every consumer expectation file on each build (contract test)
5 Months later a Sales dev renames lines[].quantity -> qty: Sales CI fails before merge
6 Sales keeps quantity; the rename becomes a v2 discussion, planned with customersReal scenario: a mobile team as customer of an internal API team; a warehouse system that asks the order system for an extra field and gets it next quarter; a data platform that publishes customer expectations as Pact contracts the producing teams must honour.
| Aspect | Customer-Supplier |
|---|---|
| Team dynamics | Customer attends supplier planning; supplier publishes a roadmap |
| Cost | Supplier spends capacity on customer requests; customer must articulate needs |
| Code shape | Consumer-driven contract tests (Pact, or expectation files) run in supplier CI |
| Risk | Too many customers: the supplier cannot plan for all of them (time to become an OHS) |
| How to leave | Upstream generalises into an Open Host Service; or downstream stops asking and conforms |
Fix / how to use it: the contract test is the mechanism: downstream writes what it reads, upstream runs it. Note a tooling nuance: Context Mapper's semantic rule #6 says "The OHS pattern is not applicable within a customer-supplier relationship", reasoning that an OHS is "one API in a one for all approach". Evans does not forbid the combination, and in practice a supplier can publish one OHS while also giving one important customer planning priority. Our running example keeps Sales-Fulfilment as customer-supplier over the published language and writes it in CML as Fulfilment [C]<-[S,PL] Sales.
Conformist Must-know
In plain words: the downstream team stops fighting and uses the upstream model as its own, at least in the part that touches the integration.
Common misunderstanding: "Conformist is always a defeat." Evans lists its upside: "choosing conformity enormously simplifies integration. Also, you will share a ubiquitous language with your upstream team." Conforming to a good model (a well-designed published language, an industry standard, an OIDC token) is often the best choice.
Definition: Evans (Reference): when "the upstream has no motivation to provide for the downstream team’s needs, the downstream team is helpless." "Therefore: Eliminate the complexity of translation between bounded contexts by slavishly adhering to the model of the upstream team. Although this cramps the style of the downstream designers and probably does not yield the ideal model for the application, choosing conformity enormously simplifies integration." Context Mapper's rule #5: "The CF pattern is not applicable within a customer-supplier relationship", because "A conformist in contrast has no influence and simply decides to conform to what the upstream provides."
Sales conforms to Catalog's product model
1 Catalog's API returns {sku, title, list_price, tax_class, variants[]}
2 Sales' cart stores CatalogProduct exactly as returned (no own Product type)
3 Catalog adds "bundle" products; Sales shows them wrong until Sales adapts
4 Team decides: still worth it (Catalog model is good, changes are rare)
5 If Catalog changes weekly or the model starts to hurt -> insert an ACL (see Evolution)Real scenario: every service that accepts an OIDC ID token and uses its sub, email claims as is; a shop that uses a payment provider's charge object as its payment record; Billing in our map, which uses the sales.order.placed.v1 types directly because they are exactly what it needs.
| When conforming is acceptable | When it is not |
|---|---|
| The upstream model is good or a standard (OIDC, iCalendar, ISO 20022) | The upstream model is a big ball of mud |
| The context is supporting or generic, not core | The downstream context is your core domain |
| Upstream changes rarely and compatibly | Upstream changes often and breaks things |
| You need few fields and use them as they are | You would rename, reinterpret or combine them |
Fix / how to use it: conform deliberately and locally: keep the upstream types in one package (Billing imports contracts/orderplaced, nothing else), so that if the upstream turns bad you can insert an ACL at exactly that seam. See the conformist consumer.
Anticorruption Layer Must-know
In plain words: the downstream team builds a translator at its own edge so that the upstream's model, words and quirks never enter its own model.
Common misunderstanding: "An ACL is a mapper class." A mapper is one part. Evans describes a layer that "talks to the other system through its existing interface" and "translates in one or both directions"; Microsoft's pattern page calls it "a facade or adapter layer". In practice it has three parts: a facade, an adapter and a translator. It also translates errors, identifiers and semantics (two ERP flags become one Sales credit status), not just field names.
Definition: Evans (Reference): "As a downstream client, create an isolating layer to provide your system with functionality of the upstream system in terms of your own domain model. This layer talks to the other system through its existing interface, requiring little or no modification to the other system. Internally, the layer translates in one or both directions as necessary between the two models." The motivation: "The models of legacy systems are usually weak (if not big balls of mud), and even the exception that is clearly designed may not fit the needs of the current project". Microsoft's pattern page: "Implement a facade or adapter layer between different subsystems that don't share the same semantics." Microservices.io frames the same problem: "How do you prevent a legacy monolith’s domain model from polluting the domain model of a new service."
The picture shows the three parts: the facade implements a port the Sales model owns; the adapter speaks the ERP's protocol (HTTP export, timeouts, status codes); the translator is a pure function from ERP record to Sales Customer, and maps identifiers and errors.
Sales places an order on account; customer data lives in the legacy ERP
1 PlaceOrderOnAccount asks CustomerDirectory.CustomerByID("cus_77") Sales language
2 Facade: translator maps cus_77 -> KUNNR 0000000077 id translation
3 Adapter: GET /export/kunde/0000000077 (timeout 2 s, retry on 5xx) ERP protocol
4 ERP returns {KUNNR, NAME1, KTOKD:"Z002", KLIMK:"1.500,00", SPERR:"", CRBLB:"X"}
5 Translator: segment=business, limit=150000 EUR cents, credit=on_hold semantics
6 Sales rule: on_hold -> order needs prepayment Sales language again
404 -> sales.ErrCustomerNotFound; 5xx/timeout -> "directory unavailable" (not "not found")Real scenario: a new core service in front of a 20-year-old ERP or mainframe; a SaaS integration (payment provider, tax engine, CRM) whose objects should not become your domain objects; a strangler-fig migration where the ACL is the seam that lets you swap the legacy system later (Strangler Fig).
Where it lives and what it costs:
| Placement | When | Cost | Source |
|---|---|---|---|
| Package inside the downstream service (our default) | One downstream needs the translation | Code to maintain; one place to change | Microsoft: "as a component within the application" |
| Separate ACL service | Several downstreams share one legacy, or different tech is needed | Extra deployable, latency, a single point of failure | Microsoft: "or as an independent service"; "adds latency" |
| In an integration platform (API gateway, iPaaS) | Protocol conversion only | Business semantics end up in config | Microsoft: API Management for "protocol concerns" |
| Event-driven ACL (consume legacy events, publish clean ones) | High-throughput, decoupled | Broker, ordering, idempotency | Microsoft: "an asynchronous, event-driven approach" |
Facade and adapter are the classic object patterns (Structural Patterns); the port-and-mapping shape is the same one used for persistence (Data Persistence in Design).
Fix / how to use it: own the port in the downstream model, keep the translator pure and table-tested, translate errors into your language, keep business rules out of the layer (Microsoft: "Avoid placing business rules or orchestration in the layer"), add correlation IDs and logs at the layer (Microsoft: "Plan for observability"), and decide up front whether it is permanent or will be retired with the legacy system. Code: Go, Laravel.
Open Host Service Must-know
In plain words: instead of building a custom integration for each consumer, the upstream publishes one well-defined protocol that anyone may use.
Common misunderstanding: "OHS means a public REST API." It means an open protocol for integration: a REST/gRPC API, an event stream, or both. The defining property is one protocol for many consumers, extended for general needs, with special cases handled outside it.
Definition: Evans (Reference): "When a subsystem has to be integrated with many others, customizing a translator for each can bog down the team." "Therefore: Define a protocol that gives access to your subsystem as a set of services. Open the protocol so that all who need to integrate with you can use it. Enhance and expand the protocol to handle new integration requirements, except when a single team has idiosyncratic needs. Then, use a one-off translator to augment the protocol for that special case so that the shared protocol can stay simple and coherent." And: "Each client is downstream, and typically some of them will be conformist and some will build anticorruption layers."
Sales becomes an OHS when the third consumer arrives
1 Fulfilment and Billing each got a tailored payload (two code paths in Sales)
2 BI asks for a third variant; Sales team says no and designs sales.order.placed.v1
3 Contract published: JSON Schema + AsyncAPI document + example message
4 Billing conforms (uses the types as they are); Fulfilment adds its needs via C/S
5 A partner warehouse wants XML: one-off translator outside the OHS (Evans' advice)
6 The OHS stays one shape; v2 only when a breaking change is unavoidableReal scenario: an identity provider exposing OpenID Connect to every application; a payments team publishing payment.captured events for all interested contexts; a public API (Stripe-, GitHub-style) consumed by thousands of clients who are all downstream.
| Aspect | Open Host Service |
|---|---|
| Team dynamics | Upstream acts as a product team for its API; deprecation policy, changelog |
| Cost | API design and stewardship, versioning, documentation |
| Code shape | Outbound translation from internal model to published language; contract tests; spec files (OpenAPI, AsyncAPI, .proto) |
| Risk | Leaking the internal model ("we just serialise the entity"); a protocol that grows a field per consumer |
| How to leave | Rarely left; replaced version by version (v1 to v2 published in parallel) |
Fix / how to use it: map outbound explicitly (never serialise the aggregate), publish the spec next to the code, and test that internal fields do not leak (publisher code).
Published Language Must-know
In plain words: a documented exchange format both sides translate into and out of, so neither side's internal model becomes the contract.
Common misunderstanding: "Our domain model is the published language." Evans explains why not: internal models "may be overly complex or poorly factored. They are probably undocumented. If one is used as a data interchange language, it essentially becomes frozen and cannot respond to new development needs."
Definition: Evans (Reference): "Use a well-documented shared language that can express the necessary domain information as a common medium of communication, translating as necessary into and out of that language." "Many industries establish published languages in the form of data interchange standards. Project teams also develop their own for use within their organization." "Published language is often combined with open-host service." DDD-crew: "Widely known examples of a Published Language are iCalendar or vCard."
The usual formats:
| Format | Describes | What the spec says | Good for |
|---|---|---|---|
| OpenAPI 3.1 | HTTP APIs | "a standard, programming language-agnostic interface description for HTTP APIs" | Sync OHS |
| AsyncAPI 3.0 | Message-driven APIs | "describe message-driven APIs in a machine-readable format. It’s protocol-agnostic" (AMQP, MQTT, Kafka...) | Event OHS |
| JSON Schema | JSON payloads | Validation vocabulary (required, type, const) | Event payloads, also inside OpenAPI/AsyncAPI |
| Protocol Buffers (proto3) | Messages and gRPC services | Field numbers; deleted numbers go in reserved | Binary events, gRPC |
| Industry standards | iCalendar, vCard, OIDC claims, ISO 20022, EDIFACT | Owned by a standards body | Cross-company integration |
Versioning rules that keep a PL usable:
| Change | Compatible? | Rule |
|---|---|---|
| Add an optional field | Yes | MINOR (v1.0 to v1.1); consumers ignore unknown fields |
| Add a required field | No for producers of old data | Make it optional, or v2 |
| Rename or remove a field | No | v2 on a new name/routing key, publish v1 and v2 in parallel |
| Change a field's meaning or unit | No, and silent | v2; never reuse a name with new semantics |
| Protobuf: delete a field | Yes if reserved | Protobuf docs: "add your deleted field number to the reserved list" |
| Change an enum's values | Usually no | Add values only; consumers must handle unknown values |
Life of sales.order.placed.v1
1 v1.0 published: order_id, customer_id, currency, total_minor, lines[]
2 v1.1 + delivery_window (optional) for Fulfilment; Billing unaffected
3 margin_minor proposed by BI -> rejected (internal, commercial secret)
4 v2 "lines" restructured for bundles -> new key sales.order.placed.v2
5 Sales publishes v1 and v2 for 3 months; consumers migrate; v1 retiredFix / how to use it: keep the schema as the source of truth in the repository (ours: contracts/sales/order_placed.v1.schema.json, .proto, asyncapi.yaml), generate or hand-write bindings, and test both sides against it. Deeper evolution rules live in Message Design & Schema Evolution and API Versioning; translating into and out of a shared format is the EIP Canonical Data Model idea (Message Transformation), and the event styles behind an event OHS are in Event-Driven Architecture.
Separate Ways Important
In plain words: two contexts that do not really need each other stop integrating, and each solves its small need on its own, even if that means a little duplication.
Common misunderstanding: "Duplication is always waste." Integration has a running cost (contracts, outages, coordination). Evans: "Integration is always expensive, and sometimes the benefit is small."
Definition: Evans (Reference): "We must be ruthless when it comes to defining requirements. If two sets of functionality have no significant relationship, they can be completely cut loose from each other." "Therefore: Declare a bounded context to have no connection to the others at all, allowing developers to find simple, specialized solutions within this small scope."
Billing wanted product descriptions on invoices
1 Option A: Billing calls Catalog per invoice line (new sync edge, Catalog outage = no invoices)
2 Option B: Billing takes sku + quantity + price from OrderPlaced; prints the SKU text it has
3 Finance agrees invoices show SKU and the order's line text; no Catalog call
4 Map: Billing and Catalog = separate ways (no line)Real scenario: an HR system and an e-commerce platform in the same company; a marketing site with its own small product list instead of integrating with the PIM; two internal tools that each keep a short list of countries rather than calling a reference-data service.
| Aspect | Separate Ways |
|---|---|
| Team dynamics | Free (Evans' third relationship word) |
| Cost | Some duplicated data or logic; possible inconsistency users notice |
| Code shape | Nothing; that is the point |
| Risk | Needs grow and an integration appears informally (spreadsheet, shared DB) |
| How to leave | Add an edge with a named pattern when the benefit becomes real |
Fix / how to use it: write "separate ways" on the map explicitly so nobody adds an accidental integration, and re-check when requirements change.
Big Ball of Mud Important
In plain words: some systems have no inner boundaries worth drawing; mark the whole thing as one blob and protect everything else from it.
Common misunderstanding: "We must model the legacy system properly before we can integrate." Evans: "It is easy to get bogged down in an attempt to describe the context boundaries of models in systems where there simply are no boundaries."
Definition: Evans (Reference): "Draw a boundary around the entire mess and designate it a big ball of mud. Do not try to apply sophisticated modeling within this context. Be alert to the tendency for such systems to sprawl into other contexts." He also notes, citing Foote and Yoder, that "The big ball of mud is actually quite practical for some situations". DDD-crew: "Big Ball Of Mud is a demarcation of a bad model or system quality. You want to make sure, that this mess does not propagate into other bounded contexts."
The ERP on the map
1 Draw one dashed box "Legacy ERP (BBoM)"; no inner contexts
2 Every edge from it into a modelled context gets an ACL
3 New features never go into the ERP; they go into new contexts next to it
4 Strangler fig: each moved capability shrinks the box; ACL becomes the seamReal scenario: a 15-year-old PHP monolith whose orders table has 140 columns; an ERP customised by three consultancies; a shared "core" database that eleven applications write to.
| Do | Do not |
|---|---|
| Draw it as one context with a clear border | Draw dozens of guessed inner contexts |
| Put an ACL on every edge into a modelled context | Let its terms into your core model |
| Use it as is for what it already does well | Add new core features inside it |
| Plan retreat by strangler fig | Plan a big-bang rewrite (Fowler: "we've seen this simple-sounding plan go down in flames most of the time") |
Fix / how to use it: mark it, wall it, and route new work around it. The ACL is the wall.
Notation: U/D, roles and the cheat-sheet style Must-know
In plain words: a small set of letters on each end of a line tells a reader the relationship at a glance.
Common misunderstanding: "Arrows show data flow." In the DDD-crew and Context Mapper style the arrow shows influence: from upstream to downstream.
Definition: the abbreviations used by Context Mapper's CML and the DDD-crew cheat sheet:
| Mark | Meaning | Where it goes | CML example |
|---|---|---|---|
| U / D | Upstream / downstream | Each end of an asymmetric line | Sales [D]<-[U] Catalog |
| S / C | Supplier / customer | Customer-supplier ends | Fulfilment [C]<-[S] Sales |
| OHS | Open host service | Upstream end only | [U,OHS,PL] |
| PL | Published language | Upstream end only | [U,OHS,PL] |
| CF | Conformist | Downstream end only | [D,CF] |
| ACL | Anticorruption layer | Downstream end only | [D,ACL] |
| SK | Shared kernel | Both ends, symmetric | Sales [SK]<->[SK] Billing |
| P | Partnership | Both ends, symmetric | Sales [P]<->[P] Fulfilment |
| BBoM | Big ball of mud | A boundary, not a line | dashed box |
Context Mapper's rules make the notation precise: "The patterns OHS and PL can only be implemented by the upstream context", "The patterns ACL and CF can only be applied by the downstream context", "The patterns ACL and CF cannot be applied jointly", and OHS, PL, ACL, CF "are not applicable in symmetric relationships (Partnership and Shared Kernel)". It also records attributes per edge: implementationTechnology, downstreamRights (INFLUENCER, OPINION_LEADER, VETO_RIGHT, DECISION_MAKER, MONOPOLIST) and exposedAggregates, and per map type (SYSTEM_LANDSCAPE or ORGANIZATIONAL) and state (AS_IS or TO_BE).
Reading one line of the map
1 Billing [D,CF]<-[U,OHS,PL] Sales { implementationTechnology = "AMQP events" }
2 "<-" : arrow points from Sales (upstream) to Billing (downstream)
3 [U,OHS,PL] : Sales offers an open host service in a published language
4 [D,CF] : Billing conforms to that language (no ACL)
5 { ... } : the mechanism; async events over AMQPFix / how to use it: pick the notation once per organisation and explain it on the map itself (DDD-crew: "Document and explain the patterns you are going to use"). Keep the CML file next to the code: our map as CML.
Communication types on the map Important
In plain words: the pattern says who adapts; the communication type says how bytes travel. Write both on each line.
Common misunderstanding: "Async events mean no coupling." Events remove temporal coupling; the event schema is still a contract and the relationship (conformist, ACL) still applies. A shared database is the worst case because it hides the relationship: every table is an unversioned published language nobody agreed to.
Definition: the mechanisms you will see, and how they show on the map:
| Mechanism | Map mark | Typical pattern pairing | Notes |
|---|---|---|---|
| Sync request/response (REST, gRPC) | solid line, "sync REST" | OHS + PL (OpenAPI / .proto), CF or ACL downstream | Temporal coupling: timeouts, retries (Service Communication) |
| Async events (Kafka, RabbitMQ) | solid line, "async events" | OHS + PL (AsyncAPI, JSON Schema, Avro, Protobuf) | Publish via outbox; consumers idempotent |
| Shared library | double line / SK | Shared Kernel only | Must be tiny and versioned |
| File / batch export | dashed line, "nightly file" | ACL downstream (legacy) | Freshness measured in hours |
| Shared database | red line, "shared DB" | none: it is a smell | Mark it; plan its removal (Data Ownership) |
| In-process call (modular monolith) | line inside one deployable | OHS = module's public interface | Translation still needed between models |
The same fact, three ways
1 Sync: Billing GET /orders/1042 at invoice time -> Sales down = no invoices
2 Async: Billing consumes sales.order.placed.v1 -> Sales down = invoices later
3 Shared: Billing SELECT * FROM sales.orders -> Sales renames a column = Billing brokenFix / how to use it: annotate every edge with its mechanism (implementationTechnology in CML), colour shared-database edges red, and attach a removal plan to each one.
Team relationships overlay Good to know
In plain words: draw the teams on top of the contexts; most edge problems are team problems.
Common misunderstanding: "One context, one team, always." Often true, but one team can own several contexts, and a context owned by two teams is a warning sign.
Definition: DDD-crew's three team relationships: mutually dependent ("their software artifacts or systems need to be delivered together to be successful and work"), upstream/downstream ("Actions of an upstream team will have an effect on the downstream team, but actions of the downstream do not have a significant impact on the upstream team"), and free ("changes in other Bounded Contexts do not influence its success or failure"). Context Mapper supports an ORGANIZATIONAL map whose contexts are teams.
| Team relationship | Patterns it usually goes with | Watch for |
|---|---|---|
| Mutually dependent | Partnership, Shared Kernel | Lockstep forever |
| Upstream/downstream | Customer-Supplier, Conformist, ACL, OHS/PL | Upstream overloaded by requests |
| Free | Separate Ways | Hidden integration appearing later |
Overlay on our map (see the running map below)
1 Team Checkout owns Sales -> upstream of Fulfilment, Billing; downstream of Billing (ACL) for payments
2 Team Warehouse owns Fulfilment -> customer of Checkout
3 Team Finance Eng owns Billing -> conformist to Sales PL; upstream OHS/PL for payments; co-owns kernel
4 Team Platform owns Identity -> upstream of all (generic OHS)
5 Vendor + one admin own the ERP -> upstream; no planning influence at allFix / how to use it: align with Team Topologies language: an X-as-a-Service interaction is an OHS; a collaboration interaction is a time-boxed Partnership.
Evolving the map Important
In plain words: relationships change as systems and teams change; the map should record the move and the reason.
Common misunderstanding: "Once we pick a pattern it is fixed." Every pattern has a typical next step.
Definition: common transitions and their triggers:
| From | To | Trigger | What changes in code |
|---|---|---|---|
| Conformist | ACL | Upstream model starts to hurt the downstream core | Insert translator at the seam where upstream types were confined |
| ACL | Conformist to OHS/PL | Upstream publishes a clean published language | Delete most of the translator; use the PL types |
| ACL (legacy) | Nothing | Strangler fig finished, legacy retired | Delete the ACL with the legacy system |
| Customer-Supplier | OHS + PL | Third and fourth customer arrive | Generalise the payload; publish a spec |
| Partnership | Customer-Supplier | Launch done, interface stable | Joint tests become consumer contract tests |
| Shared Kernel | Separate Ways | Kernel unused by one side, or growing | Copy the code; stop sharing |
| Shared Kernel | Published Language | More consumers want it | Turn shared code into a schema |
| Shared DB | OHS/PL events | Any time; it is a smell | Expand/contract migration to events (Data Ownership) |
Sales <- ERP over two years
1 Q1 Sales [D,ACL]<-[U] ERP ACL translates customer master records
2 Q3 New "Customer" context strangles the ERP's customer master
3 Q4 Customer context offers OHS + PL (customer.updated.v1)
4 Q5 Sales [D,CF]<-[U,OHS,PL] Customer; ERP ACL deleted for customers
5 Q8 ERP retired; map: the BBoM box is goneNewman's Building Microservices gives the reason bounded contexts are the right unit to move: "bounded contexts make excellent seams since by definition they represent cohesive and yet loosely coupled boundaries in an organization"; his Monolith to Microservices has a section "Pattern: Strangler Fig Applications" for moving capabilities across such a seam.
Fix / how to use it: keep AS_IS and TO_BE maps; each architecture decision record that changes an edge updates the map in the same pull request.
The running example's map Must-know
In plain words: the shop we use across the DDD path, drawn as it is today.
Common misunderstanding: "Each pair of contexts has exactly one relationship." Sales and Billing have three: an OHS/PL event edge each way (sales.order.placed.v1 down to Billing, billing.payment.captured.v1 back up to Sales) and a tiny shared kernel. Separate perspectives can live on separate maps.
Definition: the edges, each with its pattern, mechanism and reason:
| Edge | Pattern | Mechanism | Why this pattern |
|---|---|---|---|
| Sales to Fulfilment | Customer-Supplier over Sales' OHS + PL | Async sales.order.placed.v1 | Fulfilment's needs (delivery window) go into Sales planning |
| Sales to Billing | OHS + PL upstream, CF downstream | Async sales.order.placed.v1 | The PL is exactly what Billing needs; no translation pays off |
| Billing to Sales | OHS + PL upstream (Billing), ACL downstream (Sales) | Async billing.payment.captured.v1 (integration name; Billing's domain event class is PaymentCaptured) | Sales needs to know when to call Order.MarkPaid; Sales is core, so Billing's payment vocabulary stops at a thin ACL (not C/S: Context Mapper rule #7 advises against an ACL inside customer-supplier) |
| Sales and Billing | Shared Kernel | Go module / Composer package | Cart and invoice must round identically |
| Catalog to Sales | Conformist | Sync REST | Catalog's product model is good and stable |
| Identity to Sales, Billing | OHS + PL (OpenID Connect) | Tokens, discovery, JWKS | Generic subdomain; standard protocol |
| Legacy ERP to Sales | ACL downstream; ERP is BBoM | Sync HTTP export | ERP model is weak; Sales is core |
| Billing and Catalog | Separate Ways | none | Invoices use order line data |
| Sales DB to BI reports | Shared database (smell) | Direct SQL | To be replaced by events |
One order across the map
1 Customer logs in: Identity (OHS/PL: OIDC) -> Sales conforms to token claims
2 Cart shows products: Catalog -> Sales (CF, sync REST)
3 Pay on account: Sales -> ERP ACL -> credit status "good"
4 Place: Sales writes order + outbox row (one transaction)
5 Relay publishes sales.order.placed.v1 -> Fulfilment (C/S) and Billing (CF)
6 Billing drafts invoice; VAT via shared-kernel rounding = same cent as the cart
7 Billing records PaymentCaptured -> outbox -> billing.payment.captured.v1 -> Sales (ACL)
8 Sales ACL translates it into Order.MarkPaid (Billing's payment words stay outside)Fix / how to use it: the same map as code is contracts/contextmap.cml. Each edge has a code counterpart in Go and Laravel.
Mechanics
Drawing a context map step by step Must-know
- Invite every team that owns a context, plus someone who knows the legacy systems. A map drawn by architects alone shows the wish.
- List contexts by name, including implicit models inside legacy systems (Evans: "This includes the implicit models of non-object-oriented subsystems").
- Draw a line for each pair that exchanges data or calls, and write the mechanism on it.
- Decide direction by asking "if they change, do we break?" Write U and D.
- Name the pattern at each end (OHS, PL upstream; CF, ACL downstream; or SK, P for symmetric).
- Mark smells: shared databases, big balls of mud, edges nobody owns.
- Overlay teams; note where one team is upstream of many.
- Save as
AS_IS; draw aTO_BEmap only after this one is agreed.
The map as code: Context Mapper CML
The running example as a CML file in the snippet directory. It is written to respect the rules on Context Mapper's Language Semantics page (we did not run the validator): no OHS role on the customer-supplier edge (rule #6), even though Sales serves Fulfilment through the same OHS; ACL and CF never together (rule #3); no roles on the symmetric shared-kernel edge (rule #4).
/* The running example as Context Mapper CML (AS_IS = the map of today, not the wish). */
ContextMap ShopContextMap {
type = SYSTEM_LANDSCAPE
state = AS_IS
contains Sales, Fulfilment, Billing, Catalog, Identity, LegacyERP
/* Customer-supplier: Fulfilment's needs go into Sales planning.
Context Mapper forbids OHS on a C/S edge (rule #6), so only PL is written here. */
Fulfilment [C]<-[S,PL] Sales {
implementationTechnology = "AMQP events: sales.order.placed.v1"
}
/* Open host service with a published language; Billing conforms to the PL. */
Billing [D,CF]<-[U,OHS,PL] Sales {
implementationTechnology = "AMQP events: sales.order.placed.v1"
}
/* The other way: Billing is upstream with its own OHS + PL, the integration
event billing.payment.captured.v1 (domain event PaymentCaptured). Sales, the
core, protects itself with a thin ACL that calls Order.MarkPaid. Not C/S:
Context Mapper rule #7 advises against an ACL inside customer-supplier. */
Sales [D,ACL]<-[U,OHS,PL] Billing {
implementationTechnology = "AMQP events: billing.payment.captured.v1"
}
/* Tiny shared kernel: Money, Currency, rounding rule. */
Sales [SK]<->[SK] Billing
/* Sales takes Catalog's product model as-is. */
Sales [D,CF]<-[U] Catalog {
implementationTechnology = "REST: GET /products/{sku}"
}
/* Generic subdomain behind a standard protocol (OpenID Connect). */
Sales [D,CF]<-[U,OHS,PL] Identity
Billing [D,CF]<-[U,OHS,PL] Identity
/* The ERP is a big ball of mud; Sales protects itself. */
Sales [D,ACL]<-[U] LegacyERP {
implementationTechnology = "HTTP export: GET /export/kunde/{kunnr}"
}
}
BoundedContext Sales
BoundedContext Fulfilment
BoundedContext Billing
BoundedContext Catalog
BoundedContext Identity
BoundedContext LegacyERPThe published language files
The Sales OHS publishes one contract in three views: JSON Schema (source of truth), Protobuf (for binary consumers), AsyncAPI (the channel and operation).
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://contracts.shop.example/sales/order_placed.v1.schema.json",
"title": "sales.order.placed.v1",
"description": "Published Language of the Sales context. Additive changes only within v1; anything else is v2.",
"type": "object",
"required": ["event_id", "event_type", "occurred_at", "order_id", "customer_id", "currency", "total_minor", "lines"],
"properties": {
"event_id": { "type": "string" },
"event_type": { "type": "string", "const": "sales.order.placed.v1" },
"occurred_at": { "type": "string", "format": "date-time" },
"order_id": { "type": "string" },
"customer_id": { "type": "string" },
"currency": { "type": "string", "pattern": "^[A-Z]{3}$" },
"total_minor": { "type": "integer" },
"lines": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["sku", "quantity", "unit_price_minor"],
"properties": {
"sku": { "type": "string" },
"quantity": { "type": "integer", "minimum": 1 },
"unit_price_minor": { "type": "integer" }
}
}
},
"delivery_window": {
"type": "object",
"description": "Added in v1.1 for Fulfilment (customer-supplier request). Optional, so v1.0 consumers ignore it.",
"properties": {
"from": { "type": "string", "format": "date-time" },
"to": { "type": "string", "format": "date-time" }
}
}
}
}// Published Language of the Sales context, Protobuf form of sales.order.placed.v1.
// Rules: never renumber, never reuse a deleted number (reserve it), add fields only.
syntax = "proto3";
package shop.sales.v1;
option go_package = "shop.example/contracts/sales/v1;salesv1";
message OrderLine {
string sku = 1;
int32 quantity = 2;
int64 unit_price_minor = 3;
}
message DeliveryWindow {
string from = 1; // RFC 3339
string to = 2; // RFC 3339
}
message OrderPlaced {
string event_id = 1;
string occurred_at = 2; // RFC 3339
string order_id = 3;
string customer_id = 4;
string currency = 5; // ISO 4217
int64 total_minor = 6;
repeated OrderLine lines = 7;
DeliveryWindow delivery_window = 8; // added in v1.1, optional
reserved 9; // was "margin_minor": internal, removed before GA
reserved "margin_minor";
}# Open Host Service of the Sales context, described as AsyncAPI 3.0.
asyncapi: 3.0.0
info:
title: Sales events (Open Host Service)
version: 1.1.0
description: Events Sales publishes for any downstream context. Owned by the Sales team.
servers:
production:
host: broker.shop.internal:5672
protocol: amqp
channels:
orderPlaced:
address: sales.order.placed.v1
messages:
orderPlaced:
$ref: '#/components/messages/OrderPlaced'
operations:
publishOrderPlaced:
action: send
channel:
$ref: '#/channels/orderPlaced'
components:
messages:
OrderPlaced:
name: sales.order.placed.v1
contentType: application/json
payload:
$ref: './order_placed.v1.schema.json'Each downstream records the fields it reads. Sales' CI runs every file (contract test):
{
"consumer": "fulfilment",
"relationship": "customer-supplier",
"event": "sales.order.placed.v1",
"paths": ["order_id", "occurred_at", "lines[].sku", "lines[].quantity", "delivery_window.from", "delivery_window.to"]
}Finding hidden edges in the database
A shared database is an edge nobody drew. In PostgreSQL, with one role per context, grants and statistics show who touches whose tables:
-- Which roles can write tables in the sales schema? Anything but sales_app is an undrawn edge.
SELECT grantee, table_schema, table_name, privilege_type
FROM information_schema.role_table_grants
WHERE table_schema = 'sales'
AND privilege_type IN ('INSERT', 'UPDATE', 'DELETE')
AND grantee <> 'sales_app'
ORDER BY grantee, table_name;
-- Which sessions are reading sales tables right now, and from which application?
SELECT usename, application_name, left(query, 80) AS query
FROM pg_stat_activity
WHERE query ILIKE '%sales.%' AND usename <> 'sales_app';
-- Close the edge: BI keeps read access only to a published view, not to tables.
REVOKE SELECT ON ALL TABLES IN SCHEMA sales FROM bi_reader;
CREATE VIEW sales_published.orders_v1 AS
SELECT id AS order_id, customer_id, currency, total_minor, placed_at
FROM sales.orders;
GRANT USAGE ON SCHEMA sales_published TO bi_reader;
GRANT SELECT ON sales_published.orders_v1 TO bi_reader;Roles, grants and least privilege are covered in Database Security. The view is a published language in SQL form: a versioned, documented shape Sales promises to keep. It is a stepping stone; events are the destination.
Errors and failures at the edge
| What you see | Where | Meaning on the map | Handle as |
|---|---|---|---|
| HTTP 404 from the ERP export | ACL adapter | Upstream says "no such record" | Translate to sales.ErrCustomerNotFound / CustomerNotFound |
HTTP 5xx, context deadline exceeded, Laravel ConnectionException | ACL adapter | Upstream unavailable | Availability error, retry with backoff; never "not found" |
protoc: field number reserved | PL .proto | Someone reused a deleted field number | Pick a new number; Protobuf "will generate error messages if any future developers try to use these reserved field numbers" |
| Contract test: "fulfilment needs lines[].quantity" | Supplier CI | Customer-supplier contract broken | Do not merge; keep field or plan v2 |
| JSON decode error in consumer | Conformist consumer | PL changed incompatibly or bad producer | Dead-letter the message (DLQ); alert upstream |
Unknown event_type | Consumer | Wrong routing or new version | Reject; route v2 to its own handler |
Go
One Go module (academy/context-maps-integration-patterns), standard library only. Each package is one end of an edge on the map.
The ACL: adapter, translator, facade
The Sales model owns the port; it never sees ERP names.
// Package sales is the Sales bounded context (core). Its model speaks Sales
// language only; nothing here knows the ERP, Billing or the broker.
package sales
import (
"context"
"errors"
"academy/context-maps-integration-patterns/kernel"
)
// ErrCustomerNotFound is the Sales-language "no such customer".
var ErrCustomerNotFound = errors.New("sales: customer not found")
// CustomerID identifies a customer inside Sales.
type CustomerID string
// CreditStatus is what Sales needs to decide whether an order may be placed
// on account. The ERP has no such concept; the ACL derives it.
type CreditStatus int
const (
CreditUnknown CreditStatus = iota
CreditGood
CreditOnHold
CreditBlocked
)
func (s CreditStatus) String() string {
return [...]string{"unknown", "good", "on_hold", "blocked"}[s]
}
// Customer is the Sales view of a customer.
type Customer struct {
ID CustomerID
DisplayName string
Segment string // "consumer" or "business"
CreditLimit kernel.Money
Credit CreditStatus
}
// MayOrderOnAccount is a Sales rule, written in Sales words.
func (c Customer) MayOrderOnAccount(total kernel.Money) bool {
return c.Credit == CreditGood && c.CreditLimit.Currency == total.Currency && total.Minor <= c.CreditLimit.Minor
}
// CustomerDirectory is the port Sales depends on. The ERP ACL implements it.
type CustomerDirectory interface {
CustomerByID(ctx context.Context, id CustomerID) (Customer, error)
}The adapter speaks HTTP to the ERP and returns the raw record:
// Package erp is the Anticorruption Layer between Sales and the legacy ERP.
// Three parts, each with one job:
//
// client.go adapter: speaks the ERP's protocol and returns ERP records
// translator.go translator: ERP record -> Sales model (pure, no I/O)
// directory.go facade: implements sales.CustomerDirectory for the rest of Sales
//
// Nothing outside this package imports Record or the ERP field names.
package erp
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"time"
)
// errNotFound is the adapter's "404"; the facade maps it to Sales language.
var errNotFound = errors.New("erp: record not found")
// Record is the customer master record exactly as the ERP exports it.
// SAP-style field names; every value is a string, as the export delivers it.
type Record struct {
KUNNR string `json:"KUNNR"` // customer number, zero-padded to 10
NAME1 string `json:"NAME1"` // name line 1
NAME2 string `json:"NAME2"` // name line 2
KTOKD string `json:"KTOKD"` // account group: Z001 consumer, Z002 business
KLIMK string `json:"KLIMK"` // credit limit, decimal string "1500.00"
WAERS string `json:"WAERS"` // currency key
SPERR string `json:"SPERR"` // "X" = posting block
CRBLB string `json:"CRBLB"` // "X" = credit block (on hold)
}
// Client is the adapter: it knows URLs, timeouts and status codes, nothing else.
type Client struct {
BaseURL string
HTTP *http.Client
}
// NewClient returns an adapter with a bounded timeout: the ERP is slow.
func NewClient(base string) *Client {
return &Client{BaseURL: base, HTTP: &http.Client{Timeout: 2 * time.Second}}
}
// FetchCustomer calls GET /export/kunde/{kunnr}.
func (c *Client) FetchCustomer(ctx context.Context, kunnr string) (Record, error) {
u := c.BaseURL + "/export/kunde/" + url.PathEscape(kunnr)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return Record{}, err
}
res, err := c.HTTP.Do(req)
if err != nil {
return Record{}, fmt.Errorf("erp: call failed: %w", err)
}
defer res.Body.Close()
switch {
case res.StatusCode == http.StatusNotFound:
return Record{}, errNotFound
case res.StatusCode != http.StatusOK:
return Record{}, fmt.Errorf("erp: unexpected status %d", res.StatusCode)
}
var r Record
if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
return Record{}, fmt.Errorf("erp: bad payload: %w", err)
}
return r, nil
}The translator is a pure function: identifiers, decimals, flags and account groups become Sales concepts.
package erp
import (
"fmt"
"strconv"
"strings"
"academy/context-maps-integration-patterns/kernel"
"academy/context-maps-integration-patterns/sales"
)
// ToKUNNR maps a Sales id ("cus_77") to the ERP key ("0000000077").
func ToKUNNR(id sales.CustomerID) (string, error) {
n := strings.TrimPrefix(string(id), "cus_")
if n == string(id) || n == "" {
return "", fmt.Errorf("erp: %q is not a Sales customer id", id)
}
if _, err := strconv.ParseUint(n, 10, 64); err != nil {
return "", fmt.Errorf("erp: %q is not numeric", id)
}
if len(n) > 10 {
return "", fmt.Errorf("erp: %q is longer than KUNNR allows", id)
}
return strings.Repeat("0", 10-len(n)) + n, nil
}
// Translate turns an ERP record into the Sales Customer. Pure function: no
// I/O, so every legacy quirk gets a table-driven test.
func Translate(r Record) (sales.Customer, error) {
n := strings.TrimLeft(strings.TrimSpace(r.KUNNR), "0")
if n == "" {
return sales.Customer{}, fmt.Errorf("erp: empty KUNNR")
}
limit, err := parseAmount(r.KLIMK, kernel.Currency(strings.TrimSpace(r.WAERS)))
if err != nil {
return sales.Customer{}, err
}
return sales.Customer{
ID: sales.CustomerID("cus_" + n),
DisplayName: strings.TrimSpace(strings.TrimSpace(r.NAME1) + " " + strings.TrimSpace(r.NAME2)),
Segment: segment(r.KTOKD),
CreditLimit: limit,
Credit: credit(r.SPERR, r.CRBLB),
}, nil
}
// segment: the ERP's account groups become Sales segments.
func segment(ktokd string) string {
switch strings.TrimSpace(ktokd) {
case "Z002":
return "business"
default: // Z001 and every group nobody documented
return "consumer"
}
}
// credit derives a Sales concept from two ERP flags. A posting block beats a
// credit block.
func credit(sperr, crblb string) sales.CreditStatus {
switch {
case strings.TrimSpace(sperr) == "X":
return sales.CreditBlocked
case strings.TrimSpace(crblb) == "X":
return sales.CreditOnHold
default:
return sales.CreditGood
}
}
// parseAmount reads "1500.00", "1.500,00" or "" (no limit = 0) into minor units.
func parseAmount(s string, c kernel.Currency) (kernel.Money, error) {
s = strings.TrimSpace(s)
if s == "" {
return kernel.New(0, c)
}
if strings.Contains(s, ",") { // German export: 1.500,00
s = strings.ReplaceAll(s, ".", "")
s = strings.ReplaceAll(s, ",", ".")
}
whole, frac, _ := strings.Cut(s, ".")
frac = (frac + "00")[:2]
minor, err := strconv.ParseInt(whole+frac, 10, 64)
if err != nil {
return kernel.Money{}, fmt.Errorf("erp: bad KLIMK %q: %w", s, err)
}
return kernel.New(minor, c)
}The facade implements the port and translates errors:
package erp
import (
"context"
"errors"
"fmt"
"academy/context-maps-integration-patterns/sales"
)
// fetcher is what the facade needs from the adapter (lets tests swap it).
type fetcher interface {
FetchCustomer(ctx context.Context, kunnr string) (Record, error)
}
// Directory is the facade: the only type the rest of Sales sees, through the
// sales.CustomerDirectory port.
type Directory struct{ erp fetcher }
// NewDirectory wires the facade to an adapter.
func NewDirectory(f fetcher) *Directory { return &Directory{erp: f} }
var _ sales.CustomerDirectory = (*Directory)(nil)
// CustomerByID answers in Sales language and Sales errors only.
func (d *Directory) CustomerByID(ctx context.Context, id sales.CustomerID) (sales.Customer, error) {
kunnr, err := ToKUNNR(id)
if err != nil {
return sales.Customer{}, sales.ErrCustomerNotFound
}
rec, err := d.erp.FetchCustomer(ctx, kunnr)
if errors.Is(err, errNotFound) {
return sales.Customer{}, sales.ErrCustomerNotFound
}
if err != nil {
return sales.Customer{}, fmt.Errorf("customer directory unavailable: %w", err)
}
return Translate(rec)
}Tests: a table of legacy quirks, and the whole layer against a fake ERP over real HTTP.
package erp
import (
"testing"
"academy/context-maps-integration-patterns/sales"
)
func TestTranslateLegacyQuirks(t *testing.T) {
cases := []struct {
name string
rec Record
wantID sales.CustomerID
wantSeg string
wantMinor int64
wantCredit sales.CreditStatus
}{
{"business, dot decimal", Record{KUNNR: "0000000077", NAME1: "Acme ", NAME2: "GmbH", KTOKD: "Z002", KLIMK: "1500.00", WAERS: "EUR"}, "cus_77", "business", 150000, sales.CreditGood},
{"german decimal", Record{KUNNR: "0000000078", NAME1: "Kim", KTOKD: "Z001", KLIMK: "1.500,5", WAERS: "EUR"}, "cus_78", "consumer", 150050, sales.CreditGood},
{"no limit, credit block", Record{KUNNR: "0000000079", NAME1: "Lee", KTOKD: "Z001", KLIMK: "", WAERS: "EUR", CRBLB: "X"}, "cus_79", "consumer", 0, sales.CreditOnHold},
{"posting block wins", Record{KUNNR: "0000000080", NAME1: "Ng", KTOKD: "Z009", KLIMK: "10", WAERS: "USD", SPERR: "X", CRBLB: "X"}, "cus_80", "consumer", 1000, sales.CreditBlocked},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := Translate(c.rec)
if err != nil {
t.Fatal(err)
}
if got.ID != c.wantID || got.Segment != c.wantSeg || got.CreditLimit.Minor != c.wantMinor || got.Credit != c.wantCredit {
t.Fatalf("got %+v", got)
}
})
}
}
func TestTranslateRejectsGarbage(t *testing.T) {
if _, err := Translate(Record{KUNNR: "0000000081", KLIMK: "lots", WAERS: "EUR"}); err == nil {
t.Fatal("bad amount accepted")
}
if _, err := Translate(Record{KUNNR: "0000000082", KLIMK: "1", WAERS: "euro"}); err == nil {
t.Fatal("bad currency accepted")
}
}
func TestToKUNNR(t *testing.T) {
if k, _ := ToKUNNR("cus_77"); k != "0000000077" {
t.Fatalf("got %q", k)
}
if _, err := ToKUNNR("77"); err == nil {
t.Fatal("id without prefix accepted")
}
}package erp
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"academy/context-maps-integration-patterns/sales"
)
// A fake ERP over real HTTP: tests the adapter, translator and facade together.
func fakeERP(t *testing.T) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/export/kunde/0000000077":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"KUNNR":"0000000077","NAME1":"Acme","NAME2":"GmbH","KTOKD":"Z002","KLIMK":"1500.00","WAERS":"EUR","SPERR":"","CRBLB":""}`))
case "/export/kunde/0000000500":
w.WriteHeader(http.StatusInternalServerError)
default:
w.WriteHeader(http.StatusNotFound)
}
}))
}
func TestDirectorySpeaksSalesLanguage(t *testing.T) {
srv := fakeERP(t)
defer srv.Close()
dir := NewDirectory(NewClient(srv.URL))
ctx := context.Background()
c, err := dir.CustomerByID(ctx, "cus_77")
if err != nil || c.DisplayName != "Acme GmbH" || c.Credit != sales.CreditGood {
t.Fatalf("got %+v, %v", c, err)
}
if _, err := dir.CustomerByID(ctx, "cus_1"); !errors.Is(err, sales.ErrCustomerNotFound) {
t.Fatalf("404 should become sales.ErrCustomerNotFound, got %v", err)
}
if _, err := dir.CustomerByID(ctx, "cus_500"); err == nil || errors.Is(err, sales.ErrCustomerNotFound) {
t.Fatalf("500 should be an availability error, got %v", err)
}
}The OHS and its published language
The Go binding of the published language:
// Package orderplaced holds the Go binding of the Published Language
// sales.order.placed.v1. The JSON Schema in contracts/sales is the source of
// truth; this file mirrors it and contract_test.go keeps them in step.
package orderplaced
// EventType is the wire name, also the broker routing key.
const EventType = "sales.order.placed.v1"
// Line is one order line on the wire.
type Line struct {
SKU string `json:"sku"`
Quantity int64 `json:"quantity"`
UnitPriceMinor int64 `json:"unit_price_minor"`
}
// Window is the delivery window (added in v1.1, optional).
type Window struct {
From string `json:"from"`
To string `json:"to"`
}
// V1 is the event payload. Additive changes only; a breaking change is V2 on
// a new routing key, published in parallel until consumers have moved.
type V1 struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
OccurredAt string `json:"occurred_at"`
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
Currency string `json:"currency"`
TotalMinor int64 `json:"total_minor"`
Lines []Line `json:"lines"`
DeliveryWindow *Window `json:"delivery_window,omitempty"`
}The Sales order holds internal data that must not leak:
package sales
import (
"time"
"academy/context-maps-integration-patterns/kernel"
)
// Line is one order line in the Sales model.
type Line struct {
SKU string
Quantity int64
UnitPrice kernel.Money
}
// Order is the Sales aggregate, reduced to what this chapter needs. It holds
// internal data (MarginMinor, SalesRep) that must never leak into the
// published language.
type Order struct {
ID string
CustomerID CustomerID
Lines []Line
PlacedAt time.Time
DeliverFrom time.Time
DeliverTo time.Time
MarginMinor int64 // internal: commercial secret
SalesRep string // internal: commission
}
// Total sums the lines. Errors on mixed currencies.
func (o Order) Total() (kernel.Money, error) {
if len(o.Lines) == 0 {
return kernel.Money{}, nil
}
total := kernel.Money{Currency: o.Lines[0].UnitPrice.Currency}
for _, l := range o.Lines {
var err error
if total, err = total.Add(l.UnitPrice.Times(l.Quantity)); err != nil {
return kernel.Money{}, err
}
}
return total, nil
}The publisher maps outbound and writes to the outbox:
// Package ohs is the Open Host Service of Sales: one protocol for every
// downstream, expressed in the published language, never in the internal model.
package ohs
import (
"context"
"encoding/json"
"time"
"academy/context-maps-integration-patterns/contracts/orderplaced"
"academy/context-maps-integration-patterns/sales"
)
// Outbox stores the message in the same transaction as the order; a relay
// publishes it later (see the Transactional Outbox chapter).
type Outbox interface {
Add(ctx context.Context, routingKey string, payload []byte) error
}
// Publisher maps internal orders to the published language.
type Publisher struct {
Outbox Outbox
NewID func() string
}
// ToV1 is the outbound translation: internal Order -> published language.
// MarginMinor and SalesRep stay inside Sales.
func ToV1(eventID string, o sales.Order) (orderplaced.V1, error) {
total, err := o.Total()
if err != nil {
return orderplaced.V1{}, err
}
ev := orderplaced.V1{
EventID: eventID,
EventType: orderplaced.EventType,
OccurredAt: o.PlacedAt.UTC().Format(time.RFC3339),
OrderID: o.ID,
CustomerID: string(o.CustomerID),
Currency: string(total.Currency),
TotalMinor: total.Minor,
}
for _, l := range o.Lines {
ev.Lines = append(ev.Lines, orderplaced.Line{SKU: l.SKU, Quantity: l.Quantity, UnitPriceMinor: l.UnitPrice.Minor})
}
if !o.DeliverFrom.IsZero() {
ev.DeliveryWindow = &orderplaced.Window{
From: o.DeliverFrom.UTC().Format(time.RFC3339),
To: o.DeliverTo.UTC().Format(time.RFC3339),
}
}
return ev, nil
}
// OrderPlaced writes the event to the outbox.
func (p Publisher) OrderPlaced(ctx context.Context, o sales.Order) error {
ev, err := ToV1(p.NewID(), o)
if err != nil {
return err
}
b, err := json.Marshal(ev)
if err != nil {
return err
}
return p.Outbox.Add(ctx, orderplaced.EventType, b)
}The conformist consumer
Billing uses the published types as its input model, deduplicates by event_id, and computes VAT with the shared-kernel rule:
// Package billing is a Conformist downstream of the Sales open host service:
// it uses the published language types as its own input model, with no
// translation layer. That is cheap and fine while the PL is stable and
// Billing's needs are a subset of it.
package billing
import (
"encoding/json"
"fmt"
"sync"
"academy/context-maps-integration-patterns/contracts/orderplaced"
"academy/context-maps-integration-patterns/kernel"
)
// VATBasisPoints is 19% for this example.
const VATBasisPoints = 1900
// InvoiceDraft is Billing's record; its fields are named after the PL on purpose.
type InvoiceDraft struct {
OrderID string
CustomerID string
Net kernel.Money
VAT kernel.Money
}
// Handler consumes sales.order.placed.v1 at least once; it deduplicates by event_id.
type Handler struct {
mu sync.Mutex
seen map[string]bool
Invoices []InvoiceDraft
}
// NewHandler returns an empty handler.
func NewHandler() *Handler { return &Handler{seen: map[string]bool{}} }
// Handle decodes the published language directly (conformist) and drafts an invoice.
func (h *Handler) Handle(payload []byte) error {
var ev orderplaced.V1
if err := json.Unmarshal(payload, &ev); err != nil {
return fmt.Errorf("billing: undecodable %s: %w", orderplaced.EventType, err)
}
if ev.EventType != orderplaced.EventType {
return fmt.Errorf("billing: unexpected event type %q", ev.EventType)
}
h.mu.Lock()
defer h.mu.Unlock()
if h.seen[ev.EventID] {
return nil // redelivery
}
net, err := kernel.New(ev.TotalMinor, kernel.Currency(ev.Currency))
if err != nil {
return err
}
h.Invoices = append(h.Invoices, InvoiceDraft{
OrderID: ev.OrderID,
CustomerID: ev.CustomerID,
Net: net,
VAT: net.PercentOf(VATBasisPoints), // shared-kernel rounding rule
})
h.seen[ev.EventID] = true
return nil
}package billing
import (
"os"
"testing"
)
// Billing consumes the published example message, twice.
func TestConformistConsumerUsesPublishedExample(t *testing.T) {
payload, err := os.ReadFile("../../contracts/sales/order_placed.v1.example.json")
if err != nil {
t.Fatal(err)
}
h := NewHandler()
for i := 0; i < 2; i++ { // at-least-once delivery
if err := h.Handle(payload); err != nil {
t.Fatal(err)
}
}
if len(h.Invoices) != 1 {
t.Fatalf("want 1 invoice after redelivery, got %d", len(h.Invoices))
}
inv := h.Invoices[0]
if inv.Net.Minor != 4500 || inv.VAT.Minor != 855 || inv.Net.Currency != "EUR" {
t.Fatalf("got %+v", inv)
}
}The shared kernel and its versioning policy
// Package kernel is the Shared Kernel between Sales and Billing.
//
// What is in it: Money, Currency and the one rounding rule both contexts must
// agree on. Nothing else. No Order, no Customer, no Invoice.
//
// Versioning policy (co-owned by the Sales and Billing teams):
// - Semantic versioning; Version below is the single source of truth.
// - PATCH: bug fix, no behaviour change visible to callers.
// - MINOR: additive only (a new function or currency); both teams review.
// - MAJOR: any change to existing behaviour, including rounding; both teams
// must approve, and both upgrade in the same planning cycle.
// - Every change needs a green CI run in both contexts before it is tagged.
// - Owners: CODEOWNERS lists one reviewer from each team for this directory.
package kernel
import (
"errors"
"fmt"
)
// Version of the shared kernel. Bump according to the policy above.
const Version = "1.2.0"
// ErrCurrencyMismatch is returned when two amounts in different currencies meet.
var ErrCurrencyMismatch = errors.New("kernel: currency mismatch")
// Currency is an ISO 4217 code such as "EUR".
type Currency string
// Valid reports whether the code has three upper-case letters.
func (c Currency) Valid() bool {
if len(c) != 3 {
return false
}
for _, r := range c {
if r < 'A' || r > 'Z' {
return false
}
}
return true
}
// Money is an amount in minor units (cents) and a currency.
type Money struct {
Minor int64
Currency Currency
}
// New returns Money or an error for an invalid currency.
func New(minor int64, c Currency) (Money, error) {
if !c.Valid() {
return Money{}, fmt.Errorf("kernel: invalid currency %q", c)
}
return Money{Minor: minor, Currency: c}, nil
}
// Add sums two amounts of the same currency.
func (m Money) Add(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, ErrCurrencyMismatch
}
return Money{Minor: m.Minor + o.Minor, Currency: m.Currency}, nil
}
// Times multiplies by a quantity.
func (m Money) Times(q int64) Money { return Money{Minor: m.Minor * q, Currency: m.Currency} }
// PercentOf returns basisPoints/10000 of m, rounded half away from zero.
// This is THE rounding rule: Sales shows it on the cart, Billing puts it on
// the invoice. If the two ever disagree by one cent, customers complain.
func (m Money) PercentOf(basisPoints int64) Money {
n := m.Minor * basisPoints
q, r := n/10000, n%10000
if r >= 5000 {
q++
} else if r <= -5000 {
q--
}
return Money{Minor: q, Currency: m.Currency}
}package kernel
import "testing"
// These cases are the kernel's contract. Both teams run them in CI.
func TestRoundingRuleIsShared(t *testing.T) {
eur := Currency("EUR")
cases := []struct {
minor, bp, want int64
}{
{1000, 1900, 190}, // 19% VAT on 10.00
{1999, 1900, 380}, // 379.81 -> 380
{1050, 500, 53}, // 52.5 -> 53 (half away from zero)
{-1050, 500, -53}, // refunds round the same way
{1, 1900, 0}, // 0.19 cent -> 0
{4500, 0, 0}, // zero rate
{12345, 10000, 12345},
}
for _, c := range cases {
got := Money{Minor: c.minor, Currency: eur}.PercentOf(c.bp)
if got.Minor != c.want {
t.Errorf("PercentOf(%d, %d) = %d, want %d", c.minor, c.bp, got.Minor, c.want)
}
}
}
func TestAddRejectsMixedCurrencies(t *testing.T) {
a, _ := New(100, "EUR")
b, _ := New(100, "USD")
if _, err := a.Add(b); err != ErrCurrencyMismatch {
t.Fatalf("want ErrCurrencyMismatch, got %v", err)
}
}
func TestNewRejectsBadCurrency(t *testing.T) {
if _, err := New(1, "eur"); err == nil {
t.Fatal("lower-case code accepted")
}
}Contract tests across the edge
One test file checks four promises: the example and the real publisher output satisfy the schema; no internal field leaks; the Go binding and the schema list the same properties; every consumer's expectation file is satisfied.
package orderplaced_test
import (
"encoding/json"
"os"
"path/filepath"
"reflect"
"regexp"
"strings"
"testing"
"time"
"academy/context-maps-integration-patterns/contracts/orderplaced"
"academy/context-maps-integration-patterns/kernel"
"academy/context-maps-integration-patterns/sales"
"academy/context-maps-integration-patterns/sales/ohs"
)
const dir = "../../../contracts/sales/"
func load(t *testing.T, name string) any {
t.Helper()
b, err := os.ReadFile(dir + name)
if err != nil {
t.Fatal(err)
}
var v any
if err := json.Unmarshal(b, &v); err != nil {
t.Fatal(err)
}
return v
}
// validate checks the subset of JSON Schema used by our contracts: type,
// required, properties, items, const, pattern, minItems, minimum. A real
// project would use a full validator library; the idea is the same.
func validate(schema map[string]any, v any, path string) []string {
var errs []string
switch schema["type"] {
case "object":
obj, ok := v.(map[string]any)
if !ok {
return []string{path + ": not an object"}
}
for _, r := range asSlice(schema["required"]) {
if _, ok := obj[r.(string)]; !ok {
errs = append(errs, path+"."+r.(string)+": required")
}
}
props, _ := schema["properties"].(map[string]any)
for k, val := range obj {
if ps, ok := props[k].(map[string]any); ok {
errs = append(errs, validate(ps, val, path+"."+k)...)
}
}
case "array":
arr, ok := v.([]any)
if !ok {
return []string{path + ": not an array"}
}
if m, ok := schema["minItems"].(float64); ok && float64(len(arr)) < m {
errs = append(errs, path+": too few items")
}
if is, ok := schema["items"].(map[string]any); ok {
for _, it := range arr {
errs = append(errs, validate(is, it, path+"[]")...)
}
}
case "string":
s, ok := v.(string)
if !ok {
return []string{path + ": not a string"}
}
if c, ok := schema["const"].(string); ok && s != c {
errs = append(errs, path+": must be "+c)
}
if p, ok := schema["pattern"].(string); ok && !regexp.MustCompile(p).MatchString(s) {
errs = append(errs, path+": does not match "+p)
}
case "integer":
n, ok := v.(float64)
if !ok || n != float64(int64(n)) {
return []string{path + ": not an integer"}
}
if m, ok := schema["minimum"].(float64); ok && n < m {
errs = append(errs, path+": below minimum")
}
}
return errs
}
func asSlice(v any) []any { s, _ := v.([]any); return s }
func sampleOrder() sales.Order {
eur := kernel.Currency("EUR")
at := time.Date(2026, 11, 25, 10, 15, 0, 0, time.UTC)
return sales.Order{
ID: "ord_1042", CustomerID: "cus_77", PlacedAt: at,
DeliverFrom: at.Add(46 * time.Hour), DeliverTo: at.Add(50 * time.Hour),
Lines: []sales.Line{
{SKU: "MUG-RED", Quantity: 2, UnitPrice: kernel.Money{Minor: 1250, Currency: eur}},
{SKU: "TEA-ASSAM", Quantity: 1, UnitPrice: kernel.Money{Minor: 2000, Currency: eur}},
},
MarginMinor: 1900, SalesRep: "rep-12",
}
}
func publisherOutput(t *testing.T) any {
t.Helper()
ev, err := ohs.ToV1("evt_test", sampleOrder())
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(ev)
var v any
_ = json.Unmarshal(b, &v)
return v
}
// The published example and the real publisher output both satisfy the schema.
func TestPublishedLanguageSchema(t *testing.T) {
schema := load(t, "order_placed.v1.schema.json").(map[string]any)
for name, doc := range map[string]any{"example": load(t, "order_placed.v1.example.json"), "publisher": publisherOutput(t)} {
if errs := validate(schema, doc, "$"); len(errs) > 0 {
t.Errorf("%s violates the published language: %v", name, errs)
}
}
}
// Internal Sales data never leaks into the published language.
func TestNoInternalFieldsLeak(t *testing.T) {
out := publisherOutput(t).(map[string]any)
for _, k := range []string{"margin_minor", "MarginMinor", "sales_rep", "SalesRep"} {
if _, ok := out[k]; ok {
t.Errorf("internal field %q leaked", k)
}
}
}
// Every property in the schema has a JSON tag in the Go binding, and back.
func TestGoBindingMatchesSchema(t *testing.T) {
schema := load(t, "order_placed.v1.schema.json").(map[string]any)
props := schema["properties"].(map[string]any)
tags := map[string]bool{}
typ := reflect.TypeOf(orderplaced.V1{})
for i := 0; i < typ.NumField(); i++ {
tag, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
tags[tag] = true
if _, ok := props[tag]; !ok {
t.Errorf("Go field %s (%q) not in schema", typ.Field(i).Name, tag)
}
}
for p := range props {
if !tags[p] {
t.Errorf("schema property %q missing in Go binding", p)
}
}
}
// Consumer-driven contracts: each downstream lists the paths it reads; the
// supplier's CI (this test) fails before a release that would break them.
func TestConsumerExpectations(t *testing.T) {
files, _ := filepath.Glob(dir + "consumers/*.expects.json")
if len(files) == 0 {
t.Fatal("no consumer expectations found")
}
out := publisherOutput(t)
for _, f := range files {
exp := load(t, "consumers/"+filepath.Base(f)).(map[string]any)
for _, p := range asSlice(exp["paths"]) {
if !has(out, strings.Split(p.(string), ".")) {
t.Errorf("%s needs %q, publisher does not provide it", exp["consumer"], p)
}
}
}
}
func has(v any, path []string) bool {
if len(path) == 0 {
return true
}
key := path[0]
if strings.HasSuffix(key, "[]") {
obj, ok := v.(map[string]any)
if !ok {
return false
}
arr, ok := obj[strings.TrimSuffix(key, "[]")].([]any)
if !ok || len(arr) == 0 {
return false
}
return has(arr[0], path[1:])
}
obj, ok := v.(map[string]any)
if !ok {
return false
}
next, ok := obj[key]
return ok && has(next, path[1:])
}The Go angle
- Packages are the seams.
sales/acl/erpis the only package that knows ERP field names;contracts/orderplacedis the only one Billing imports from Sales. Go'sinternal/directory can make that rule compiler-enforced (move the ERP record intosales/acl/erp/internal/). - Ports as small interfaces.
sales.CustomerDirectoryhas one method; the facade satisfies it implicitly (var _ sales.CustomerDirectory = (*Directory)(nil)documents it). net/http/httptestgives you a fake upstream over real HTTP, so adapter, translator and facade are tested together without the ERP.context.Contextcarries the deadline into the adapter;http.Client.Timeoutbounds the slow legacy call.- Schemas:
encoding/jsonstruct tags are the binding; a full JSON Schema validator orprotoc-gen-gogenerated types are the production options. The shared kernel is a separate Go module in real life (go get shop.example/kernel@v1.2.0), so its version is visible in each context'sgo.mod. - Watermill or a plain AMQP client carries the events; the pattern does not depend on the library.
Laravel
Laravel 13, PHP 8.4. Contexts are modules under app/Modules/<Context>; the shared kernel is a Composer path package.
The ACL: adapter, translator, facade
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
/** Port owned by Sales. The ERP anticorruption layer implements it. */
interface CustomerDirectory
{
/**
* @throws CustomerNotFound the customer does not exist
* @throws CustomerDirectoryUnavailable the source cannot be asked right now
*/
public function customerById(string $id): Customer;
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use RuntimeException;
/** Sales-language "we cannot ask right now"; never confused with "not found". */
final class CustomerDirectoryUnavailable extends RuntimeException {}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use Shop\SharedKernel\Money;
/** The Sales view of a customer. No ERP field name appears here. */
final readonly class Customer
{
public function __construct(
public string $id, // "cus_77"
public string $displayName,
public string $segment, // "consumer" | "business"
public Money $creditLimit,
public CreditStatus $credit,
) {}
public function mayOrderOnAccount(Money $total): bool
{
return $this->credit === CreditStatus::Good
&& $total->currency === $this->creditLimit->currency
&& $total->minor <= $this->creditLimit->minor;
}
}The adapter uses the HTTP client's timeout, connectTimeout, retry and throw (all documented on the Laravel 13 HTTP client page):
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Acl\Erp;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Adapter: speaks the ERP's export protocol and returns the raw record.
* Knows URLs, timeouts and status codes; knows nothing about Sales.
*/
final class ErpCustomerClient
{
public function __construct(private readonly string $baseUrl) {}
/**
* @return array<string, string>|null the KNA1-style record, or null on 404
*
* @throws RequestException on any other failure
*/
public function fetch(string $kunnr): ?array
{
$response = Http::baseUrl($this->baseUrl)
->acceptJson()
->connectTimeout(1)
->timeout(2)
// Retry only what can heal: network errors and 5xx, never a 404.
->retry(2, 200, fn (Throwable $e) => $e instanceof ConnectionException
|| ($e instanceof RequestException && $e->response->serverError()), throw: false)
->get('/export/kunde/'.rawurlencode($kunnr));
if ($response->status() === 404) {
return null;
}
return $response->throw()->json();
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Acl\Erp;
use App\Modules\Sales\Domain\CreditStatus;
use App\Modules\Sales\Domain\Customer;
use InvalidArgumentException;
use Shop\SharedKernel\Money;
/** Translator: ERP record -> Sales model. Pure; every quirk has a test. */
final class ErpCustomerTranslator
{
public static function toKunnr(string $salesId): string
{
if (preg_match('/^cus_(\d{1,10})$/', $salesId, $m) !== 1) {
throw new InvalidArgumentException("{$salesId} is not a Sales customer id");
}
return str_pad($m[1], 10, '0', STR_PAD_LEFT);
}
/** @param array<string, string> $r */
public function toCustomer(array $r): Customer
{
$number = ltrim(trim($r['KUNNR'] ?? ''), '0');
if ($number === '') {
throw new InvalidArgumentException('Empty KUNNR');
}
return new Customer(
id: 'cus_'.$number,
displayName: trim(trim($r['NAME1'] ?? '').' '.trim($r['NAME2'] ?? '')),
segment: trim($r['KTOKD'] ?? '') === 'Z002' ? 'business' : 'consumer',
creditLimit: $this->amount($r['KLIMK'] ?? '', trim($r['WAERS'] ?? '')),
credit: match (true) {
trim($r['SPERR'] ?? '') === 'X' => CreditStatus::Blocked,
trim($r['CRBLB'] ?? '') === 'X' => CreditStatus::OnHold,
default => CreditStatus::Good,
},
);
}
/** "1500.00", "1.500,00" or "" (no limit) -> minor units. */
private function amount(string $raw, string $currency): Money
{
$s = trim($raw);
if ($s === '') {
return new Money(0, $currency);
}
if (str_contains($s, ',')) {
$s = str_replace(['.', ','], ['', '.'], $s);
}
if (preg_match('/^(-?\d+)(?:\.(\d{1,2}))?$/', $s, $m) !== 1) {
throw new InvalidArgumentException("Bad KLIMK {$raw}");
}
return new Money((int) ($m[1].str_pad($m[2] ?? '', 2, '0')), $currency);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Acl\Erp;
use App\Modules\Sales\Domain\Customer;
use App\Modules\Sales\Domain\CustomerDirectory;
use App\Modules\Sales\Domain\CustomerDirectoryUnavailable;
use App\Modules\Sales\Domain\CustomerNotFound;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use InvalidArgumentException;
/**
* Facade: the only ACL class the rest of Sales sees (through the port).
* Errors are translated too: no Laravel HTTP exception crosses the port.
*/
final class ErpCustomerDirectory implements CustomerDirectory
{
public function __construct(
private readonly ErpCustomerClient $client,
private readonly ErpCustomerTranslator $translator,
) {}
public function customerById(string $id): Customer
{
try {
$kunnr = ErpCustomerTranslator::toKunnr($id);
} catch (InvalidArgumentException) {
throw new CustomerNotFound($id);
}
try {
$record = $this->client->fetch($kunnr);
} catch (ConnectionException|RequestException $e) {
throw new CustomerDirectoryUnavailable('ERP customer export unavailable', previous: $e);
}
if ($record === null) {
throw new CustomerNotFound($id);
}
return $this->translator->toCustomer($record);
}
}The provider wires the edge: the Sales port is bound to the ERP ACL.
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Modules\Sales\Acl\Erp\ErpCustomerClient;
use App\Modules\Sales\Acl\Erp\ErpCustomerDirectory;
use App\Modules\Sales\Acl\Erp\ErpCustomerTranslator;
use App\Modules\Sales\Domain\CustomerDirectory;
use Illuminate\Support\ServiceProvider;
/** Wires each edge of the context map to its implementation. */
final class ContextMapServiceProvider extends ServiceProvider
{
public function register(): void
{
// Sales <- LegacyERP: anticorruption layer behind a Sales-owned port.
$this->app->singleton(CustomerDirectory::class, fn () => new ErpCustomerDirectory(
new ErpCustomerClient(config('services.erp.base_url')),
new ErpCustomerTranslator(),
));
}
}Tests with Pest; Http::fake stands in for the ERP:
<?php
declare(strict_types=1);
use App\Modules\Sales\Acl\Erp\ErpCustomerClient;
use App\Modules\Sales\Acl\Erp\ErpCustomerDirectory;
use App\Modules\Sales\Acl\Erp\ErpCustomerTranslator;
use App\Modules\Sales\Domain\CreditStatus;
use App\Modules\Sales\Domain\CustomerDirectoryUnavailable;
use App\Modules\Sales\Domain\CustomerNotFound;
use Illuminate\Support\Facades\Http;
describe('translator', function () {
it('translates legacy quirks into Sales language', function (array $record, string $id, string $segment, int $limit, CreditStatus $credit) {
$c = (new ErpCustomerTranslator())->toCustomer($record);
expect($c->id)->toBe($id)
->and($c->segment)->toBe($segment)
->and($c->creditLimit->minor)->toBe($limit)
->and($c->credit)->toBe($credit);
})->with([
'business, dot decimal' => [['KUNNR' => '0000000077', 'NAME1' => 'Acme', 'KTOKD' => 'Z002', 'KLIMK' => '1500.00', 'WAERS' => 'EUR'], 'cus_77', 'business', 150000, CreditStatus::Good],
'german decimal' => [['KUNNR' => '0000000078', 'NAME1' => 'Kim', 'KTOKD' => 'Z001', 'KLIMK' => '1.500,5', 'WAERS' => 'EUR'], 'cus_78', 'consumer', 150050, CreditStatus::Good],
'credit block' => [['KUNNR' => '0000000079', 'NAME1' => 'Lee', 'KTOKD' => 'Z001', 'KLIMK' => '', 'WAERS' => 'EUR', 'CRBLB' => 'X'], 'cus_79', 'consumer', 0, CreditStatus::OnHold],
'posting block wins' => [['KUNNR' => '0000000080', 'NAME1' => 'Ng', 'KTOKD' => 'Z009', 'KLIMK' => '10', 'WAERS' => 'USD', 'SPERR' => 'X', 'CRBLB' => 'X'], 'cus_80', 'consumer', 1000, CreditStatus::Blocked],
]);
it('maps ids both ways', function () {
expect(ErpCustomerTranslator::toKunnr('cus_77'))->toBe('0000000077');
});
});
describe('directory (facade + adapter + translator)', function () {
beforeEach(function () {
Http::fake([
'erp.test/export/kunde/0000000077' => Http::response([
'KUNNR' => '0000000077', 'NAME1' => 'Acme', 'NAME2' => 'GmbH', 'KTOKD' => 'Z002',
'KLIMK' => '1500.00', 'WAERS' => 'EUR', 'SPERR' => '', 'CRBLB' => '',
], 200),
'erp.test/export/kunde/0000000500' => Http::response([], 500),
'erp.test/*' => Http::response([], 404),
]);
$this->directory = new ErpCustomerDirectory(new ErpCustomerClient('https://erp.test'), new ErpCustomerTranslator());
});
it('answers in Sales language', function () {
$c = $this->directory->customerById('cus_77');
expect($c->displayName)->toBe('Acme GmbH')->and($c->credit)->toBe(CreditStatus::Good);
});
it('turns an ERP 404 into a Sales exception', function () {
$this->directory->customerById('cus_1');
})->throws(CustomerNotFound::class);
it('turns an ERP 5xx into "unavailable", never "not found"', function () {
$this->directory->customerById('cus_500');
})->throws(CustomerDirectoryUnavailable::class);
});The OHS, the published language and the conformist job
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Contracts;
/**
* Published Language: sales.order.placed.v1. Mirrors
* contracts/sales/order_placed.v1.schema.json, which is the source of truth.
* Additive changes only; a breaking change is OrderPlacedV2 on a new key.
*/
final readonly class OrderPlacedV1
{
public const string TYPE = 'sales.order.placed.v1';
/** @param list<array{sku: string, quantity: int, unit_price_minor: int}> $lines */
public function __construct(
public string $eventId,
public string $occurredAt,
public string $orderId,
public string $customerId,
public string $currency,
public int $totalMinor,
public array $lines,
public ?array $deliveryWindow = null, // v1.1, optional: {from, to}
) {}
/** @return array<string, mixed> */
public function toArray(): array
{
return array_filter([
'event_id' => $this->eventId,
'event_type' => self::TYPE,
'occurred_at' => $this->occurredAt,
'order_id' => $this->orderId,
'customer_id' => $this->customerId,
'currency' => $this->currency,
'total_minor' => $this->totalMinor,
'lines' => $this->lines,
'delivery_window' => $this->deliveryWindow,
], fn ($v) => $v !== null);
}
/** @param array<string, mixed> $p */
public static function fromArray(array $p): self
{
return new self(
eventId: $p['event_id'],
occurredAt: $p['occurred_at'],
orderId: $p['order_id'],
customerId: $p['customer_id'],
currency: $p['currency'],
totalMinor: $p['total_minor'],
lines: $p['lines'],
deliveryWindow: $p['delivery_window'] ?? null,
);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Ohs;
use App\Modules\Sales\Contracts\OrderPlacedV1;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Open Host Service: maps the internal order to the published language and
* stores it in the outbox inside the caller's transaction. A relay publishes
* the outbox to the broker (see the Transactional Outbox chapter).
*/
final class OrderPlacedPublisher
{
/**
* @param array{id: string, customer_id: string, currency: string, placed_at: \DateTimeInterface,
* lines: list<array{sku: string, quantity: int, unit_price_minor: int}>,
* margin_minor: int, sales_rep: string,
* deliver_from?: \DateTimeInterface, deliver_to?: \DateTimeInterface} $order
*/
public static function toV1(array $order, string $eventId): OrderPlacedV1
{
$total = array_sum(array_map(fn ($l) => $l['quantity'] * $l['unit_price_minor'], $order['lines']));
// margin_minor and sales_rep are internal: they are simply not mapped.
return new OrderPlacedV1(
eventId: $eventId,
occurredAt: $order['placed_at']->format(DATE_RFC3339),
orderId: $order['id'],
customerId: $order['customer_id'],
currency: $order['currency'],
totalMinor: $total,
lines: array_map(fn ($l) => [
'sku' => $l['sku'],
'quantity' => $l['quantity'],
'unit_price_minor' => $l['unit_price_minor'],
], $order['lines']),
deliveryWindow: isset($order['deliver_from'], $order['deliver_to']) ? [
'from' => $order['deliver_from']->format(DATE_RFC3339),
'to' => $order['deliver_to']->format(DATE_RFC3339),
] : null,
);
}
/** Call inside the same DB::transaction that saved the order. */
public function publish(array $order): void
{
$event = self::toV1($order, (string) Str::ulid());
DB::table('outbox')->insert([
'id' => $event->eventId,
'routing_key' => OrderPlacedV1::TYPE,
'payload' => json_encode($event->toArray(), JSON_THROW_ON_ERROR),
'created_at' => now(),
]);
}
}<?php
declare(strict_types=1);
namespace App\Modules\Billing\Jobs;
use App\Modules\Sales\Contracts\OrderPlacedV1;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Shop\SharedKernel\Money;
/**
* Billing is a Conformist downstream of the Sales OHS: it takes the published
* language class as its input model, with no translation of its own.
*/
final class CreateInvoiceFromOrderPlaced implements ShouldQueue
{
use Queueable;
private const int VAT_BASIS_POINTS = 1900;
/** @param array<string, mixed> $payload the decoded broker message */
public function __construct(public array $payload) {}
public function handle(): void
{
$event = OrderPlacedV1::fromArray($this->payload);
$net = new Money($event->totalMinor, $event->currency);
// Idempotent: the unique key on event_id absorbs redeliveries.
DB::table('billing_invoice_drafts')->insertOrIgnore([
'event_id' => $event->eventId,
'order_id' => $event->orderId,
'customer_id' => $event->customerId,
'currency' => $net->currency,
'net_minor' => $net->minor,
'vat_minor' => $net->percentOf(self::VAT_BASIS_POINTS)->minor, // shared-kernel rule
'created_at' => now(),
]);
}
}The shared kernel package
{
"name": "shop/shared-kernel",
"description": "Shared Kernel of Sales and Billing: Money, Currency, the rounding rule. Nothing else.",
"type": "library",
"version": "1.2.0",
"license": "proprietary",
"require": {
"php": "^8.4"
},
"autoload": {
"psr-4": {
"Shop\\SharedKernel\\": "src/"
}
},
"extra": {
"owners": ["team-sales", "team-billing"],
"versioning-policy": [
"SemVer. PATCH = fix with no visible behaviour change.",
"MINOR = additive only (new method, new currency); one reviewer from each team.",
"MAJOR = any change to existing behaviour, rounding included; both teams approve and upgrade in the same cycle.",
"A tag is cut only after both contexts' CI is green against the candidate."
]
}
}<?php
declare(strict_types=1);
namespace Shop\SharedKernel;
use InvalidArgumentException;
/**
* Shared Kernel (Sales + Billing). Amount in minor units and an ISO 4217 code.
* Same rules as the Go kernel package; the same test cases run in both CIs.
*/
final readonly class Money
{
public const string VERSION = '1.2.0';
public function __construct(
public int $minor,
public string $currency,
) {
if (preg_match('/^[A-Z]{3}$/', $currency) !== 1) {
throw new InvalidArgumentException("Invalid currency {$currency}");
}
}
public function add(self $other): self
{
if ($other->currency !== $this->currency) {
throw new InvalidArgumentException('Currency mismatch');
}
return new self($this->minor + $other->minor, $this->currency);
}
public function times(int $quantity): self
{
return new self($this->minor * $quantity, $this->currency);
}
/** basisPoints/10000 of the amount, rounded half away from zero: THE shared rule. */
public function percentOf(int $basisPoints): self
{
$n = $this->minor * $basisPoints;
$q = intdiv($n, 10000);
$r = $n % 10000;
if ($r >= 5000) {
$q++;
} elseif ($r <= -5000) {
$q--;
}
return new self($q, $this->currency);
}
}Contract tests across the edge
The PHP test reads the same schema, example and consumer files as the Go test: one published language, two implementations, one set of promises.
<?php
declare(strict_types=1);
use App\Modules\Sales\Contracts\OrderPlacedV1;
use App\Modules\Sales\Ohs\OrderPlacedPublisher;
// The same schema, example and consumer expectations the Go side tests against.
const CONTRACTS = __DIR__.'/../../../contracts/sales/';
function contract(string $file): array
{
return json_decode(file_get_contents(CONTRACTS.$file), true, flags: JSON_THROW_ON_ERROR);
}
function publishedSample(): array
{
$at = new DateTimeImmutable('2026-11-25T10:15:00Z');
return OrderPlacedPublisher::toV1([
'id' => 'ord_1042', 'customer_id' => 'cus_77', 'currency' => 'EUR', 'placed_at' => $at,
'lines' => [
['sku' => 'MUG-RED', 'quantity' => 2, 'unit_price_minor' => 1250],
['sku' => 'TEA-ASSAM', 'quantity' => 1, 'unit_price_minor' => 2000],
],
'margin_minor' => 1900, 'sales_rep' => 'rep-12',
'deliver_from' => $at->modify('+46 hours'), 'deliver_to' => $at->modify('+50 hours'),
], 'evt_test')->toArray();
}
it('publishes every required field of the schema', function () {
$schema = contract('order_placed.v1.schema.json');
expect(array_keys(publishedSample()))->toContain(...$schema['required']);
expect(publishedSample()['event_type'])->toBe(OrderPlacedV1::TYPE);
});
it('never leaks internal Sales fields', function () {
expect(publishedSample())
->not->toHaveKey('margin_minor')
->not->toHaveKey('sales_rep');
});
it('satisfies every consumer expectation (customer-supplier tests in the supplier CI)', function (string $file) {
$expects = contract('consumers/'.$file);
$event = publishedSample();
foreach ($expects['paths'] as $path) {
$value = $event;
foreach (explode('.', $path) as $key) {
if (str_ends_with($key, '[]')) {
$value = $value[substr($key, 0, -2)][0] ?? null;
} else {
$value = $value[$key] ?? null;
}
}
expect($value)->not->toBeNull("{$expects['consumer']} needs {$path}");
}
})->with(['fulfilment.expects.json', 'billing.expects.json']);
it('round-trips the published example', function () {
$example = contract('order_placed.v1.example.json');
expect(OrderPlacedV1::fromArray($example)->toArray())->toEqual($example);
});The Laravel angle
- Service container bindings are the map in code.
ContextMapServiceProvideris the one place where a Sales port meets an implementation; swapping the ERP ACL for a future Customer-context client is one line. - HTTP client:
Http::fakewithHttp::responsetests the adapter without the ERP;retry(..., throw: false)with awhencallback retries only network errors and 5xx. - Queues: the conformist consumer is a queued job (
ShouldQueue+Queueable);insertOrIgnoreon a uniqueevent_idmakes redelivery harmless (Idempotent Consumer). Dispatch withafterCommitor publish through an outbox. - Composer path repositories let the shared kernel live in the monorepo as
packages/shared-kernelwith its own version; both modules requireshop/shared-kernel: ^1.2. - Architecture tests (Pest
arch()) can forbidApp\Modules\Sales\Domainfrom usingApp\Modules\Sales\Acland forbid any module but Billing from depending on the Billing namespace.
Solving the classic problems
A legacy ERP is leaking into the core model
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| ACL inside the core service | Port + facade + adapter + translator (above) | Core stays clean; one place to change | Code to maintain; latency of the legacy call |
| ACL as its own service | Separate deployable translating for several consumers | Shared by many | Extra service, single point of failure (Microsoft) |
| Event-driven ACL | CDC on ERP tables, publish clean events | Decoupled from ERP uptime | CDC setup (Change Data Capture) |
| Conform | Use ERP records directly | Zero translation code | ERP model becomes your core model: avoid for core |
A SaaS provider's model (payments, tax, CRM)
Treat the provider as an upstream you cannot influence. Conform where its model is the standard of the domain (a payment intent's status values), and put an ACL in front where your core rules live (your Payment aggregate should not be the provider's charge object). Keep provider IDs as attributes, not identities, so a second provider can be added.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Thin ACL | Map provider objects to your Payment, map webhooks to your events | Switching providers is local | Mapping code |
| Conform at the edge, ACL at the core | Provider types inside the integration module only | Little code | Discipline: never import provider SDK in the domain |
A breaking change in a published language
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Do not break | Add optional fields only | No coordination | Schema accumulates fields |
| Versioned parallel publishing | Publish v1 and v2; deprecate v1 with a date | Consumers move on their schedule | Two outputs for a while |
| One-off translator | Special needs of one consumer handled outside the OHS (Evans) | OHS stays simple | Someone owns the translator |
| Consumer contract tests in CI | Fail the build before release | Catches it early | Requires consumers to write expectations |
The shared kernel keeps growing
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Written size limit | "Money, Currency, rounding: nothing else" in the package doc | Clear rule | Needs enforcement in review |
| Two-team CODEOWNERS | Every change needs both | Real co-ownership | Slower changes (intended) |
| Split it | Move one-sided code back to its context | Kernel shrinks | Some duplication |
| Replace with a PL | Shared schema instead of shared code | No release coupling | Each side writes its own code |
A conformist downstream is suffering
When upstream changes keep breaking you, insert an ACL at the seam where you confined the upstream types (that is why you confine them). If the upstream would listen, ask for Customer-Supplier status with contract tests.
A shared database between contexts
Mark it red, publish a view as an interim published language (see Mechanics), then move readers to events. Detailed migration: Data Ownership in Microservices and Microservices Data Patterns.
Choosing
| Situation | Pattern | Extra technique | Reason |
|---|---|---|---|
| Two teams must ship one feature together, once | Partnership (time-boxed) | Joint test suite, end date on the map | Failure of either is failure of both |
| A tiny concept must be identical on both sides | Shared Kernel | Versioning policy, both-team review | Divergence is a bug |
| Downstream needs things and upstream will listen | Customer-Supplier | Consumer contract tests in upstream CI | Planning, not hope |
| Upstream will not listen, its model is good | Conformist | Confine upstream types to one package | Cheapest integration |
| Upstream will not listen, its model is bad | Anticorruption Layer | Port + facade + adapter + translator | Protect your model |
| Downstream is your core domain, upstream anything else | Anticorruption Layer (or CF to a clean PL) | Translate semantics, not just names | Core model is the asset |
| Many consumers of one context | Open Host Service + Published Language | OpenAPI / AsyncAPI / Protobuf, versioning | One protocol beats N translators |
| Cross-company or industry exchange | Published Language (standard) | Use iCalendar, vCard, OIDC, ISO 20022 | Nobody owns it; everybody understands it |
| Integration value is small | Separate Ways | Write it on the map | Integration is always expensive |
| A legacy system with no inner structure | Big Ball of Mud + ACL | Strangler fig | Do not model the mess |
| Generic subdomain bought as a product | Conformist to its OHS/PL | ACL only where it meets core rules | You will not change the product |
In architecture: from a single process to a distributed system
Context maps do not depend on deployment. The same patterns appear in one process and across a hundred services; what changes is the cost of each edge.
Monolith: one process, one database
In a plain monolith the contexts are often implicit, which is exactly why the map helps: it shows that "the order module" is used by four features with four meanings. The simplest correct move is to name the contexts, create one package or namespace per context, and put translation where two models meet. Example: the shop's monolith has Order used by checkout and by the warehouse screens; the map shows two contexts (Sales, Fulfilment) and a missing translation, so the team splits Order into sales.Order and fulfilment.PickList, with a mapping function between them.
Modular monolith: in-process OHS, still translating
In a modular monolith each module's public interface is its Open Host Service, and the DTOs on that interface are its Published Language. Translation is still needed: a module that imports another's internal entities is a conformist at best and a shared kernel nobody agreed to at worst.
// Inside one binary: the Sales module's public API is its OHS.
package salesapi // the only Sales package other modules may import
type OrderSummary struct { // published language, in-process
OrderID string
TotalMinor int64
Currency string
}
type API interface {
OrderSummary(ctx context.Context, id string) (OrderSummary, error)
}Enforce the map with architecture tests (Go import rules, Pest arch()), give each module its own schema and database role, and use in-process events (Laravel events, a Go event bus) for the edges that will become async later. Example: Billing listens to OrderPlaced in-process today; because it already consumes the published shape, extracting Billing later changes the transport, not the model.
Microservices: every edge has a network and a contract
Across services the pattern names become concrete artefacts: OHS + PL means an OpenAPI or AsyncAPI document in the repo; Customer-Supplier means consumer contract tests in the supplier's pipeline; ACL means a package or a service with its own monitoring; Shared Kernel means a versioned library with release coupling (keep it tiny). Example flow:
Sales service broker Fulfilment / Billing
1 tx: insert order + outbox row
2 relay -> publish sales.order.placed.v1 --> Fulfilment consumes (C/S, uses delivery_window)
3 --> Billing consumes (CF), insertOrIgnore by event_id
4 Sales CI: contract_test reads consumers/*.expects.json before every release
5 ERP ACL in Sales: sync HTTP with 2 s timeout; 5xx -> retry; still down -> order waitsSee Service Communication for timeouts and retries and Saga when an edge carries a multi-step process.
Distributed data: replicas, caches and multi-region
An edge that ships data creates copies. A conformist consumer that stores upstream data has a replica of the upstream model, with lag; an ACL that caches translated records has a translated replica that can be stale in two ways (upstream changed, or translation rules changed). Put the freshness on the map ("Billing: copy of orders, lag under 5 s"), version translation rules so you can re-translate, and prefer events over polling for cross-region edges. In multi-region setups an OHS is often replicated per region while the published language stays global; the schema registry (or the schema files in the repository) is the single source of truth.
Scaling path: 1×, 10×, 100×
| Scale | Map | Typical change |
|---|---|---|
| 1× (one team) | A drawing on a whiteboard; contexts as packages | Name contexts; add one ACL for the legacy system |
| 10× (5 to 10 teams) | CML file in the repo, reviewed per integration | Customer-supplier contract tests; first OHS with a PL; shared kernel with a policy |
| 100× (dozens of teams) | Several maps per question; team map separate from system map | OHS everywhere for widely used contexts; schema registry; platform-provided ACL templates; deprecation SLAs |
Lab: draw, implement and break the map
Everything runs offline with Go installed.
Setup.
cd docs/snippets/ddd/context-maps-integration-patterns/go
go vet ./...
go test ./...
# ok academy/context-maps-integration-patterns/billing
# ok academy/context-maps-integration-patterns/contracts/orderplaced
# ok academy/context-maps-integration-patterns/kernel
# ok academy/context-maps-integration-patterns/sales/acl/erpStep 1: draw today's map. For a system you know, list the contexts and draw each edge with U/D and a pattern tag. Expected: at least one edge you cannot classify. That edge is a decision nobody made.
Step 2: break the customer-supplier contract. In go/contracts/orderplaced/v1.go change the tag json:"quantity" to json:"qty" and run go test ./contracts/.... Expected:
--- FAIL: TestPublishedLanguageSchema
publisher violates the published language: [$.lines[].quantity: required ...]
--- FAIL: TestConsumerExpectations
billing needs "lines[].quantity", publisher does not provide it
fulfilment needs "lines[].quantity", publisher does not provide itNote that go test ./billing/... still passes: the conformist test reads the example file, not the publisher. That is why the supplier-side contract test matters. Revert.
Step 3: leak an internal field. In contracts/orderplaced/v1.go add the field MarginMinor int64 `json:"margin_minor"` to V1, and set it from o.MarginMinor in ToV1 (sales/ohs/publisher.go). Expected: TestGoBindingMatchesSchema fails with Go field MarginMinor ("margin_minor") not in schema, and TestNoInternalFieldsLeak fails with internal field "margin_minor" leaked. Revert.
Step 4: add a legacy quirk to the ACL. The ERP starts sending KLIMK as "1500" with no decimals for some customers. Add a case to translator_test.go expecting 150000, run it, fix parseAmount if needed. Expected: only the translator changes; Sales code is untouched.
Step 5: change the shared kernel. Change the rounding in kernel.PercentOf to round half to even. Expected: TestRoundingRuleIsShared fails on {1050, 500, 53}. Discuss: this is a MAJOR version under the policy; both teams must approve.
Step 6: write the map as CML. Open contracts/contextmap.cml in the Context Mapper online IDE or VS Code extension, add Fulfilment [C,ACL]<-[S,OHS] Sales, and read the validator's message. Expected, per the Language Semantics page: an error for OHS on a customer-supplier edge (rule #6) and a warning for ACL there (rule #7, which the page calls a soft rule).
Common misconceptions
| Belief | Reality |
|---|---|
| A context map is the target architecture | It is today's reality; the target is a separate TO_BE map |
| Upstream means "sends the data" | Upstream means "its changes affect the other side" |
| Conformist is always bad | Conforming to a good PL or standard is often best |
| An ACL is just a mapper class | Facade + adapter + translator; it also translates errors, IDs and semantics |
| A shared kernel is the common library | It is tiny, explicit, co-owned and versioned; a big common library is implementation coupling |
| Customer-Supplier gives the customer a veto | It gives a voice in planning and tests in CI; Evans warns against veto power |
| OHS means REST | It means one open integration protocol; events count |
| Our entities can be the published language | Internal models "essentially becomes frozen" when used for interchange |
| Events remove all coupling | They remove temporal coupling; the schema is still a contract |
| Separate Ways is laziness | It is a deliberate decision that integration costs more than it brings |
| You must model a legacy system before integrating | Draw a boundary around the mess (Big Ball of Mud) and put an ACL in front |
| Each pair of contexts has one relationship | One pair can have several edges (e.g. OHS/PL events and a shared kernel) |
Cheat sheet
| Topic | Remember |
|---|---|
| Context map | Today's contexts, edges, direction, pattern, mechanism; small maps per question |
| Upstream/downstream | Influence flow; "if they change, do we break?" |
| Partnership | Mutually dependent teams; joint planning; time-box it |
| Shared Kernel | Tiny, co-owned, versioned, tested in both CIs |
| Customer-Supplier | Downstream priorities in upstream planning; consumer tests in upstream CI; no veto |
| Conformist | Adopt upstream model; fine for good models and non-core contexts; confine the types |
| Anticorruption Layer | Facade + adapter + translator owned by downstream; no business rules inside |
| Open Host Service | One protocol for all; special cases in one-off translators |
| Published Language | Documented exchange format (OpenAPI, AsyncAPI, JSON Schema, Protobuf, standards) |
| Separate Ways | No integration; write it on the map |
| Big Ball of Mud | Mark it, wall it, strangle it |
| Notation | U/D, S/C; OHS, PL upstream; CF, ACL downstream; SK, P symmetric |
| Shared database | Red edge; publish a view, then events |
| Modular monolith | Module API = OHS; DTOs = PL; translation still needed |
| Evolution | CF to ACL, ACL to CF on a clean PL, C/S to OHS, SK to separate ways |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does a context map show that an architecture diagram does not? Must-know
Answer
Answer: Models and influence: which bounded contexts exist (including implicit models in legacy systems), who is upstream on each edge, which pattern governs the edge, and where translation happens. See The context map.
2 — Billing calls a Fulfilment API to fetch delivery dates. Who is upstream? Must-know
Answer
Answer: Fulfilment: a change to its API breaks Billing, not the other way round. Upstream is about influence, not about who initiates the call. See Upstream, downstream and power.
3 — Why does Evans warn against giving the customer veto power in Customer-Supplier? Good to know
Answer
Answer: "the freewheeling development of the upstream team will stop if the downstream team has veto power over changes." The customer gets planning influence and automated acceptance tests in upstream CI instead. See Customer-Supplier.
4 — Name three things that may go into a shared kernel and three that should not. Important
Answer
Answer: May: Money/Currency, a rounding rule both must apply, identifier formats. Should not: entities like Order or Customer, persistence models, utility grab-bags. See Shared Kernel.
5 — When is Conformist the right choice? Must-know
Answer
Answer: When the upstream will not adapt to you, its model is good (or a standard), your context is not core, and you use the data as it is. Confine the upstream types to one package so an ACL can be inserted later. See Conformist.
6 — What are the three parts of an ACL, and what does each do? Important
Answer
Answer: Facade: implements the downstream-owned port. Adapter: speaks the upstream protocol (URLs, timeouts, status codes). Translator: maps records, identifiers, semantics and errors into the downstream model. See Anticorruption Layer.
7 — Why should an internal domain model not be used as the published language? Important
Answer
Answer: Evans: internal models may be complex, poorly factored, undocumented, and "If one is used as a data interchange language, it essentially becomes frozen and cannot respond to new development needs." See Published Language.
8 — An OHS consumer needs XML instead of JSON. What does Evans advise? Good to know
Answer
Answer: Keep the shared protocol simple: "use a one-off translator to augment the protocol for that special case". See Open Host Service.
9 — Which combinations does Context Mapper reject, and why? Good to know
Answer
Answer: ACL and CF together (protect or conform, not both), OHS/PL/ACL/CF on symmetric relationships (SK, P), CF on a customer-supplier edge (a customer has influence), OHS on customer-supplier (one-for-all vs tailored). ACL on C/S is only a warning. See Notation.
10 — How do you show and then remove a shared-database edge? Important
Answer
Answer: Draw it red on the map; detect it with grants and pg_stat_activity; replace table access with a published view as an interim PL; move readers to events. See Finding hidden edges.
11 — In a modular monolith, what plays the role of OHS and PL? Important
Answer
Answer: The module's public interface is the OHS, and the DTOs on it are the PL. Other modules still translate into their own models. See Modular monolith.
12 — What is the usual next step for a Conformist edge that starts to hurt? Important
Answer
Answer: Insert an ACL at the seam where the upstream types were confined; if the upstream is willing, ask for Customer-Supplier status with contract tests. See Evolving the map.
Glossary
| Term | Meaning |
|---|---|
| Context map | A description of bounded contexts and the relationships between them, as they are today |
| Bounded context | Boundary within which one model and one language apply (Bounded Context) |
| Upstream | The side whose actions affect the other's success |
| Downstream | The side affected by the other's actions |
| Mutually dependent | Two contexts that must both be delivered for either to succeed |
| Free | A context whose success does not depend on other contexts' work |
| Partnership (P) | Mutually dependent teams with coordinated planning and joint integration |
| Shared Kernel (SK) | A small, explicitly bounded, co-owned subset of model and code |
| Customer-Supplier (C/S) | Upstream/downstream where downstream priorities factor into upstream planning |
| Conformist (CF) | Downstream adopts the upstream model without translation |
| Anticorruption Layer (ACL) | Downstream-owned layer that translates the upstream model into its own |
| Facade | ACL part that offers the downstream port |
| Adapter | ACL part that speaks the upstream protocol |
| Translator | ACL part that maps data, identifiers, semantics and errors |
| Open Host Service (OHS) | One open protocol giving access to a context for all integrators |
| Published Language (PL) | A well-documented shared exchange language, often paired with OHS |
| Separate Ways | Deliberate decision not to integrate two contexts |
| Big Ball of Mud (BBoM) | A system with mixed models and no consistent boundaries; walled off on the map |
| U/D, S/C | Upstream/downstream and supplier/customer marks on map lines |
| Context Mapper / CML | A DSL and tool for context maps as text files with semantic validation |
| AS_IS / TO_BE | Context Mapper states for the current and the desired map |
downstreamRights | CML attribute: INFLUENCER, OPINION_LEADER, VETO_RIGHT, DECISION_MAKER, MONOPOLIST |
| OpenAPI | Language-agnostic interface description for HTTP APIs |
| AsyncAPI | Machine-readable, protocol-agnostic description of message-driven APIs |
| JSON Schema | Vocabulary to describe and validate JSON documents |
| Protocol Buffers | Binary schema language; deleted field numbers go into reserved |
| Consumer-driven contract | Downstream-written expectations run in upstream CI (e.g. Pact) |
| Pact | A code-first contract testing tool for HTTP and message integrations |
| Strangler fig | Gradual replacement of a legacy system around a seam such as an ACL |
| Outbox | Writing an event in the same transaction as state, published later by a relay |
| Shared database (smell) | Two contexts reading or writing the same tables: an undrawn, unversioned edge |
| Team relationships | DDD-crew's three: mutually dependent, upstream/downstream, free |
| iCalendar, vCard | Industry published languages cited by DDD-crew |
| OpenID Connect (OIDC) | Identity protocol used as a generic OHS/PL by identity providers |
References
- Eric Evans, Domain-Driven Design Reference, 2015: "Context Mapping for Strategic Design" (bounded context, upstream-downstream, mutually dependent, free, Context Map, Partnership, Shared Kernel, Customer/Supplier Development, Conformist, Anticorruption Layer, Open-host Service, Published Language, Separate Ways, Big Ball of Mud)
- DDD-crew, context-mapping repository README (team relationships, nine patterns, best practices, cheat sheet), CC BY 4.0
- Context Mapper, Context Map (CML reference), Customer/Supplier, Language Semantics, CML Reference introduction
- Martin Fowler, "Bounded Context", 15 January 2014; "Strangler Fig", 22 August 2024
- Microsoft Azure Architecture Center, "Anti-Corruption Layer pattern"
- Chris Richardson, microservices.io, "Pattern: Anti-corruption layer"
- Vaughn Vernon, Implementing Domain-Driven Design (Addison-Wesley, 2013), chapter 3 "Context Maps"; preface and guide read in the publisher's sample pages
- Vlad Khononov, Learning Domain-Driven Design (O'Reilly, 2021), chapter 4 "Integrating Bounded Contexts" (not read; grouping from search results of the table of contents)
- Brian Foote and Joseph Yoder, "Big Ball of Mud", 1999 version
- Sam Newman, Building Microservices (O'Reilly, 2015), chapter "Splitting the Monolith", free excerpt published by Thoughtworks (bounded contexts as seams); Monolith to Microservices (2019), table of contents on the author's site
- AsyncAPI Specification 3.0.0; OpenAPI Specification 3.1.0; Protocol Buffers, Language Guide (proto3)
- Pact documentation, Introduction
- Laravel 13, HTTP Client, Queues