Service Boundaries: Teams, Conway's Law, the Distributed Monolith and the Hidden Tax
"Any organization that designs a system (defined more broadly here than just information systems) will inevitably produce a design whose structure is a copy of the organization's communication structure." — Melvin E. Conway, author's note on How Do Committees Invent? (Datamation, April 1968)
Summary: A service boundary is a line around data, behaviour, a team and a deployment unit at the same time; draw it where change and communication are naturally low, or every feature pays a hidden tax in coordination, latency and outages. Focus: What a boundary is, Conway's law and the inverse Conway manoeuvre, Team Topologies and cognitive load, six decomposition strategies, boundary heuristics, Newman's coupling types, the distributed monolith, the hidden tax of microservices, granularity integrators and disintegrators, context mapping between services, boundary evolution (merge, split, strangler fig, tactical forking), and how to measure boundary health from deploys, call graphs and git history. Learning goal: Given a system and an org chart, propose service boundaries, name the coupling each one leaves behind and its cost, detect a distributed monolith with numbers rather than opinions, and enforce the boundaries you chose with architecture tests, contract tests and a change-coupling report in Go and Laravel.
This chapter belongs to group AR 03 (Microservices in Practice). It assumes you know why one would choose services at all (Monolith vs Microservices vs Modular Monolith, Microservices Architecture) and what a module boundary inside one deployable looks like (Modular Monolith). It owns the question where do the lines go and what does each line cost? The neighbours own the rest: how services talk (Service Communication), who owns which tables (Data Ownership in Microservices), the edge (API Gateway, BFF & Service Mesh), and the DDD modelling behind a context (Bounded Context, Context Maps).
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why the line matters more than the technology | Why boundaries exist |
| Conway 1968 to Team Topologies and Hard Parts | Where it comes from |
| Data + behaviour + team + deployment | What a boundary is |
| Conway's law, inverse Conway manoeuvre | Conway's law, Inverse Conway |
| Stream-aligned, platform, enabling, complicated-subsystem | Team Topologies |
| By capability, subdomain, volatility, data, scale, compliance | Decomposition strategies |
| Information hiding, change together, transactions, chatty test | Boundary heuristics |
| Domain, temporal, deployment, implementation coupling | Coupling types |
| Lockstep deploys, shared DB, call chains, shared libraries | The distributed monolith |
| Latency, consistency, debugging, testing, on-call | The hidden tax |
| How big, nanoservices | Granularity |
| Partnership, shared kernel, ACL, OHS, conformist | Context mapping between services |
| Merge, split, strangler fig, tactical forking | Boundary evolution |
| Deploy coupling, call graphs, change coupling from git | Measuring boundary health |
| Orders and Billing done right and wrong, with tests | Go, Laravel |
| Shared DB, sync chains, entity services, lockstep | Solving the classic problems |
| Which strategy for which situation | Choosing |
| Monolith to distributed data | In architecture |
| Hands-on | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Service boundary | The line around one service's data, code, team and release | Billing owns invoices, its code, its pager, its pipeline | Two teams edit the same table and blame each other |
| Conway's law | Systems copy the communication structure of the people who build them | Three layer teams produce three layers | Architecture fights the org chart and loses |
| Inverse Conway manoeuvre | Change the teams first to get the architecture you want | Form an Orders team before splitting orders out | You draw services nobody can own |
| Cognitive load | How much one team must keep in its head | One team owns 14 services and 3 databases | Slow changes, outages nobody understands |
| Bounded context | The area where one model and one vocabulary hold | "Customer" in Billing is an account, in Support a person | One giant model with contradictory meanings |
| Coupling | How much a change in one place forces a change elsewhere | Renaming a column breaks another service | Every release needs a meeting |
| Distributed monolith | Services that must still change, deploy and fail together | Five services, one release train, one database | You pay for microservices and get a monolith |
| Hidden tax | The costs that arrive with the network, not with features | Retries, tracing, contract tests, on-call | Velocity drops after the split |
Coupling and its tax (Newman's four types; details in Coupling types):
| Coupling | Plain words | Typical source | Tax you pay | Remedy |
|---|---|---|---|---|
| Domain | A needs something B does | Billing needs to know an order was placed | Small, if the contract is small | Narrow published language |
| Temporal | A works only while B is up | Synchronous call chain | Availability multiplies, latency adds | Events, local copies, timeouts |
| Deployment | A and B must ship together | Release train, lockstep versions | Every team waits for the slowest | Backward-compatible contracts |
| Implementation | A depends on B's internals | Shared tables, shared domain library | B can no longer change alone | Hide internals; API or event only |
Decomposition strategies (compared in Decomposition strategies):
| Strategy | Split along | Good first choice when | Watch out for |
|---|---|---|---|
| Business capability | What the business does (Orders, Billing) | Org already has capability owners | Capabilities that share one invariant |
| Subdomain / bounded context | Where the language and model change | Domain is rich, experts disagree on words | Over-fine contexts, too many services |
| Volatility | What changes often vs rarely | One part churns weekly, rest is stable | Volatility that is temporary |
| Data ownership | Who is the single writer of each record | Many writers to the same tables today | Reporting needs that join everything |
| Scaling needs | Very different load profiles | Search takes 95% of traffic | Splitting for scale you do not have |
| Compliance / security | Regulated data and blast radius | Card data (PCI DSS), health data | Spreading the regulated data anyway |
Distributed monolith: symptom → test → remedy.
| Symptom | Quick test | Remedy |
|---|---|---|
| Lockstep deploys | Share of releases that needed another service released too | Expand/contract contracts, versioned events |
| Shared database | More than one service role can write a table | Database per service, or schema + role per service |
| Synchronous call chains | Depth of the call graph for one user request | Events, data replication, merge chatty pairs |
| Shared library with domain logic | Same domain class imported by 2+ services | Copy, publish a contract, or merge |
| Change coupling | Two services in the same commits > 30% of the time | Move the boundary or merge |
Why boundaries exist
Every system above a certain size is split somewhere, because no single person can hold it in their head and no single team can change it fast enough. The question is never whether there are boundaries, only where they are and what crosses them. A good boundary keeps most changes on one side; a bad one turns every feature into a cross-team project. In a monolith a bad module boundary costs you some refactoring. Across a network it costs you latency, partial failure, a contract to version and a pager rota, on every request, forever. That is why Fowler's Microservices article says the hard part is not services but "It's hard to figure out exactly where the component boundaries should lie."
| Draw boundaries along team and change lines | Draw boundaries along technical lines (layers, entities) |
|---|---|
| Most features touch one service | Most features touch every service |
| Teams deploy alone | Release trains, change advisory boards |
| Failures stay local | One slow service takes down the rest |
| Some data is duplicated on purpose | Data lives in one place and everyone reads it |
| Harder up front: you must understand the business | Easy up front: the database diagram is the plan |
| Good for: long-lived products with several teams | Good for: nothing at service level; fine as layers inside a service |
The analogy we reuse on this page: a restaurant kitchen. A kitchen has stations: grill, cold starters, pastry. Each station owns its ingredients, its tools, its cook, and it hands finished plates to the pass. If the pastry chef must walk to the grill to borrow a pan for every dessert (a shared library), if every station reads the same order slip and crosses items out on it (a shared database), or if the grill cannot plate a steak until pastry confirms the dessert (a synchronous chain), you have one kitchen pretending to be three. The stations are boundaries; the pass and the order ticket are the contract; the head chef's seating plan of cooks is Conway's law.
The picture shows the law in both directions: teams split by layer produce a layered system in which every feature crosses three teams; stream-aligned teams with a platform produce services that mirror them.
Three common misunderstandings, up front
- "Boundaries are a technical decision." They are a social and economic one first. Conway's paper concludes that "a design effort should be organized according to the need for communication"; the line you draw decides who must talk to whom.
- "Smaller services are more decoupled." Size and coupling are different axes. Ten tiny services that all change together are more coupled than one well-bounded service. Hard Parts warns that "One common mistake many development teams make is focusing too much on granularity disintegrators while ignoring granularity integrators."
- "If we have separate repositories and containers, we have microservices." Separate processes with a shared database, a shared domain library and one release train are a distributed monolith: the costs of distribution without its benefits.
Where it comes from
Conway, 1968. Melvin Conway's How Do Committees Invent? appeared in Datamation in April 1968. Its argument is graph-theoretic: the structure of the design organisation and the structure of the system are related by a homomorphism, "so simple that in some cases it is an identity". He also explains why large organisations get worse, not better: "the number of possible communication paths in an organization is approximately half the square of the number of people", so communication must be restricted, and the system inherits the restrictions.
Brooks, 1975. Fred Brooks named it "Conway's law" in The Mythical Man-Month (we take this from Fowler's bliki footnote, not from the book itself).
Parnas, 1972. On the Criteria To Be Used in Decomposing Systems into Modules gave the rule this chapter reuses for services: split by design decisions likely to change and hide each one behind an interface (see Design Quality).
Evans, 2003. Domain-Driven Design introduced the bounded context and the context map. Evans's free DDD Reference (2015) defines a bounded context as "A description of a boundary (typically a subsystem, or the work of a particular team) within which a particular model is defined and applicable." Note "the work of a particular team": DDD tied model boundaries to teams from the start.
LeRoy and Simons, 2010. Fowler credits the term "inverse Conway maneuver" to Jonny LeRoy and Matt Simons in the December 2010 Cutter IT Journal (we read Fowler's footnote, not the article).
Lewis and Fowler, 2014. The Microservices article (March 2014) made boundaries the centre of the style: services "organized around business capabilities", with "Decentralized Data Management", and the rule that "If you find yourself repeatedly changing two services together, that's a sign that they should be merged."
Newman, 2015 and 2019. Building Microservices (1st ed., February 2015) used Feathers' idea of a seam to find service boundaries in a monolith: "bounded contexts make excellent seams". Monolith to Microservices (2019) has a chapter section "On Coupling And Cohesion" and the migration patterns (strangler fig, branch by abstraction, parallel run). The four coupling types we use come from that book's first chapter; we confirmed the chapter outline on Newman's own book page and the list of types from a reader's notes (secondary).
Monolith First, 2015. Fowler's MicroservicePremium (13 May 2015) and MonolithFirst (3 June 2015) argued that microservices "only work well if you come up with good, stable boundaries between the services", and that you learn those boundaries best inside a monolith.
Team Topologies, 2019. Matthew Skelton and Manuel Pais described four team types and three interaction modes, with cognitive load as the limit on how much a team (and so a service set) can own. Fowler's summary (25 July 2023) calls the focus on cognitive load "the bright insight of Team Topologies".
Hard Parts, 2021. Ford, Richards, Sadalage and Dehghani's Software Architecture: The Hard Parts (first edition October 2021) gave granularity disintegrators and integrators and two decomposition approaches for existing systems: component-based decomposition and tactical forking.
Year Idea What it changed for boundaries
1 1968 Conway: system copies communication Org design is architecture design
2 1972 Parnas: hide decisions likely to change Boundaries follow change, not steps
3 2003 Evans: bounded context, context map One model per boundary; relations named
4 2010 Inverse Conway manoeuvre Change teams to get the architecture
5 2014 Microservices: business capabilities Boundary = team = deployable = data
6 2015 Newman: seams; Fowler: Monolith First Find boundaries before distributing them
7 2019 Team Topologies: cognitive load Team capacity limits service ownership
8 2021 Hard Parts: integrators/disintegrators Granularity as a measured trade-offThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a request or change timeline, real scenarios, a comparison table, and the fix.
What a boundary is Must-know
In plain words: a service boundary is a promise that one team owns a piece of data and the behaviour around it, changes it on its own schedule, and lets others in only through a published door.
Common misunderstanding: "A boundary is a separate repository or container." Those are packaging. A boundary has four faces, and if any one is shared, the boundary leaks.
Definition: a service boundary aligns four things: data (one service is the system of record and the only writer), behaviour (the rules that keep that data valid live with it), team (one team can change both without asking), and deployment (it can be released alone). Lewis and Fowler define a component as "a unit of software that is independently replaceable and upgradeable"; the four faces are what make that true for a service.
Change request: "invoices get a due date per customer segment"
1 Billing team edits billing.invoices + rule code data + behaviour inside one boundary
2 Billing contract unchanged (new optional field only) no other team involved
3 Billing deploys at 14:05 deployment alone
4 Orders, Shipping keep running v1 consumers nobody else redeploys
Leaky version: Orders also writes billing.invoices -> step 2 needs the Orders team, step 3 waits for theirsReal scenario: a shop where Orders inserts rows into billing_invoices "because it is faster"; Billing cannot add a NOT NULL column without breaking Orders. A bank where the ledger service is the only writer of balances, and everything else asks or listens. An insurer where one team owns three services that always deploy together: that is one boundary in three containers.
The four faces, and what breaks each:
| Face | Healthy | Leak | Detect with |
|---|---|---|---|
| Data | One writer per table; others read via API/events | Second service writes or joins the table | DB roles and grants; query logs |
| Behaviour | Rules live with the data they protect | Same rule copied in two services, or in a shared library | Code search for the rule; change coupling |
| Team | One team, clear on-call | "Shared ownership", two teams approve PRs | CODEOWNERS, pager rota |
| Deployment | Independent pipeline and version | Release train, lockstep versions | Deploy logs: how often releases go together |
Fix / how to use it: write the four faces down per service (an ownership table in the repo), then enforce data with database roles, behaviour and dependencies with architecture tests, team with CODEOWNERS, and deployment with contract tests that let each pipeline run alone.
Conway's law Must-know
In plain words: the system ends up shaped like the conversations of the people who build it.
Common misunderstanding: "Conway's law is about org charts." It is about communication. Fowler's summary quotes Chris Ford: "Conway understood that software coupling is enabled and encouraged by human communication." Two teams on the same org-chart branch who never talk will still produce a hard seam; two teams in different departments who pair daily will produce coupled code.
Definition: Conway (1968): "organizations which design systems (in the broad sense used here) are constrained to produce designs which are copies of the communication structures of these organizations." Fowler (2022) on its weight: "if there is one thing they all agree on, it's the importance and power of Conway's Law."
Org: front-end team, back-end team, DBA team (activity-oriented)
1 Feature "gift wrapping" needs a UI field, an API field, a column
2 Front-end files a ticket for back-end; back-end files one for DBA
3 DBA adds the column in the next schema window (two weeks)
4 Back-end, tired of waiting, stores the flag in an existing JSON column
Result: logic lands "in whichever application they have access to" (Lewis and Fowler) -> layers, not featuresReal scenario: Fowler's compiler example: "if a single team writes a compiler, it will be a one-pass compiler, but if the team is divided into two, then it will be a two-pass compiler." An architect of six teams in six cities: "There are going to be six major subsystems. I have no idea what they are going to be, but there are going to be six of them." A remote-first company where time zones, not offices, now draw the seams (Fowler notes time zones "still have a big effect, even online").
How organisations respond (Fowler's three responses):
| Response | What it means | Outcome |
|---|---|---|
| Ignore | Draw the architecture without looking at teams | The org wins; boundaries erode to match teams |
| Accept | Draw boundaries where communication is already thin | Stable, maybe not ideal |
| Inverse Conway manoeuvre | Change teams to get the desired boundaries | Works when code and org change together |
Fix / how to use it: before drawing a boundary, draw the communication graph: who talks to whom daily, who only through tickets. Put service boundaries on the thin edges. Small groups ("A dozen or two people can have deep and informal communications") will naturally build a monolith, and that is fine.
The inverse Conway manoeuvre Important
In plain words: if the system copies the teams, design the teams you want the system to copy.
Common misunderstanding: "Reorganise and the architecture follows." Fowler: "If you have an existing system with a rigid architecture that you want to change, changing the development organization isn't going to be an instant fix. Instead it's more likely to result in a mismatch between developers and code that adds friction."
Definition: "we deliberately alter the development team's organization structure to encourage the desired software architecture" (Fowler, Conway's Law). The rule he closes with: "the modular decomposition of a system and the decomposition of the development organization must be done together."
Goal: Billing as an independent service
1 Q1 Form a stream-aligned Billing team; it owns the billing module in the monolith
2 Q1 Team adds module boundary + arch test; only it approves billing/ changes (CODEOWNERS)
3 Q2 Billing schema + role; Orders reads via the module API
4 Q3 Billing extracted as a service behind the same API; events replace in-process calls
Without step 1: an extracted service with no owner, patched by whoever is nearestReal scenario: a retailer that forms "checkout" and "catalog" teams before splitting the monolith; a SaaS company merging two half-teams that kept stepping on each other into one team owning both services, then merging the services; a platform team created so stream-aligned teams stop each building their own deployment scripts.
| Move | Org change | Code change that must accompany it |
|---|---|---|
| Create a team for a capability | New stream-aligned team | Module or service boundary, ownership file |
| Merge two teams | One team | Consider merging their services (evolution) |
| Create a platform team | X-as-a-Service provider | Self-service pipeline, templates, broker |
| Split a team that is too big | Two teams | Find the seam first; split code along it |
Fix / how to use it: sequence it: team first, module boundary second, data third, network last. Each step is reversible; the network step is the expensive one.
Team Topologies and cognitive load Must-know
In plain words: a team can only own as much software as it can understand; size your service boundaries to fit the team, not the other way round.
Common misunderstanding: "More services per team is efficiency." Team Topologies' key-concepts page: "Teams can only handle so much complexity before breaking down. Each new tool, responsibility or domain your team is given taxes their mental bandwidth."
Definition: Skelton and Pais's four team types and three interaction modes, as listed on teamtopologies.com:
| Team type | Definition (teamtopologies.com) | Service-boundary consequence |
|---|---|---|
| Stream-aligned | "aligned to a flow of work from (usually) a segment of the business domain" | Owns business services end to end; "You Built It, You Run It" |
| Platform | "a grouping of other team types that provide a compelling internal product to accelerate delivery by Stream-aligned teams" | Owns CI/CD, broker, observability; consumed self-service |
| Enabling | "helps a Stream-aligned team to overcome obstacles. Also detects missing capabilities." | Owns no production service; coaches |
| Complicated-subsystem | "where significant mathematics/calculation/technical expertise is needed" | Owns a specialist component (pricing engine, video codec) |
| Interaction mode | Definition | Typical boundary |
|---|---|---|
| Collaboration | "working together for a defined period of time to discover new things" | Boundary still moving; temporary |
| X-as-a-Service | "one team provides and one team consumes something 'as a Service'" | Stable API, self-service |
| Facilitation | "one team helps and mentors another team" | No runtime boundary |
Team "Checkout" (6 people) owns: cart, orders, payments, invoices, emails, 4 DBs, Kafka setup
1 Incident at 02:00 in invoices; the on-call engineer has never touched it
2 Feature work stalls for a week of firefighting
3 Fix: invoices -> new Billing stream-aligned team; Kafka setup -> platform team (X-as-a-Service)
4 Checkout now owns cart + orders: two services it fully understandsReal scenario: a team of five owning 22 microservices (common after a "one service per entity" split): most are never touched and nobody can debug them. A machine-learning ranking model owned by a complicated-subsystem team, consumed by the search team as a service. A platform team whose broker cluster lets every stream-aligned team publish events without learning Kafka operations.
Fix / how to use it: for each proposed service, ask "which team owns it, and is that team's total load still sane?" Fowler: "the primary benefit of a platform is to reduce the cognitive load on stream-aligned teams". If the answer is "nobody" or "the team that already owns twelve", the boundary is wrong, not the team.
Bounded context as the boundary candidate Must-know
In plain words: where the meaning of a word changes, a boundary probably belongs.
Common misunderstanding: "One bounded context equals one microservice." A context is a model boundary; it can be one service, several services, or a module in a monolith. Lewis and Fowler: "there is a natural correlation between service and context boundaries", not an identity.
Definition: Evans (DDD Reference): "A description of a boundary (typically a subsystem, or the work of a particular team) within which a particular model is defined and applicable." Fowler: DDD recognises that "total unification of the domain model for a large system will not be feasible or cost-effective", and "Usually the dominant one is human culture, since models act as Ubiquitous Language, you need a different model when the language changes." Full modelling detail lives in Bounded Context.
Word "Customer" in one shop
1 Sales: prospect with a segment and a discount tier
2 Billing: an account with a credit limit and payment method
3 Shipping: a delivery address and a phone number
4 Support: a person with tickets and a satisfaction score
One Customer table with all fields = four teams editing one schema = implementation couplingReal scenario: Fowler's electricity utility where "meter" meant three different things; a marketplace where "Product" is a catalog listing for one team and a stock-keeping unit for another; a hospital where "Patient" in admissions and in billing have different identifiers and life cycles (polysemes).
| Signal | Suggests a context boundary | Suggests the same context |
|---|---|---|
| Same word, different attributes or rules | Yes | |
| Different experts you would interview | Yes | |
| Invariant spans both sides (must be atomic) | Yes | |
| Changes always arrive together | Yes |
Fix / how to use it: run an Event Storming session, mark where the language shifts, and treat those lines as boundary candidates; then test them with the heuristics before any network goes in.
Decomposition strategies Must-know
In plain words: there are six common reasons to put a line in a particular place; good boundaries usually satisfy several at once.
Common misunderstanding: "Split by entity: a User service, a Product service, an Order service." Entity (noun) services are the classic wrong split: every use case touches several of them. Dehghani warns against services "driven by the existing normalized view of the data", which "almost always leads to a cambrian explosion of large number of anemic services for CRUD resources."
Definition: the strategies, with their source:
| Strategy | Source | Rule (quoted or summarised) | Strength | Weakness |
|---|---|---|---|---|
| By business capability | microservices.io | "Define services corresponding to business capabilities", "something that a business does in order to generate value" | Stable: capabilities change slower than org charts | Capability maps can be political |
| By subdomain / bounded context | microservices.io, Evans | "Define services corresponding to Domain-Driven Design (DDD) subdomains"; core, supporting, generic | Follows language and model | Needs domain knowledge to do well |
| By volatility | Hard Parts (code volatility); Parnas | Separate what changes often from what is stable | Shrinks the blast radius of change | Volatility shifts over time |
| By data ownership | Newman (database seams); microservices.io database per service | One writer per record; split along data seams | Removes shared-database coupling | Cross-domain queries need new paths |
| By scaling needs | Hard Parts ("Scalability and throughput") | Parts with very different load get their own service | Cost-efficient scaling | Often premature |
| By compliance / security | Hard Parts ("Security"); Newman (security as split driver) | Isolate regulated or sensitive data | Smaller audit scope (e.g. PCI DSS) | Regulated data leaks into logs and events anyway |
Online shop, one candidate per strategy
1 Capability: Orders, Billing, Shipping, Catalog
2 Subdomain: Pricing (core), Catalog (supporting), Email (generic -> buy SaaS)
3 Volatility: Promotions rules change weekly -> separate from stable Orders
4 Data: Billing is the only writer of invoices and credit
5 Scale: Search serves 90% of reads -> own service + index
6 Compliance: Card tokens in a payment vault service, nothing else sees a PANReal scenario: a ride-hailing pricing engine split for volatility (rules change daily); a card vault split for PCI scope; a news site's search split for scale; a B2B product split by capability because each capability has a different buyer and roadmap.
Fix / how to use it: start with capability or subdomain to get candidates, then use the other four to move a line (volatility, data, compliance) or to justify an extra split (scale). A line supported by only one driver, and that driver is "scale we might need", is the first to drop.
Boundary heuristics Must-know
In plain words: six quick tests tell you whether a proposed line will hold.
Common misunderstanding: "Draw it once in a workshop and we are done." Fowler's Monolith First: "even experienced architects working in familiar domains have great difficulty getting boundaries right at the beginning." Heuristics are tests you re-run as the system changes.
Definition:
| Heuristic | Test question | Passes when | Fails when |
|---|---|---|---|
| Information hiding (Parnas, Newman) | Can the service change its internals without telling anyone? | Schema and code are private; only the contract is public | Others read its tables or classes |
| Change together, stay together (common closure) | Do most changes to X also change Y? | Fewer than ~1 in 10 changes cross the line | Lewis and Fowler: "repeatedly changing two services together" means merge |
| Transaction boundary | Is there an invariant that must be atomic across the line? | Invariants stay inside one service | Newman: if state "really, really wants to be kept consistent, do everything you can to avoid splitting it up" |
| Data gravity | Where does most of the data a use case needs already live? | The use case's data sits on one side | Every request gathers data from three services |
| Chatty interface test | How many calls cross the line per user request? | One or two coarse calls, or none (events) | Ten fine-grained calls; Lewis and Fowler: remote APIs "need to be coarser-grained" |
| One-team ownership | Can exactly one team own it? | One team, on-call included | "Shared by teams A and B" |
Candidate split: Orders | Inventory
1 Info hiding: Inventory exposes Reserve(sku, qty) only pass
2 Change: 12 of 80 order-related commits also touched inventory borderline (15%)
3 Transaction: "never sell what we do not have" spans both FAIL -> needs reservation + saga
4 Data gravity: checkout needs stock levels on every request FAIL -> cache/replica of stock
5 Chatty: 1 reserve call per order pass
6 Ownership: Fulfilment team owns inventory pass
Decision: split, but design the reservation saga and stock projection first, or keep them togetherReal scenario: a ticketing system where seat inventory and orders share an invariant (no double booking) and were kept together; a CMS where "articles" and "comments" failed the change test and were merged after a year; a payments split that passed all six because the PSP integration had its own language and team.
Fix / how to use it: run the six tests on paper for each candidate line; any FAIL needs a named mitigation (saga, projection, merge) before the split. Run the change test for real with the change-coupling tool on the monolith's history.
Coupling types across services Must-know
In plain words: coupling is not one thing; four different kinds tie services together, and they cost very different amounts.
Common misunderstanding: "Asynchronous messaging removes coupling." It removes temporal coupling. A consumer that depends on every field of a producer's internal entity is still implementation-coupled, just with a broker in the middle.
Definition: Newman, Monolith to Microservices chapter 1, distinguishes domain, temporal, implementation and deployment coupling (outline from Newman's book page; the list from a reader's notes, secondary). We define them as used on this page:
| Type | Definition | Example | Hidden tax | Becomes acceptable when |
|---|---|---|---|---|
| Domain | One service needs functionality or information another provides | Billing must know orders were placed | Changes to the shared concept ripple | The contract is small, explicit and versioned |
| Temporal | Both must be available at the same moment for work to finish | Orders calls Pricing synchronously | Availability multiplies; latency adds; retries amplify | The callee is extremely reliable or the call is optional |
| Deployment | Services must be released together | Orders v5 needs Billing v7 the same day | Release coordination; rollback of two services | Never across teams; fine inside one team's two processes |
| Implementation | One service depends on how another is built | Shared tables, shared ORM models, shared domain library | Provider cannot refactor; schema becomes public API | Never across a service boundary |
Same feature, four couplings, four bills
1 Domain: Billing reads OrderPlaced{order_id,total} bill: one contract to version
2 Temporal: Orders -> Pricing -> Tax, 3 x 99.9% up bill: 99.7% at best, latencies add
3 Deployment: Orders and Billing share a JAR with Invoice class bill: every Invoice change = joint release
4 Implementation: Orders SELECTs billing_invoices directly bill: Billing cannot rename a columnReal scenario: a team migrating to Kafka that published its JPA entities as events: no temporal coupling, total implementation coupling (every column rename broke consumers). A "common" library with Money, Customer and OrderStatus used by 30 services: deployment coupling through version upgrades. Microservices.io's shared-database page lists exactly these costs: "Development time coupling" and "Runtime coupling".
Fix / how to use it: aim for "domain coupling only, kept small": publish a published language (event or API contract) that is not your internal model; make reads local (events, projections) to drop temporal coupling; keep contracts backward compatible to drop deployment coupling; never share tables or domain classes to drop implementation coupling.
The distributed monolith Must-know
In plain words: a system that is deployed as many services but still has to be changed, released and debugged as one.
Common misunderstanding: "A distributed monolith is a monolith that runs on several machines." A horizontally scaled monolith (many copies of one deployable) is fine. The problem is many different deployables that are coupled as tightly as modules in one, so you pay network and operational costs without independent change.
Definition: a set of services with high deployment and implementation coupling between them, recognisable by lockstep deploys, a shared database, synchronous call chains and shared libraries containing domain logic. Newman's Monolith to Microservices lists the distributed monolith among "other monoliths" (reader's notes, secondary), and Lewis and Fowler warn that if components do not compose cleanly, "all you are doing is shifting complexity from inside a component to the connections between components."
Tuesday release of "add sales_region to orders"
1 09:00 Orders adds column orders.sales_region
2 09:10 Reporting service SELECTs orders.* and breaks (shared DB)
3 09:30 Billing's copy of shared-domain-lib Order class needs the field: lib v4.2 -> v4.3
4 11:00 Orders, Billing, Reporting rebuilt with lib 4.3; release train scheduled for 16:00
5 16:20 Pricing slow -> Orders slow -> checkout times out (sync chain)
6 16:40 Rollback must roll back three services togetherReal scenario: a company with 40 "microservices" and one weekly release window; a startup whose services all import core-models; a bank whose services each call the customer service on every request, so a customer-service outage is a total outage.
Symptoms, how to detect them, and remedies:
| Symptom | Detection | Threshold to worry | Remedy |
|---|---|---|---|
| Lockstep deploys | Deploy log: releases containing more than one service, or "deploy B before A" runbooks | More than ~20% of releases coordinated | Expand/contract API changes; versioned events |
| Shared database | information_schema.role_table_grants; DB query logs per role | Any table written by two service roles | Schema + role per service; then database per service |
| Synchronous call chains | Distributed traces: depth and fan-out per request | Depth over 3 on the critical path | Events, local projections, merge chatty pair |
| Shared libraries with domain logic | Dependency graph: domain packages imported by 2+ services | Any domain rule in a shared lib | Copy the code, publish a contract, or merge |
| Change coupling | git co-change degree between services | Over 30% for a pair with 5+ shared commits | Move the line or merge |
| Shared on-call | Incidents that need two teams to resolve | Most incidents | Re-draw boundaries to one owner each |
Fix / how to use it: measure first (Measuring boundary health), then attack the most expensive coupling: implementation (shared tables and libraries) before deployment before temporal. Sometimes the right fix is to merge services back into one deployable with modules: a modular monolith is a legitimate destination.
The hidden tax of microservices Important
In plain words: every service boundary charges rent on every request and every change, whether you notice or not.
Common misunderstanding: "The cost of microservices is the Kubernetes cluster." Infrastructure is the visible line item. Fowler's Microservice Premium: microservices "introduce complexity on their own account. This adds a premium to a project's cost and risk".
Definition: the hidden tax is the sum of costs that come from the boundary itself rather than from features:
| Tax | Where it comes from | Rough size | Who pays |
|---|---|---|---|
| Latency | In-process call (nanoseconds) becomes a network hop (sub-millisecond to milliseconds) plus serialisation | Fowler: remote calls "are orders of magnitude slower" | Users, on every request |
| Availability | Chained dependencies multiply | 3 services at 99.9% in a chain: 0.999^3 = 99.7% | Users; the SLO (SLAs and error budgets) |
| Consistency | No ACID transaction across services | Sagas, compensations, outbox, idempotency (Saga, Outbox) | Developers, every cross-service invariant |
| Debugging | A request spans processes and logs | Tracing, correlation IDs, log aggregation | On-call engineers |
| Testing | Integration happens over a network | Contract tests, test environments, fakes | Every team, every pipeline |
| Infrastructure | Pipelines, images, secrets, dashboards per service | Linear in number of services | Platform team |
| On-call | Each service needs an owner who can be woken | People, not servers | Teams' cognitive load |
| Duplicate data | Local copies to avoid temporal coupling | Storage plus staleness handling | Developers, users (stale reads) |
| Versioning | Contracts must evolve without lockstep | Version fields, deprecation windows | Producer teams |
One checkout request, before and after a split into 5 services
1 Monolith: 1 process, 1 transaction, p99 120 ms, one log stream
2 Split: 5 hops x ~2-5 ms network + serialisation, p99 tail of the slowest hop dominates
3 Failure: Pricing timeout -> retry x3 -> 3x load on a struggling service (cascading failure)
4 Debug: 5 log streams; without a trace ID, 40 minutes to find which hop failedReal scenario: a team whose p99 doubled after extracting a pricing service called four times per page; a payments flow that needed an outbox and an inbox to replace one COMMIT; a company whose test environment costs more than production because each team needs every service running.
Fix / how to use it: price the tax before splitting: count calls per request, invariants per boundary, and services per team. Pay it only where the benefit (independent change by an independent team, isolated scale or compliance) is larger. See Cascading Failures and Timeouts, Retries & Jitter for the runtime half.
Granularity: integrators, disintegrators and nanoservices Important
In plain words: two sets of forces pull a service apart or push it back together; the right size is where they balance.
Common misunderstanding: "A microservice should be under N lines of code." Hard Parts: "Granularity is not defined by the number of classes or lines of code in a service, but rather what the service does."
Definition: Ford et al. list six disintegrators ("When should I consider breaking apart a service into smaller parts?") and four integrators ("When should I consider putting services back together?"):
| Disintegrator (split) | Question (Hard Parts) | Integrator (merge) | Question (Hard Parts) |
|---|---|---|---|
| Service scope and function | "Is the service doing too many unrelated things?" | Database transactions | "Is an ACID transaction required between separate services?" |
| Code volatility | "Are changes isolated to only one part of the service?" | Workflow and choreography | "Do services need to talk to one another?" |
| Scalability and throughput | "Do parts of the service need to scale differently?" | Shared code | "Do services need to share code among one another?" |
| Fault tolerance | "Are there errors that cause critical functions to fail within the service?" | Data relationships | "can the data it uses be broken apart as well?" |
| Security | "Do some parts of the service need higher security levels than others?" | ||
| Extensibility | "Is the service always expanding to add new contexts?" |
A nanoservice is a service whose overhead (contract, pipeline, on-call, network hop) exceeds the value of what it does: one entity's CRUD, one function, a "service" that is always called together with one other service. Nanoservices are what you get when only disintegrators are considered.
Notification service: email, SMS, postal letter (Hard Parts example, summarised)
1 Scope: all three "notify a customer" -> cohesive, keep together
2 Volatility: postal letter code changes weekly -> disintegrator: split postal out?
3 Fault: email provider outage kills SMS too -> disintegrator
4 Integrators: no shared transaction, no shared data -> nothing pulls back
Result: postal letter separate; email + SMS maybe separate; one "Notification" boundary stays a team'sReal scenario: a shop with separate cart-service, cart-item-service and cart-total-service (nanoservices: every request calls all three); a fraud model split from payments for scale and a different team; an address-validation function that is better as a library or a SaaS call than a service.
Fix / how to use it: for any split, list the disintegrators that justify it and the integrators that oppose it, and write both in the ADR (Architecture Decisions). Hard Parts also offers two size metrics: number of statements and number of public operations; use them to spot outliers, not as targets.
Context mapping between services Important
In plain words: once you have boundaries, name the relationship across each one: who adapts to whom, and through what.
Common misunderstanding: "All integrations are the same: just call the API." The relationship decides who pays for change. A downstream team that conforms to an upstream model inherits every upstream change; one with an anticorruption layer pays once, in the layer.
Definition: Evans's context map patterns, as stated in the DDD Reference, applied to services (full modelling in Context Maps & Integration Patterns):
| Pattern | DDD Reference wording (short) | As a service relationship | Coupling it leaves |
|---|---|---|---|
| Partnership | "forge a partnership between the teams in charge of the two contexts" | Two teams plan and release interface changes jointly | Deployment coupling by agreement; keep it temporary |
| Shared kernel | "Designate with an explicit boundary some subset of the domain model that the teams agree to share. Keep this kernel small." | A tiny shared contract package (IDs, currency codes) | Implementation coupling, small and explicit |
| Customer/supplier | "downstream priorities factor into upstream planning" | Consumer contract tests run in the supplier's CI | Domain coupling, protected by tests |
| Conformist | "slavishly adhering to the model of the upstream team" | Downstream uses the upstream event model as-is | Downstream absorbs every upstream change |
| Anticorruption layer (ACL) | "create an isolating layer to provide your system with functionality of the upstream system in terms of your own domain model" | A translator at the consumer's edge | Upstream changes stop at the ACL |
| Open host service (OHS) | "Define a protocol that gives access to your subsystem as a set of services. Open the protocol" | A public, versioned API or event stream | Domain coupling only, for many consumers |
| Published language | "Use a well-documented shared language ... as a common medium of communication" | The event schema / OpenAPI document | Shared vocabulary, not shared code |
| Separate ways | "Declare a bounded context to have no connection to the others at all" | No integration; duplicate if needed | None |
OrderPlaced crossing three relationships
1 Orders (OHS) publishes orders.order_placed.v1 (published language)
2 Billing (customer/supplier + ACL) translates it to ChargeRequest; its contract test runs in Orders' CI
3 Shipping (conformist) stores the event fields as-is; accepts it changes when Orders changes
4 Orders renames total_cents in v2; Billing changes one ACL function; Shipping changes its schemaReal scenario: a company wrapping a 20-year-old ERP behind an ACL so new services never see its table names; payment providers (Stripe, Adyen) as open host services where every merchant is a conformist or builds an ACL; two teams in a partnership for the first quarter of a new product, moving to customer/supplier once the API settles.
Fix / how to use it: draw the map for your services and label every edge. Default to OHS + published language upstream and ACL downstream; treat partnership and shared kernel as short-lived, small exceptions.
Boundary evolution: merge, split, strangler fig, tactical forking Important
In plain words: boundaries are discovered, not decreed, so plan how to move them.
Common misunderstanding: "Merging services back is admitting failure." Lewis and Fowler treat it as normal design feedback: "If you find yourself repeatedly changing two services together, that's a sign that they should be merged." They also note why it is harder across a network: "Moving code is difficult across service boundaries, any interface changes need to be coordinated between participants".
Definition: four moves:
| Move | When | How | Source |
|---|---|---|---|
| Merge | High change coupling, chatty pair, shared invariant, one team owns both | Fold one service into the other behind the existing API; retire the second pipeline | Lewis and Fowler; Hard Parts integrators |
| Split | A disintegrator holds and a team can own the new part | Module boundary first, then data, then process | Newman's seams; Fowler's Monolith First |
| Strangler fig | Replacing a legacy system piece by piece | Route traffic for one capability to new code; grow until the old is gone | Fowler: "begins with small additions" and replaces the host gradually (Strangler Fig) |
| Tactical forking | Tangled monolith with no clean components | Copy the whole codebase, delete what the new service does not need | Hard Parts; Thoughtworks Radar (March 2022) |
Component-based decomposition (the other Hard Parts approach) suits monoliths that already have recognisable components: identify, measure and consolidate components, then extract them. Tactical forking suits the opposite: Thoughtworks Radar describes it as "one possible alternative to the more common approach of fully modularizing the codebase first", where "a team can create a new fork of the codebase and use that to address and extract one particular concern or area while deleting the unnecessary code."
Tactical forking: extracting Billing from a tangled monolith
1 Copy the monolith repo -> billing-svc
2 Route /billing/* to billing-svc; the monolith keeps the rest
3 In billing-svc: delete controllers, jobs, tables not reachable from billing paths (iterate until tests pass)
4 In the monolith: delete billing code once traffic is fully moved
5 Two smaller codebases; dead code removed on both sides; data split lastReal scenario: the Guardian website (cited by Lewis and Fowler) growing new features as services around a monolith core; a team that merged cart and checkout after measuring 70% change coupling; a bank strangling a mainframe batch system one product at a time.
Fix / how to use it: keep boundaries cheap to move as long as possible: module boundaries and schema-per-module before processes (Modular Monolith). When you extract, Dehghani's advice applies: "Go Macro First, then Micro", and decouple "Capability and not Code".
Measuring boundary health Good to know
In plain words: you can see bad boundaries in your deploy logs, traces and git history before you feel them in meetings.
Common misunderstanding: "The import graph shows our coupling." It shows static coupling only. Two services can have zero imports between them and still change together in every commit, because they share a concept, a table or a team. CodeScene's documentation: "Change Coupling means that two (or more) modules change together over time."
Definition: three families of boundary metrics:
| Metric | What it measures | How to collect | Healthy | Unhealthy |
|---|---|---|---|---|
| Deploy coupling ratio | Releases that needed another service released in the same window | CI/CD deploy events per service, grouped by change ticket | Under 10% | Over 20%, or "release train" exists |
| Independent deploy frequency | How often each service ships alone | Deploy log per pipeline | Daily or more for active services | Only on the shared release date |
| Call graph depth / fan-out | Synchronous hops per user request | Traces (OpenTelemetry), service-graph view | Depth 1-2 on critical path | Depth over 3, or cycles |
| Cross-service calls per request | Chattiness | Trace span counts | 0-2 | 10+ |
| Change coupling degree | How often two modules change in the same commit | git log analysis (tool below) | Under ~20% between services | Over 30% with 5+ shared commits |
| Cross-team coupling | Change coupling where modules belong to different teams | Change coupling + CODEOWNERS | Low | High: CodeScene notes "coordination costs in the organization might soar" |
| Shared table writers | Service roles with write grants on a table | information_schema.role_table_grants | 1 | 2+ |
Monthly boundary review, 15 minutes
1 go run ./cmd/changecoupling -repo . -depth 2 -since "3 months ago"
2 services/cart <-> services/checkout shared 41 degree 72% -> merge candidate
3 Traces: checkout p99 path depth 5 (cart, pricing, promo, tax, stock) -> make promo/tax async or local
4 Deploys: 9 of 31 releases bundled cart+checkout -> confirms (1)
5 Action: ADR-0021 "merge cart into checkout"; revisit in 3 monthsReal scenario: a team that used change coupling on its monolith's history to pick the first extraction (the module with the least coupling to everything else, as Newman advises: "pull out the seam that is least depended on"); a platform team that publishes a per-service "deploys alone %" dashboard; an architecture review that rejected a split because the two modules co-changed in 60% of commits.
Fix / how to use it: run the change-coupling tool on your repository, filter to pairs across service or team lines, and review the top five monthly alongside deploy and trace data. CodeScene's caution applies: change coupling "is neither good nor bad; it all depends on what modules are coupled and for what reason".
Mechanics
Drawing boundaries step by step Must-know
A boundary workshop (half a day, people who know the domain and the teams)
1 List business capabilities and subdomains (core / supporting / generic)
2 Event Storming: mark where the language changes -> candidate contexts
3 Overlay the org: which team would own each candidate? Any orphan or overloaded team?
4 Run the six heuristics on each line; mark FAILs
5 Run change coupling on history for the matching modules; mark pairs over 30%
6 Pick lines that pass; for each FAIL, name the mitigation or drop the line
7 Write one ADR per boundary: owner, data, contract, coupling accepted, revisit trigger
8 Implement as modules first; add arch tests; extract to a process only with a reasonEnforcing the data face in the database
Database roles make the data boundary a hard error instead of a convention. In PostgreSQL, one schema and one login role per service:
-- PostgreSQL: each service owns one schema and gets one role. Nobody else can touch it.
CREATE ROLE orders_svc LOGIN PASSWORD 'change-me';
CREATE ROLE billing_svc LOGIN PASSWORD 'change-me';
CREATE SCHEMA orders AUTHORIZATION orders_svc;
CREATE SCHEMA billing AUTHORIZATION billing_svc;
REVOKE ALL ON SCHEMA orders FROM PUBLIC;
REVOKE ALL ON SCHEMA billing FROM PUBLIC;
CREATE TABLE orders.orders (
id text PRIMARY KEY, customer_id text NOT NULL, currency char(3) NOT NULL,
total_cents bigint NOT NULL CHECK (total_cents >= 0), created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE orders.outbox (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, event_id text NOT NULL UNIQUE,
event_type text NOT NULL, payload jsonb NOT NULL, published_at timestamptz
);
CREATE TABLE billing.invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, account_ref text NOT NULL,
amount_minor bigint NOT NULL CHECK (amount_minor > 0), currency char(3) NOT NULL,
source_ref text NOT NULL, status text NOT NULL
);
CREATE TABLE billing.inbox (event_id text PRIMARY KEY, processed_at timestamptz NOT NULL DEFAULT now());
-- Health check: which roles can write which schema? More than one writer = shared-database coupling.
SELECT table_schema, grantee, string_agg(DISTINCT privilege_type, ',') AS privileges
FROM information_schema.role_table_grants
WHERE table_schema IN ('orders', 'billing') AND privilege_type IN ('INSERT', 'UPDATE', 'DELETE')
GROUP BY table_schema, grantee
ORDER BY table_schema, grantee;MySQL has no schema inside a database; the equivalent is one database per service (CREATE DATABASE billing) and GRANT ALL ON billing.* TO 'billing_svc'@'%', with no grant for orders_svc. On SQL Server use schemas with GRANT ... ON SCHEMA::billing TO billing_svc; on Oracle, one schema user per service.
Error messages you will see when a boundary is enforced
| Where | Message | Meaning |
|---|---|---|
| PostgreSQL | ERROR: permission denied for schema billing (SQLSTATE 42501) | Orders' role tried to read Billing's schema: the boundary held |
| MySQL | ERROR 1142 (42000): SELECT command denied to user 'orders_svc'@'%' for table 'invoices' | Same, MySQL wording |
| Go compiler | use of internal package ... not allowed | Imported another module's internal/ |
| Go arch test (this page) | orders/x.go imports academy/service-boundaries/billing (forbidden: orders may only share the published language) | The boundary rule was broken |
| Go contract test (this page) | billing needs field "total_cents"; provider no longer sends it | Producer broke a consumer's contract |
Pest arch() | Failed expectation naming the class and the forbidden namespace (exact wording depends on Pest version; not verified) | Module boundary broken |
| Pact (if you use it) | Verification failure listing the interaction and the mismatched field | Consumer-driven contract broken |
Go
The running example is two boundaries in a shop: Orders (places orders) and Billing (invoices customers). First the wrong shape, then the right one, then the tests and the measuring tool. The module is docs/snippets/architecture/service-boundaries/go; go vet ./... and go test ./... pass.
Wrong: shared tables and a synchronous chain
Checkout reads Billing's tables (implementation coupling), calls Pricing then Tax before it can answer (temporal coupling), and inserts Billing's invoice row inside its own transaction, which only works because the database is shared. Every coupling on the ladder is present:
// Package wrong shows the distributed-monolith shape: the Orders service
// reads and writes Billing's tables and calls two services synchronously
// before it can answer. It compiles and works on a good day.
package wrong
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"strings"
)
// Checkout is Orders' handler. Every line below couples it to another team.
type Checkout struct {
DB *sql.DB // the SAME database Billing and Customers use
HTTP *http.Client // used for synchronous calls in a chain
PricingURL string
TaxURL string
}
func (c *Checkout) PlaceOrder(ctx context.Context, customerID int64, sku string, qty int) error {
// Implementation coupling: Orders knows Billing's table and column names.
var creditLimit, openCents int64
err := c.DB.QueryRowContext(ctx, `
SELECT b.credit_limit_cents, COALESCE(SUM(i.amount_cents), 0)
FROM billing_accounts b
LEFT JOIN billing_invoices i ON i.account_id = b.id AND i.status = 'open'
WHERE b.customer_id = $1
GROUP BY b.credit_limit_cents`, customerID).Scan(&creditLimit, &openCents)
if err != nil {
return fmt.Errorf("read billing tables: %w", err)
}
// Temporal coupling: Pricing and Tax must both be up, in sequence,
// for Orders to accept a single order.
price, err := c.getInt(ctx, c.PricingURL+"/prices/"+sku)
if err != nil {
return fmt.Errorf("pricing down, checkout down: %w", err)
}
tax, err := c.getInt(ctx, fmt.Sprintf("%s/tax?amount=%d", c.TaxURL, price*int64(qty)))
if err != nil {
return fmt.Errorf("tax down, checkout down: %w", err)
}
total := price*int64(qty) + tax
if openCents+total > creditLimit {
return fmt.Errorf("credit limit exceeded")
}
// One transaction across "two services": works only because they share
// a database. Splitting the database later breaks this function.
tx, err := c.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
var orderID int64
if err := tx.QueryRowContext(ctx,
`INSERT INTO orders (customer_id, sku, qty, total_cents) VALUES ($1, $2, $3, $4) RETURNING id`,
customerID, sku, qty, total).Scan(&orderID); err != nil {
return err
}
// Orders writes Billing's invoice row directly: Billing's invariants are
// now enforced (or not) by another team's code.
if _, err := tx.ExecContext(ctx,
`INSERT INTO billing_invoices (account_id, order_id, amount_cents, status)
SELECT id, $2, $3, 'open' FROM billing_accounts WHERE customer_id = $1`,
customerID, orderID, total); err != nil {
return err
}
return tx.Commit()
}
func (c *Checkout) getInt(ctx context.Context, url string) (int64, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return 0, err
}
resp, err := c.HTTP.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, fmt.Errorf("%s: %s", url, strings.ToLower(resp.Status))
}
var v struct {
Cents int64 `json:"cents"`
}
return v.Cents, json.NewDecoder(resp.Body).Decode(&v)
}Right: published language, outbox, anticorruption layer
The published language is a package of data shapes only, versioned in its name. Both sides import it; neither imports the other:
// Package contracts is the published language between Orders and Billing.
// It contains data shapes only: no behaviour, no database code, no domain
// rules. Both services may import it; neither may import the other.
package contracts
import "time"
// OrderPlacedV1Type is the event type name on the wire (topic or routing key).
const OrderPlacedV1Type = "orders.order_placed.v1"
// OrderPlacedV1 is published by Orders after its local transaction commits
// (via the outbox). Fields are only ever added, never renamed or removed,
// within v1. A breaking change becomes orders.order_placed.v2.
type OrderPlacedV1 struct {
EventID string `json:"event_id"` // idempotency key for consumers
OccurredAt time.Time `json:"occurred_at"` // UTC
OrderID string `json:"order_id"`
CustomerID string `json:"customer_id"`
Currency string `json:"currency"` // ISO 4217
TotalCents int64 `json:"total_cents"`
Lines []LineV1 `json:"lines"`
SalesRegion string `json:"sales_region,omitempty"` // added later; optional
}
// LineV1 is one order line as Orders describes it.
type LineV1 struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
PriceCents int64 `json:"price_cents"`
}Orders writes the order and the event to its own outbox in one local transaction. No other service must be up for an order to be accepted (no temporal coupling); see Outbox for the relay:
// Package orders is the Orders boundary: it owns the orders tables and the
// outbox, and it tells the world what happened through the published
// language in package contracts. It never touches Billing's data.
package orders
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
"academy/service-boundaries/contracts"
)
// Line is Orders' own model of a line. It is not the wire type.
type Line struct {
SKU string
Quantity int
PriceCents int64
}
// Service places orders. Its only dependency is its own database.
type Service struct {
DB *sql.DB
Now func() time.Time
}
var ErrEmptyOrder = errors.New("orders: an order needs at least one line")
// Place stores the order and the OrderPlaced event in ONE local transaction.
// A relay (not shown; see the outbox chapter) publishes outbox rows later.
// No other service has to be up for an order to be accepted.
func (s *Service) Place(ctx context.Context, customerID, currency string, lines []Line) (string, error) {
if len(lines) == 0 {
return "", ErrEmptyOrder
}
var total int64
for _, l := range lines {
total += l.PriceCents * int64(l.Quantity)
}
orderID, eventID := newID("ord"), newID("evt")
evt := contracts.OrderPlacedV1{
EventID: eventID, OccurredAt: s.Now().UTC(),
OrderID: orderID, CustomerID: customerID,
Currency: currency, TotalCents: total,
}
for _, l := range lines {
evt.Lines = append(evt.Lines, contracts.LineV1{SKU: l.SKU, Quantity: l.Quantity, PriceCents: l.PriceCents})
}
payload, err := json.Marshal(evt)
if err != nil {
return "", err
}
tx, err := s.DB.BeginTx(ctx, nil)
if err != nil {
return "", err
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders.orders (id, customer_id, currency, total_cents) VALUES ($1, $2, $3, $4)`,
orderID, customerID, currency, total); err != nil {
return "", fmt.Errorf("insert order: %w", err)
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders.outbox (event_id, event_type, payload) VALUES ($1, $2, $3)`,
eventID, contracts.OrderPlacedV1Type, payload); err != nil {
return "", fmt.Errorf("insert outbox: %w", err)
}
return orderID, tx.Commit()
}
func newID(prefix string) string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return prefix + "-" + hex.EncodeToString(b)
}Billing has its own model (ChargeRequest) and one translator, the ACL, that is the only code aware of Orders' event:
// Package billing is the Billing boundary. It owns invoices and credit, and
// it learns about orders only through the published OrderPlaced event.
package billing
import (
"errors"
"fmt"
"academy/service-boundaries/contracts"
)
// ChargeRequest is Billing's OWN model. Billing talks about "billable
// accounts" and "charges", not about orders and lines.
type ChargeRequest struct {
IdempotencyKey string
AccountRef string
AmountMinor int64
Currency string
SourceRef string // "order:<id>", for the audit trail
}
var errInvalidEvent = errors.New("billing: invalid OrderPlaced event")
// TranslateOrderPlaced is the anticorruption layer (ACL): the only place in
// Billing that knows the shape of Orders' event. If Orders publishes v2,
// only this function (and a v2 twin) changes.
func TranslateOrderPlaced(e contracts.OrderPlacedV1) (ChargeRequest, error) {
if e.EventID == "" || e.CustomerID == "" || e.TotalCents <= 0 || len(e.Currency) != 3 {
return ChargeRequest{}, fmt.Errorf("%w: %+v", errInvalidEvent, e)
}
return ChargeRequest{
IdempotencyKey: e.EventID,
AccountRef: "customer:" + e.CustomerID,
AmountMinor: e.TotalCents,
Currency: e.Currency,
SourceRef: "order:" + e.OrderID,
}, nil
}Its consumer is idempotent through an inbox table in the same transaction as the invoice (Idempotent Consumers & Inbox):
package billing
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"academy/service-boundaries/contracts"
)
// Consumer handles orders.order_placed.v1 messages from the broker.
type Consumer struct {
DB *sql.DB // Billing's own database; Orders has no credentials for it
}
// Handle is idempotent: the event id is stored in an inbox table inside the
// same transaction as the invoice, so a redelivered message is a no-op.
func (c *Consumer) Handle(ctx context.Context, body []byte) error {
var evt contracts.OrderPlacedV1
if err := json.Unmarshal(body, &evt); err != nil {
return fmt.Errorf("decode: %w", err) // poison message: route to DLQ
}
req, err := TranslateOrderPlaced(evt)
if err != nil {
return err
}
tx, err := c.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx,
`INSERT INTO billing.inbox (event_id) VALUES ($1) ON CONFLICT (event_id) DO NOTHING`,
req.IdempotencyKey)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return nil // already processed
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO billing.invoices (account_ref, amount_minor, currency, source_ref, status)
VALUES ($1, $2, $3, $4, 'open')`,
req.AccountRef, req.AmountMinor, req.Currency, req.SourceRef); err != nil {
return err
}
return tx.Commit()
}package billing
import (
"testing"
"academy/service-boundaries/contracts"
)
func TestTranslateOrderPlaced(t *testing.T) {
got, err := TranslateOrderPlaced(contracts.OrderPlacedV1{
EventID: "evt-1", OrderID: "ord-9", CustomerID: "cus-7", Currency: "EUR", TotalCents: 4200,
})
if err != nil {
t.Fatal(err)
}
want := ChargeRequest{IdempotencyKey: "evt-1", AccountRef: "customer:cus-7", AmountMinor: 4200, Currency: "EUR", SourceRef: "order:ord-9"}
if got != want {
t.Fatalf("got %+v, want %+v", got, want)
}
if _, err := TranslateOrderPlaced(contracts.OrderPlacedV1{EventID: "evt-2"}); err == nil {
t.Fatal("expected an error for an incomplete event")
}
}Tests that keep the boundary honest
The architecture test parses imports and fails the build if Orders imports Billing, Billing imports Orders, or the contracts package grows behaviour (database/sql):
package boundaries_test
import (
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"strings"
"testing"
)
// The rules of the boundary, as data. A boundary that exists only in a
// diagram is a wish; this test makes it a build failure.
var forbidden = map[string][]string{
"orders": {"academy/service-boundaries/billing"},
"billing": {"academy/service-boundaries/orders"},
"contracts": {"academy/service-boundaries/orders", "academy/service-boundaries/billing", "database/sql"},
}
func TestBoundaries(t *testing.T) {
for dir, bans := range forbidden {
err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") {
return err
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, imp := range f.Imports {
p := strings.Trim(imp.Path.Value, `"`)
for _, ban := range bans {
if p == ban || strings.HasPrefix(p, ban+"/") {
t.Errorf("%s imports %s (forbidden: %s may only share the published language)", path, p, dir)
}
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
}The consumer-driven contract test: Billing commits the fields it reads to a JSON file; Orders' CI encodes a real event and checks every field and type. Renaming total_cents fails Orders' build, not Billing's production:
{
"consumer": "billing",
"provider": "orders",
"event": "orders.order_placed.v1",
"required_fields": {
"event_id": "string",
"occurred_at": "string",
"order_id": "string",
"customer_id": "string",
"currency": "string",
"total_cents": "number"
}
}package contracts
import (
"encoding/json"
"os"
"testing"
"time"
)
// consumerContract is what a consumer team commits to this repository:
// the fields it reads and their JSON types. The provider's CI runs this test,
// so Orders cannot remove or retype a field Billing relies on.
type consumerContract struct {
Consumer string `json:"consumer"`
Provider string `json:"provider"`
Event string `json:"event"`
RequiredFields map[string]string `json:"required_fields"`
}
func TestOrderPlacedV1SatisfiesBillingContract(t *testing.T) {
raw, err := os.ReadFile("testdata/billing_expects_order_placed_v1.json")
if err != nil {
t.Fatal(err)
}
var c consumerContract
if err := json.Unmarshal(raw, &c); err != nil {
t.Fatal(err)
}
if c.Event != OrderPlacedV1Type {
t.Fatalf("contract is for %q, provider publishes %q", c.Event, OrderPlacedV1Type)
}
// Encode a sample event exactly as the provider would publish it.
sample := OrderPlacedV1{
EventID: "evt-1", OccurredAt: time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC),
OrderID: "ord-1", CustomerID: "cus-1", Currency: "EUR", TotalCents: 12000,
Lines: []LineV1{{SKU: "BOOK-1", Quantity: 2, PriceCents: 6000}},
}
body, err := json.Marshal(sample)
if err != nil {
t.Fatal(err)
}
var wire map[string]any
if err := json.Unmarshal(body, &wire); err != nil {
t.Fatal(err)
}
for field, want := range c.RequiredFields {
v, ok := wire[field]
if !ok {
t.Errorf("%s needs field %q; provider no longer sends it", c.Consumer, field)
continue
}
if got := jsonType(v); got != want {
t.Errorf("%s expects %q to be %s, provider sends %s", c.Consumer, field, want, got)
}
}
}
func jsonType(v any) string {
switch v.(type) {
case string:
return "string"
case float64:
return "number"
case bool:
return "boolean"
case []any:
return "array"
case map[string]any:
return "object"
default:
return "null"
}
}Measuring: change coupling from git
changecoupling reads git log --name-only, maps each file to a module (the first -depth directories), skips huge commits (-max-files), and prints pairs that co-change, with the degree as shared commits divided by the average of the two modules' commit counts (the "sum of coupling" idea CodeScene documents; our formula is a simple variant):
// Command changecoupling finds modules that change together in git history.
// Two modules that keep appearing in the same commits are coupled, whatever
// the import graph says; if they belong to different services or teams,
// every such commit is a coordinated change across a boundary.
//
// go run ./cmd/changecoupling -repo ~/src/shop -depth 2 -since "12 months ago"
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"os/exec"
"sort"
"strings"
)
// Pair is one coupled pair of modules.
type Pair struct {
A, B string
Shared int // commits that touched both
RevsA, RevsB int // commits that touched each
DegreePercent int // Shared / average(RevsA, RevsB) * 100
}
// Options control the analysis.
type Options struct {
Depth int // path segments that name a module: 2 -> "services/orders"
MinShared int // ignore pairs that co-changed fewer times
MinDegree int // ignore pairs below this coupling percentage
MaxFiles int // skip huge commits (renames, formatting, dependency bumps)
}
func main() {
repo := flag.String("repo", ".", "path to a git repository")
since := flag.String("since", "12 months ago", "git --since value")
var o Options
flag.IntVar(&o.Depth, "depth", 2, "path segments that make up a module name")
flag.IntVar(&o.MinShared, "min-shared", 5, "minimum commits shared by a pair")
flag.IntVar(&o.MinDegree, "min-degree", 30, "minimum coupling degree in percent")
flag.IntVar(&o.MaxFiles, "max-files", 50, "ignore commits touching more files than this")
flag.Parse()
cmd := exec.Command("git", "-C", *repo, "log", "--no-merges", "--since="+*since,
"--name-only", "--pretty=format:@@%H")
out, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := cmd.Start(); err != nil {
fmt.Fprintln(os.Stderr, "git:", err)
os.Exit(1)
}
commits, err := ReadCommits(out, o)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := cmd.Wait(); err != nil {
fmt.Fprintln(os.Stderr, "git:", err)
os.Exit(1)
}
pairs := Couple(commits, o)
fmt.Printf("%-32s %-32s %7s %7s %7s %7s\n", "MODULE A", "MODULE B", "SHARED", "REVS A", "REVS B", "DEGREE")
for _, p := range pairs {
fmt.Printf("%-32s %-32s %7d %7d %7d %6d%%\n", p.A, p.B, p.Shared, p.RevsA, p.RevsB, p.DegreePercent)
}
}
// ReadCommits parses `git log --name-only --pretty=format:@@%H` output into
// one set of module names per commit.
func ReadCommits(r io.Reader, o Options) ([]map[string]bool, error) {
var commits []map[string]bool
var files []string
flush := func() {
if len(files) == 0 || len(files) > o.MaxFiles {
files = files[:0]
return
}
mods := map[string]bool{}
for _, f := range files {
mods[ModuleOf(f, o.Depth)] = true
}
commits = append(commits, mods)
files = files[:0]
}
sc := bufio.NewScanner(r)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
switch {
case strings.HasPrefix(line, "@@"):
flush()
case line != "":
files = append(files, line)
}
}
flush()
return commits, sc.Err()
}
// ModuleOf maps a file path to its module: the first depth directories.
func ModuleOf(path string, depth int) string {
parts := strings.Split(path, "/")
if len(parts) <= 1 {
return "(root)"
}
dirs := parts[:len(parts)-1]
if len(dirs) > depth {
dirs = dirs[:depth]
}
return strings.Join(dirs, "/")
}
// Couple counts revisions and shared commits and returns pairs sorted by
// degree, then by shared commits.
func Couple(commits []map[string]bool, o Options) []Pair {
revs := map[string]int{}
shared := map[[2]string]int{}
for _, c := range commits {
mods := make([]string, 0, len(c))
for m := range c {
mods = append(mods, m)
revs[m]++
}
sort.Strings(mods)
for i := 0; i < len(mods); i++ {
for j := i + 1; j < len(mods); j++ {
shared[[2]string{mods[i], mods[j]}]++
}
}
}
var pairs []Pair
for k, n := range shared {
avg := float64(revs[k[0]]+revs[k[1]]) / 2
deg := int(float64(n) / avg * 100)
if n < o.MinShared || deg < o.MinDegree {
continue
}
pairs = append(pairs, Pair{A: k[0], B: k[1], Shared: n, RevsA: revs[k[0]], RevsB: revs[k[1]], DegreePercent: deg})
}
sort.Slice(pairs, func(i, j int) bool {
if pairs[i].DegreePercent != pairs[j].DegreePercent {
return pairs[i].DegreePercent > pairs[j].DegreePercent
}
if pairs[i].Shared != pairs[j].Shared {
return pairs[i].Shared > pairs[j].Shared
}
return pairs[i].A+pairs[i].B < pairs[j].A+pairs[j].B
})
return pairs
}package main
import (
"strings"
"testing"
)
const sampleLog = `@@c1
services/orders/place.go
services/billing/invoice.go
@@c2
services/orders/place.go
services/billing/invoice.go
@@c3
services/orders/cancel.go
@@c4
services/catalog/search.go
@@c5
services/orders/place.go
services/billing/credit.go
`
func TestCouple(t *testing.T) {
o := Options{Depth: 2, MinShared: 2, MinDegree: 30, MaxFiles: 50}
commits, err := ReadCommits(strings.NewReader(sampleLog), o)
if err != nil {
t.Fatal(err)
}
pairs := Couple(commits, o)
if len(pairs) != 1 {
t.Fatalf("want 1 pair, got %+v", pairs)
}
p := pairs[0]
// billing changed in 3 commits, orders in 4, together in 3: 3 / 3.5 = 85%.
if p.A != "services/billing" || p.B != "services/orders" || p.Shared != 3 || p.DegreePercent != 85 {
t.Fatalf("unexpected pair %+v", p)
}
}
func TestModuleOf(t *testing.T) {
cases := map[string]string{
"README.md": "(root)",
"services/orders/place.go": "services/orders",
"services/orders/internal/db/x.go": "services/orders",
"app/Modules/Billing/Invoice.php": "app/Modules",
}
for in, want := range cases {
if got := ModuleOf(in, 2); got != want {
t.Errorf("ModuleOf(%q) = %q, want %q", in, got, want)
}
}
}The Go angle
| Go feature | Boundary face it serves | Notes |
|---|---|---|
Packages and internal/ | Behaviour, information hiding | internal/ is enforced by the compiler; a service's internals stay private even in a monorepo |
A contracts package with types only | Published language | No methods with logic, no database/sql; checked by arch_test.go |
| Consumer-side interfaces | Domain coupling kept small | The consumer declares what it needs; the provider does not import it |
database/sql with one DSN per service | Data | Each binary gets credentials for its own schema only |
go/parser in tests | Fitness function | Import rules as a failing test |
encoding/json round trip in tests | Contract | Field names and types of the wire format, checked in the provider's CI |
os/exec + git log | Health measurement | Change coupling without external tools |
One cmd/<svc> per deployable | Deployment | The same packages can ship as one binary (modular monolith) or several |
Pact has a Go implementation (pact-go) if you prefer a broker-based consumer-driven workflow; Pact's docs define contract testing as "checking each application in isolation to ensure the messages it sends or receives conform to a shared understanding that is documented in a 'contract'." The stdlib version above is the same idea without the broker.
Laravel
The same two boundaries in a Laravel 13 application (PHP 8.4) structured as modules under App\Modules. PHP is not installed on the authoring machine; the code was reviewed, not run.
Wrong: one controller, three teams' data
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
/**
* The distributed-monolith shape in Laravel: "Orders" reads and writes
* Billing's tables and calls Pricing and Tax synchronously, in a chain.
*/
class CheckoutController
{
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'customer_id' => ['required', 'integer'],
'sku' => ['required', 'string'],
'qty' => ['required', 'integer', 'min:1'],
]);
// Implementation coupling: Billing's table and column names.
$credit = DB::table('billing_accounts as b')
->leftJoin('billing_invoices as i', function ($join) {
$join->on('i.account_id', '=', 'b.id')->where('i.status', 'open');
})
->where('b.customer_id', $data['customer_id'])
->groupBy('b.credit_limit_cents')
->selectRaw('b.credit_limit_cents, COALESCE(SUM(i.amount_cents), 0) AS open_cents')
->first();
// Temporal coupling: two synchronous hops before we can answer.
$price = Http::timeout(2)->get(config('services.pricing.url')."/prices/{$data['sku']}")
->throw()->json('cents');
$tax = Http::timeout(2)->get(config('services.tax.url').'/tax', ['amount' => $price * $data['qty']])
->throw()->json('cents');
$total = $price * $data['qty'] + $tax;
abort_if($credit === null || $credit->open_cents + $total > $credit->credit_limit_cents, 422, 'Credit limit exceeded');
// One transaction across two teams' tables: only possible because
// the database is shared. This is the line that blocks the split.
$orderId = DB::transaction(function () use ($data, $total) {
$orderId = DB::table('orders')->insertGetId([
'customer_id' => $data['customer_id'],
'sku' => $data['sku'],
'qty' => $data['qty'],
'total_cents' => $total,
]);
DB::table('billing_invoices')->insert([
'account_id' => DB::table('billing_accounts')->where('customer_id', $data['customer_id'])->value('id'),
'order_id' => $orderId,
'amount_cents' => $total,
'status' => 'open',
]);
return $orderId;
});
return response()->json(['id' => $orderId], 201);
}
}Right: published language, outbox, ACL, idempotent job
The published language is a final readonly class with an explicit wire format:
<?php
namespace App\Modules\Orders\Contracts;
/**
* Published language between Orders and its consumers. Data only: no
* Eloquent, no facades, no business rules. Fields are added, never renamed
* or removed, within v1; a breaking change becomes OrderPlacedV2.
*/
final readonly class OrderPlacedV1
{
public const TYPE = 'orders.order_placed.v1';
/**
* @param list<array{sku: string, quantity: int, price_cents: int}> $lines
*/
public function __construct(
public string $eventId,
public string $occurredAt,
public string $orderId,
public string $customerId,
public string $currency,
public int $totalCents,
public array $lines,
public ?string $salesRegion = null,
) {}
/** @return array<string, mixed> */
public function toArray(): array
{
return array_filter([
'event_id' => $this->eventId,
'occurred_at' => $this->occurredAt,
'order_id' => $this->orderId,
'customer_id' => $this->customerId,
'currency' => $this->currency,
'total_cents' => $this->totalCents,
'lines' => $this->lines,
'sales_region' => $this->salesRegion,
], fn ($v) => $v !== null);
}
/** @param array<string, mixed> $p */
public static function fromArray(array $p): self
{
return new self(
eventId: (string) $p['event_id'],
occurredAt: (string) $p['occurred_at'],
orderId: (string) $p['order_id'],
customerId: (string) $p['customer_id'],
currency: (string) $p['currency'],
totalCents: (int) $p['total_cents'],
lines: $p['lines'] ?? [],
salesRegion: $p['sales_region'] ?? null,
);
}
}Orders writes only to its own connection (orders, configured in config/database.php with credentials for the orders schema) and records the event in its outbox in the same DB::connection('orders')->transaction():
<?php
namespace App\Modules\Orders;
use App\Modules\Orders\Contracts\OrderPlacedV1;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Orders' use case. It writes only to the "orders" connection (its own
* schema and credentials) and records the event in its outbox in the same
* transaction. A relay publishes outbox rows to the broker afterwards.
*/
final class PlaceOrder
{
/**
* @param list<array{sku: string, quantity: int, price_cents: int}> $lines
*/
public function __invoke(string $customerId, string $currency, array $lines): string
{
throw_if($lines === [], \InvalidArgumentException::class, 'An order needs at least one line.');
$total = array_sum(array_map(fn (array $l) => $l['price_cents'] * $l['quantity'], $lines));
$orderId = (string) Str::ulid();
$event = new OrderPlacedV1(
eventId: (string) Str::uuid(),
occurredAt: now('UTC')->toIso8601ZuluString(),
orderId: $orderId,
customerId: $customerId,
currency: $currency,
totalCents: $total,
lines: $lines,
);
DB::connection('orders')->transaction(function () use ($orderId, $customerId, $currency, $total, $event) {
$db = DB::connection('orders');
$db->table('orders')->insert([
'id' => $orderId,
'customer_id' => $customerId,
'currency' => $currency,
'total_cents' => $total,
]);
$db->table('outbox')->insert([
'event_id' => $event->eventId,
'event_type' => OrderPlacedV1::TYPE,
'payload' => json_encode($event->toArray(), JSON_THROW_ON_ERROR),
]);
});
return $orderId;
}
}Billing's own model and its anticorruption layer:
<?php
namespace App\Modules\Billing\Acl;
/** Billing's own vocabulary: accounts and charges, not orders and lines. */
final readonly class ChargeRequest
{
public function __construct(
public string $idempotencyKey,
public string $accountRef,
public int $amountMinor,
public string $currency,
public string $sourceRef,
) {}
}<?php
namespace App\Modules\Billing\Acl;
use App\Modules\Orders\Contracts\OrderPlacedV1;
use InvalidArgumentException;
/**
* Anticorruption layer: the only Billing class that knows Orders' event.
*/
final class OrderPlacedTranslator
{
public function translate(OrderPlacedV1 $e): ChargeRequest
{
if ($e->eventId === '' || $e->customerId === '' || $e->totalCents <= 0 || strlen($e->currency) !== 3) {
throw new InvalidArgumentException("Invalid OrderPlaced event {$e->eventId}");
}
return new ChargeRequest(
idempotencyKey: $e->eventId,
accountRef: "customer:{$e->customerId}",
amountMinor: $e->totalCents,
currency: $e->currency,
sourceRef: "order:{$e->orderId}",
);
}
}The consumer is a queued job (ShouldQueue with the Queueable trait, $tries and backoff()); insertOrIgnore on the inbox returns the number of inserted rows, so a redelivery inserts 0 and returns early:
<?php
namespace App\Modules\Billing\Jobs;
use App\Modules\Billing\Acl\OrderPlacedTranslator;
use App\Modules\Orders\Contracts\OrderPlacedV1;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
/**
* Billing's consumer for orders.order_placed.v1. The payload arrives as an
* array (from the outbox relay or a broker consumer); Billing writes only to
* its own "billing" connection. Idempotent through the inbox table.
*/
final class HandleOrderPlaced implements ShouldQueue
{
use Queueable;
public int $tries = 5;
/** @param array<string, mixed> $payload */
public function __construct(public array $payload) {}
/** @return list<int> */
public function backoff(): array
{
return [5, 30, 120, 600];
}
public function handle(OrderPlacedTranslator $acl): void
{
$charge = $acl->translate(OrderPlacedV1::fromArray($this->payload));
DB::connection('billing')->transaction(function () use ($charge) {
$db = DB::connection('billing');
$fresh = $db->table('inbox')->insertOrIgnore(['event_id' => $charge->idempotencyKey]);
if ($fresh === 0) {
return; // redelivery: already invoiced
}
$db->table('invoices')->insert([
'account_ref' => $charge->accountRef,
'amount_minor' => $charge->amountMinor,
'currency' => $charge->currency,
'source_ref' => $charge->sourceRef,
'status' => 'open',
]);
});
}
}Tests that keep the boundary honest
Pest architecture tests: "Architecture testing enables you to specify expectations that test whether your application adheres to a set of architectural rules" (pestphp.com). not->toUse forbids dependencies; toOnlyBeUsedIn "enables you to limit the usage of a specific class or set of classes to only particular parts of your application" (the docs show a string argument; the array form used here is not verified against the docs):
<?php
// Pest architecture tests: the boundary rules fail the build, not a review.
arch('orders never reaches into billing')
->expect('App\Modules\Orders')
->not->toUse('App\Modules\Billing');
arch('billing sees only the published language of orders')
->expect('App\Modules\Billing')
->not->toUse([
'App\Modules\Orders\PlaceOrder',
'App\Modules\Orders\Models',
]);
arch('the published language is plain data')
->expect('App\Modules\Orders\Contracts')
->not->toUse([
'Illuminate\Support\Facades\DB',
'Illuminate\Database\Eloquent\Model',
]);
arch('only the ACL touches the orders contract inside billing')
->expect('App\Modules\Orders\Contracts')
->toOnlyBeUsedIn([
'App\Modules\Orders',
'App\Modules\Billing\Acl',
'App\Modules\Billing\Jobs',
]);The contract test reads the same consumer contract file as the Go version:
<?php
use App\Modules\Orders\Contracts\OrderPlacedV1;
// Consumer-driven contract: Billing commits the fields it reads; Orders' CI
// runs this test, so a rename or removal fails before it ships.
it('still satisfies what billing expects from orders.order_placed.v1', function () {
$contract = json_decode(
file_get_contents(base_path('contracts/billing_expects_order_placed_v1.json')),
true,
flags: JSON_THROW_ON_ERROR,
);
expect($contract['event'])->toBe(OrderPlacedV1::TYPE);
$wire = json_decode(json_encode((new OrderPlacedV1(
eventId: 'evt-1',
occurredAt: '2026-11-25T10:00:00Z',
orderId: 'ord-1',
customerId: 'cus-1',
currency: 'EUR',
totalCents: 12000,
lines: [['sku' => 'BOOK-1', 'quantity' => 2, 'price_cents' => 6000]],
))->toArray()), true);
foreach ($contract['required_fields'] as $field => $type) {
expect($wire)->toHaveKey($field);
$actual = match (true) {
is_string($wire[$field]) => 'string',
is_int($wire[$field]), is_float($wire[$field]) => 'number',
is_bool($wire[$field]) => 'boolean',
is_array($wire[$field]) => 'array',
default => 'null',
};
expect($actual)->toBe($type, "billing expects {$field} to be {$type}");
}
});The Laravel angle
| Laravel feature | Boundary face it serves | Notes |
|---|---|---|
Multiple connections in config/database.php, DB::connection('billing') | Data | One connection and DB user per module/service; the grant does the enforcing |
| Module namespaces + service providers | Behaviour | One provider per module wires it; nothing else reaches in |
Events with ShouldDispatchAfterCommit | Temporal (in-process) | The Laravel 13 events docs: implement this interface so an event is dispatched only after the transaction commits |
Queued jobs and listeners (ShouldQueue, $tries, backoff()) | Temporal | Work continues when the consumer is slow or down |
insertOrIgnore, unique keys | Idempotency | Inbox pattern without extra packages |
Pest arch() | Fitness function | not->toUse, toOnlyBeUsedIn, ignoring |
Http::timeout()->retry() | Temporal, when sync is unavoidable | Bound the call; never chain three of them on the request path |
Event::fake(), Queue::fake() | Testing | Test a module's published events without the consumer (Testing Messaging) |
Solving the classic problems
Two services share one database
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Schema + role per service | Separate schemas, one writer role each; others lose grants | Cheap, immediate, enforceable | Same server: shared resource limits, shared outages |
| Database view as a read contract | Provider publishes a view; consumer reads only that | Hides table layout | Still runtime coupling; Newman: "Useful only for read-only" (reader's notes) |
| API or events + local projection | Consumer keeps its own copy from events | Removes runtime and implementation coupling | Eventual consistency; projection code |
| Database per service | Separate instance or cluster | Full isolation | Cross-domain queries move to reporting or CQRS (Data Ownership) |
A synchronous call chain on the critical path
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Event-carried state | Consumer stores what it needs from events | No call at request time | Stale data window |
| Async command | Accept the request, finish later | Callee outage does not block the user | UX must handle "pending" |
| Merge the chatty pair | One service, in-process calls | Removes the hop and the contract | Bigger service; check ownership |
| Bound the call | Timeout, retry with jitter, circuit breaker, fallback | Limits damage | Still temporal coupling (Circuit Breaker) |
A shared library with domain logic
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Copy the code | Each service owns its version of the rule | No lockstep upgrades | Rules may drift (sometimes correctly: different contexts) |
| Publish a contract package with data only | Types, IDs, enums; no rules | Small, stable, explicit (a shared kernel) | Version it carefully |
| Move the rule into one service | Others ask or listen | One owner for the rule | New domain coupling |
| Keep technical libraries | Logging, tracing, HTTP clients | Fine: no domain meaning | Upgrade cadence still matters |
Lockstep deploys and release trains
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Expand and contract | Add the new field, migrate consumers, remove the old later | No coordinated release | Two-step changes, temporary duplication |
| Versioned events and APIs | order_placed.v1 and .v2 side by side | Consumers move at their own pace | Producer runs both for a while |
| Consumer-driven contract tests | Consumers' expectations run in the provider's CI | Breaking changes caught before deploy | Contract files to maintain |
| Merge services that always ship together | One deployable | Honest about the coupling | Larger blast radius |
Services split by entity
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Re-cut by capability | Group entities by the use cases that change them | Features land in one service | Data migration between services |
| Merge into a modular monolith | Modules keep the logical split | Transactions return | One deployable again |
| Keep a thin entity service only for a generic subdomain | e.g. an address book with no rules | Low churn makes it harmless | Rarely the case for core entities |
Choosing
| Situation | Recommended boundary approach | Extra technique | Reason |
|---|---|---|---|
| One team, new product | No service boundaries; modules in one deployable | Arch tests, ADRs | Fowler's Monolith First; Conway: a small team builds a monolith anyway |
| 2-4 teams, one product | Modular monolith with module per team | Schema + role per module, CODEOWNERS | Boundaries learned cheaply before a network |
| Teams blocked by each other's releases | Extract the module with the most independent change | Change coupling report to pick it | Least-depended-on seam first (Newman) |
| One part needs very different scale | Split that part only | Read replicas or a search index may be enough | Scale disintegrator, no others needed |
| Regulated data (cards, health) | Isolate it in its own service and store | Tokenisation; no regulated data in events | Compliance scope shrinks |
| Many services always deploy together | Merge them or fix contracts | Expand/contract, versioned events | Remove the distributed monolith |
| Legacy, tangled monolith | Tactical forking or strangler fig | Route per capability | Modularising first may take years |
| Legacy with clear components | Component-based decomposition | Measure components, then extract | Lower risk than forking |
| Overloaded team | Move a service to a new or other team, or merge services | Team Topologies: platform or complicated-subsystem team | Cognitive load is the limit |
| Two contexts, one invariant | Keep together | Model the invariant as one aggregate | Integrator: database transaction |
Decision flow for one proposed line:
1 Can exactly one team own each side? no -> do not split (or change teams first)
2 Is there an invariant that must be atomic across it? yes -> keep together, or design a saga first
3 Do the two sides change together more than ~30% of time? yes -> do not split; re-cut the line
4 Does a user request need more than 2 sync calls across? yes -> add events/projections, or re-cut
5 Is there a disintegrator (volatility, scale, fault, security, scope)? no -> keep as a module
6 Split: module -> schema+role -> contract + tests -> processIn architecture: from a single process to a distributed system
The same Orders/Billing line at each stage. What changes is the price of crossing it.
Monolith: one process, one database
How it shows up: boundaries are folders and namespaces; crossing is a function call; one COMMIT covers the order and the invoice.
Simplest correct usage: even here, give each future boundary its own package and a facade. Do not split yet: Conway says a team of a dozen will build a monolith, and that is fine.
Example (simple): a small shop: OrderController calls InvoiceService::createFor($order) inside one DB::transaction. One ADR records "Billing logic lives in app/Billing".
Example (production-shaped): a 25-person product where checkout and billing are folders. The weekly change-coupling report shows app/Orders ↔ app/Billing at 12%: the line is real, but not worth a network yet.
Modular monolith and multiple databases
How it shows up: modules own tables (schema + role), expose facades and publish in-process events; arch tests block imports of internals. This is where most boundaries should be tested before they are distributed (Modular Monolith).
Example: the code on this page running in one Laravel app: PlaceOrder writes to the orders connection and the outbox; a relay dispatches HandleOrderPlaced on the same queue; Billing writes only through the billing connection. Pest arch tests and the contract test run in one CI.
Modular monolith, one deployable
1 PlaceOrder: BEGIN (orders conn) -> INSERT orders.orders, orders.outbox -> COMMIT
2 Relay: SELECT unpublished outbox rows -> dispatch HandleOrderPlaced(payload) to queue
3 Worker: Billing ACL -> BEGIN (billing conn) -> INSERT inbox, invoices -> COMMIT
4 Billing down (worker stopped): orders still accepted; invoices catch up laterMicroservices: the boundary becomes a network
What survives: the published language, the ACL, the outbox and inbox, the contract test. Only the transport changes: the relay publishes to a broker topic orders.order_placed.v1 instead of the local queue.
What breaks: anything that relied on the shared process: a join across modules, a synchronous facade call in a hot loop (now a remote call), a shared transaction. The boundary tests from the modular stage tell you none of these exist.
orders-svc and billing-svc, separate pipelines and databases
1 POST /orders -> orders-svc commits order + outbox (orders DB)
2 relay publishes orders.order_placed.v1 (event_id = idempotency key)
3 billing-svc consumes; ACL translates; inbox dedups; invoice committed (billing DB)
4 Orders deploys v2 of its API on Monday; Billing deploys on Thursday; contract test guarded both
Failure path: broker down -> outbox rows accumulate; relay catches up; no order lostDistributed data: replicas, caches and multi-region
| Where the boundary is tested | What breaks | Design response |
|---|---|---|
| Billing reads its projection of orders | Projection lags the event stream | Show "processing" state; reconcile job; lag alert |
| Read replica of orders DB used by a reporting service | Reporting couples to Orders' schema | Publish a reporting contract (events into a warehouse), not replica access |
| Cache of customer credit in Orders | Stale credit approves an order over the limit | Treat as a hint; Billing makes the final decision asynchronously, with compensation |
| Multi-region: Orders active in two regions | Duplicate events, reordering | Idempotent consumers; per-key ordering (Ordering & Partitioning) |
| Cross-service invariant | No distributed ACID across services in practice | Sagas with compensation (Saga); 2PC only inside one database product (Distributed SQL & 2PC) |
Scaling path: 1×, 10×, 100×
| Scale | Boundaries | Practices |
|---|---|---|
| 1× (one team) | Modules in one deployable | Facades, ADRs, arch tests |
| 10× (3-8 teams) | Modular monolith or a few services per capability, each with one owner | Schema + role per module, contract tests, change-coupling review, platform basics (CI, broker) |
| 100× (dozens of teams) | Services per capability grouped by stream; platform and enabling teams | Team Topologies, context map maintained as a living document, deploy-coupling and trace metrics per boundary, regular merge/split reviews |
Lab: find, fix and guard a boundary
Everything runs offline with Go installed.
Setup.
cd docs/snippets/architecture/service-boundaries/go
go vet ./...
go test ./...
# ok academy/service-boundaries
# ok academy/service-boundaries/billing
# ok academy/service-boundaries/cmd/changecoupling
# ok academy/service-boundaries/contractsStep 1: read the wrong version. Open wrong/checkout.go and label each block with its coupling type (implementation, temporal, deployment). Expected: the SELECT ... billing_accounts and the INSERT INTO billing_invoices are implementation coupling; the two getInt calls are temporal coupling; the shared transaction is why the services cannot be deployed or split independently.
Step 2: break the boundary on purpose. Add _ "academy/service-boundaries/billing" to the imports of orders/orders.go and run go test . from the module root. Expected: TestBoundaries fails with orders/orders.go imports academy/service-boundaries/billing (forbidden: ...). Revert.
Step 3: break the contract on purpose. In contracts/orders_v1.go change the JSON tag of TotalCents to "total" and run go test ./contracts. Expected:
--- FAIL: TestOrderPlacedV1SatisfiesBillingContract
contract_test.go: billing needs field "total_cents"; provider no longer sends itRevert. Now do the change the safe way: add a new optional field Discount int64 json:"discount_cents,omitempty". Expected: the test passes (expand, do not rename).
Step 4: measure your own repository.
go run ./cmd/changecoupling -repo /path/to/your/repo -depth 2 -since "12 months ago" -min-shared 5
# MODULE A MODULE B SHARED REVS A REVS B DEGREE
# services/cart services/checkout 41 52 61 72%For a Laravel app use -depth 3 so app/Modules/Billing is one module. Expected: a ranked list. For each of the top five pairs, write down: same team or different teams? Same service or different services?
| Result | Same service | Different services, same team | Different services, different teams |
|---|---|---|---|
| Degree over 30% | Fine: cohesive | Merge candidate | Boundary problem: re-cut or merge, ADR |
| Degree 10-30% | Fine | Watch | Check the contract is small and versioned |
| Degree under 10% | Possibly two modules hiding in one | Good boundary | Good boundary |
Step 5: enforce the data face. In a local PostgreSQL, run the SQL from Mechanics, then connect as orders_svc and try SELECT * FROM billing.invoices;. Expected: ERROR: permission denied for schema billing. Run the grants query. Expected: each schema has exactly one writer.
Step 6 (Laravel, optional). Copy the PHP files into a Laravel 13 project with Pest, add orders and billing connections in config/database.php, copy php/contracts/ to the project root, and run ./vendor/bin/pest. Expected: four arch tests and the contract test pass; adding use App\Modules\Billing\Acl\ChargeRequest; to PlaceOrder.php fails "orders never reaches into billing".
Common misconceptions
| Belief | Reality |
|---|---|
| A boundary is a repository or a container | A boundary has four faces: data, behaviour, team, deployment; sharing any one leaks it |
| Conway's law is about the org chart | It is about communication paths; who actually talks to whom |
| Reorganising teams fixes the architecture | Fowler: with a rigid existing system it adds friction; change code and org together |
| Smaller services are more decoupled | Coupling and size are different; nanoservices are often more coupled |
| One bounded context = one microservice | A context can be a module, one service or several; correlation, not identity |
| Messaging removes coupling | It removes temporal coupling only; domain and implementation coupling remain |
| A shared domain library avoids duplication cheaply | It creates deployment and implementation coupling across every importer |
| A shared database is fine if each service uses its own tables | Only if roles enforce it; otherwise joins and writes creep in (microservices.io: development-time and runtime coupling) |
| Split by entity (User, Product, Order services) | Use cases cross entities; the result is chatty, anemic CRUD services |
| Merging services is a failure | It is normal feedback: "repeatedly changing two services together" means merge |
| The cost of microservices is infrastructure | The larger costs are latency, consistency, debugging, testing, on-call and versioning |
| You can get the boundaries right up front | Fowler: even experienced architects "have great difficulty getting boundaries right at the beginning" |
| The import graph shows the real coupling | Change coupling from git shows logical coupling that imports miss |
Cheat sheet
| Topic | Remember |
|---|---|
| Boundary | Data + behaviour + team + deployment; one writer per record |
| Conway's law | Systems copy communication structures; put boundaries on thin communication edges |
| Inverse Conway | Shape teams to shape the system; change code and org together |
| Team Topologies | Stream-aligned, platform, enabling, complicated-subsystem; collaboration, X-as-a-Service, facilitation |
| Cognitive load | The real size limit of what one team (and its services) can own |
| Strategies | Capability, subdomain, volatility, data ownership, scale, compliance; combine them |
| Heuristics | Info hiding, change together, transaction boundary, data gravity, chatty test, one owner |
| Coupling ladder | Domain (keep small) < temporal < deployment < implementation (never across services) |
| Distributed monolith | Lockstep deploys, shared DB, sync chains, shared domain libs |
| Hidden tax | Latency, availability (0.999^n), consistency, debugging, testing, infra, on-call, duplicate data, versioning |
| Granularity | 6 disintegrators vs 4 integrators; size is what it does, not LOC |
| Context map | OHS + published language upstream, ACL downstream; partnership and shared kernel small and temporary |
| Evolution | Merge on change coupling; split via modules first; strangler fig; tactical forking for tangled code |
| Health metrics | Deploy coupling ratio, call depth, change coupling degree, writers per table |
| Enforcement | DB roles, arch tests (Go parser, Pest arch()), contract tests, CODEOWNERS |
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 — Name the four faces of a service boundary and one leak for each. Must-know
Answer
Answer: Data (another service writes your table), behaviour (the rule is copied or in a shared lib), team (two teams own it), deployment (release train). See What a boundary is.
2 — State Conway's law in his words and say what it is really about. Must-know
Answer
Answer: "organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations." It is about communication paths, not the org chart as such. See Conway's law.
3 — Why is the inverse Conway manoeuvre not an instant fix for an existing system? Important
Answer
Answer: With a rigid architecture, new teams no longer match the code, which "adds friction". Org and code must change together, in small steps. See Inverse Conway.
4 — Which Team Topologies team type exists to reduce cognitive load of stream-aligned teams through a self-service internal product, and which interaction mode does it use? Important
Answer
Answer: The platform team, mainly in X-as-a-Service mode (collaboration while the platform is being shaped). See Team Topologies.
5 — Three services at 99.9% availability are called in a synchronous chain. What is the best-case availability of the request, and which coupling type causes it? Must-know
Answer
Answer: 0.999^3 ≈ 99.7%. Temporal coupling. See The hidden tax.
6 — Why is "events instead of calls" not enough to remove coupling? Must-know
Answer
Answer: It removes temporal coupling. If the event is the producer's internal entity, implementation coupling remains; if versions must ship together, deployment coupling remains. See Coupling types.
7 — Give four symptoms of a distributed monolith and one metric for each. Important
Answer
Answer: Lockstep deploys (share of coordinated releases), shared database (writers per table), sync call chains (trace depth), shared domain libraries (services importing the same domain package); also change coupling degree. See The distributed monolith.
8 — Name the four granularity integrators from Hard Parts. Good to know
Answer
Answer: Database transactions, workflow and choreography, shared code, data relationships. See Granularity.
9 — Orders publishes an event that Billing and Shipping consume. Billing translates it to its own model; Shipping stores it as-is. Name the context-map patterns. Important
Answer
Answer: Orders: open host service with a published language. Billing: customer/supplier with an anticorruption layer. Shipping: conformist. See Context mapping.
10 — When would you choose tactical forking over component-based decomposition? Good to know
Answer
Answer: When the monolith is tangled and has no recognisable components, so modularising first would take too long; you copy the codebase and delete what the new service does not need. See Boundary evolution.
11 — Your change-coupling report shows cart and checkout, owned by two teams, co-changing in 72% of 41 shared commits. What do you do? Important
Answer
Answer: Treat it as a boundary problem: either merge them (and the teams' ownership) or re-cut the line so the frequently changing concept is on one side. Record it in an ADR. See Measuring boundary health.
12 — What does the Go contract test on this page protect against, and in whose CI does it run? Important
Answer
Answer: The provider (Orders) removing or retyping a field the consumer (Billing) reads; it runs in the provider's CI. See Go.
Glossary
| Term | Meaning |
|---|---|
| Service boundary | The line around one service's data, behaviour, owning team and deployment unit |
| Conway's law | Systems copy the communication structure of the organisation that designs them (Conway 1968) |
| Homomorphism | Conway's term for the structure-preserving map between organisation and system |
| Inverse Conway manoeuvre | Changing team structure to encourage a desired architecture (LeRoy and Simons, 2010) |
| Team Topologies | Skelton and Pais's model: four team types, three interaction modes |
| Stream-aligned team | Team aligned to a flow of work from a segment of the business domain |
| Platform team | Team providing an internal product (CI, broker, observability) consumed self-service |
| Enabling team | Team that coaches others to overcome obstacles |
| Complicated-subsystem team | Team owning a component that needs specialist expertise |
| X-as-a-Service | Interaction mode where one team consumes another's offering with little collaboration |
| Collaboration / facilitation | Interaction modes: working together for a period; coaching |
| Cognitive load | The amount a team must understand to own its software; the limit on boundary size |
| Two-pizza team | A team small enough to be fed by two pizzas (at most about a dozen people) |
| Bounded context | Boundary within which one model and its language are defined and applicable (Evans) |
| Polyseme | A word with several related meanings across contexts ("customer", "meter") |
| Business capability | Something a business does to generate value (microservices.io) |
| Subdomain (core, supporting, generic) | Part of the business domain, classified by how differentiating it is |
| Volatility-based decomposition | Splitting by how often code changes |
| Data ownership | One service is the system of record and sole writer for a piece of data |
| Data gravity | Use cases and services drift toward where the data they need already lives |
| Seam | A part of code that can be worked on in isolation (Feathers), used by Newman to find service boundaries |
| Information hiding | Hiding a design decision likely to change behind an interface (Parnas) |
| Common closure | Things that change together belong together |
| Chatty interface | A boundary crossed by many fine-grained calls per request |
| Domain coupling | One service needs functionality or information another provides |
| Temporal coupling | Both services must be available at the same time for work to complete |
| Deployment coupling | Services must be released together |
| Implementation coupling | One service depends on another's internals (tables, classes) |
| Distributed monolith | Many deployables coupled so tightly they change, deploy and fail together |
| Lockstep deploy / release train | Coordinated releases of several services at once |
| Hidden tax / microservice premium | The cost added by boundaries themselves: latency, consistency, testing, on-call, infra |
| Granularity disintegrator | A force that justifies splitting a service (scope, volatility, scale, fault tolerance, security, extensibility) |
| Granularity integrator | A force that justifies keeping services together (transactions, workflow, shared code, data relationships) |
| Nanoservice | A service whose overhead outweighs what it does |
| Entity service | A service built around one data entity's CRUD; usually a wrong cut |
| Context map | Diagram of bounded contexts and the relationships between them |
| Partnership | Two teams that succeed or fail together and coordinate interface evolution |
| Shared kernel | A small, explicitly shared part of the model and code |
| Customer/supplier | Upstream plans with downstream priorities; downstream's tests run upstream |
| Conformist | Downstream adopts the upstream model as-is |
| Anticorruption layer (ACL) | Downstream translator that keeps the upstream model out of its own |
| Open host service (OHS) | A protocol opened to all integrators as a set of services |
| Published language | A documented shared language (schema) used for integration |
| Separate ways | No integration between two contexts |
| Strangler fig | Gradually replacing a legacy system by growing new parts around it |
| Tactical forking | Copying a tangled codebase and deleting what a new service does not need |
| Component-based decomposition | Identifying and consolidating components in a monolith before extracting them |
| Change coupling | Modules that change together over time in version control |
| Deploy coupling ratio | Share of releases that needed another service released too |
| Contract test / consumer-driven contract | Each side tested in isolation against a documented contract; consumers publish their expectations |
| Architecture test / fitness function | An automated check that a structural rule still holds |
| Outbox / inbox | Local tables that make publishing and consuming atomic with business writes |
| Idempotency key | An identifier that makes repeated processing a no-op |
| Expand and contract | Add the new form, migrate users, remove the old form later |
References
- Melvin E. Conway, "How Do Committees Invent?", Datamation, April 1968 (author's online copy with 2010s note)
- Martin Fowler, "Conway's Law", 20 October 2022
- Martin Fowler, "Team Topologies", 25 July 2023; Team Topologies, Key concepts
- Martin Fowler, "Bounded Context", 15 January 2014
- Eric Evans, Domain-Driven Design Reference, 2015 (Bounded Context, Context Map, Partnership, Shared Kernel, Customer/Supplier, Conformist, Anticorruption Layer, Open-host Service, Published Language, Separate Ways, Big Ball of Mud)
- James Lewis and Martin Fowler, "Microservices", March 2014
- Martin Fowler, "Microservice Premium", 13 May 2015; "Monolith First", 3 June 2015; "Microservice Prerequisites"; "Microservices and the First Law of Distributed Objects", 13 August 2014; "Strangler Fig", 22 August 2024
- Zhamak Dehghani, "How to break a Monolith into Microservices", 24 April 2018
- Chris Richardson, microservices.io: Decompose by business capability, Decompose by subdomain, Shared database, Database per service
- Sam Newman, Building Microservices (O'Reilly, February 2015), chapter "Splitting the Monolith", free excerpt published by Thoughtworks
- Sam Newman, Monolith to Microservices (O'Reilly, 2019), table of contents on the author's site; coupling types and distributed monolith via Dan Lebrero's book notes (secondary)
- Neal Ford, Mark Richards, Pramod Sadalage, Zhamak Dehghani, Software Architecture: The Hard Parts (O'Reilly, October 2021), chapter 7 "Service Granularity", free excerpt published by Thoughtworks
- Thoughtworks Technology Radar, "Tactical forking", March 2022
- CodeScene documentation, "Change Coupling: Visualize Logical Dependencies"
- Pact documentation, Introduction; Pest, Architecture testing; Laravel 13, Events