Monolith vs Microservices vs Modular Monolith: Deciding
"So my primary guideline would be don't even consider microservices unless you have a system that's too complex to manage as a monolith." — Martin Fowler, Microservice Premium, 13 May 2015
Summary: Picking a deployment shape is a bet on what you need to optimise: delivery speed, independent scaling, team autonomy, fault isolation or cost. Start from that goal, buy the cheapest shape that reaches it, and write down the signal that would make you change your mind. Focus: The question behind the question, the decision drivers, the microservice premium item by item, startup → scale-up → enterprise timelines, the modular monolith as the default and where it stops being enough, signals to split and to merge, migration in both directions, a weighted scorecard, three filled ADRs, bad reasons, hybrid topologies, and one feature built in all three forms in Go and Laravel with the tests that change. Learning goal: Given a team, a product and a platform, name the goal, score the three forms against it, write the ADR with an explicit "revisit if" signal, and know the first two migration steps in either direction.
This chapter owns the decision. Each style has its own chapter that explains how it works inside: Layered Monolith, Modular Monolith and Microservices Architecture. After a decision to split, the next chapters take over: Service Boundaries (Conway's law, the distributed monolith), Service Communication (sync vs async, retries), Data Ownership and, for the migration mechanics, Strangler Fig. How to write and review an ADR in general is in Architecture Decisions.
Page map
| If you are looking for | Go to |
|---|---|
| The whole decision in three tables | Everything in one minute |
| Why this is a decision at all | Why the decision exists |
| Conway 1968 to Google 2023 and Prime Video 2023 | Where it comes from |
| Goal, premium, monolith-first, logical vs physical, granularity, cognitive load, DORA, split and merge signals | The concepts, one by one |
| Every driver in one table | Decision drivers |
| What microservices cost, line by line | Cost model |
| Startup, scale-up, enterprise | Timelines |
| What changes in code, measuring signals in SQL, error messages | Mechanics |
| One feature in three forms | Go, Laravel, Cost per form |
| Splitting, merging back, keeping modules clean, hybrids, bad reasons | Solving the classic problems |
| Flowchart, scorecard, three filled ADRs | Choosing |
| Monolith to distributed system | In architecture |
| Exercise with measurable output | Lab |
| Wrong beliefs, cheat sheet, self-check, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The three forms. Each style's inside is taught in its own chapter; here only what matters for choosing.
| Form | In plain words | Unit of deployment | Boundary enforced by | Cross-boundary call | Transaction across parts | Best when |
|---|---|---|---|---|---|---|
| Monolith (unstructured or layered) | One app, code organised by technical layer or not at all | One | Nothing but discipline | Function call | Yes, one database transaction | One small team, unclear domain, speed to market |
| Modular monolith | One app, cut into modules with public APIs and private internals | One | Language visibility, fitness tests (Go internal/, Pest arch(), Shopify Packwerk) | Function call through a module interface; in-process events | Yes, when you need it | Most systems, most of the time: several teams, one platform |
| Microservices | Many apps, each owning its data, deployed independently | Many | The network and separate repositories or pipelines | HTTP/gRPC or messages, with timeouts and retries | No; sagas, outbox, eventual consistency | Many teams that must ship independently; real scaling or isolation asymmetry; mature platform |
The question behind the question. "Should we use microservices?" is the wrong first question. Ask what you are optimising, then find the cheapest form that reaches it.
| You want to optimise | Measured by | Cheapest form that usually reaches it | Microservices needed when |
|---|---|---|---|
| Delivery speed of one team | DORA change lead time, deployment frequency | Monolith or modular monolith with a fast pipeline | Practically never for one team |
| Delivery speed of many teams | Lead time per team, merge/deploy queue wait | Modular monolith with module ownership and a merge queue | Teams still block each other on one release train after modularising |
| Scaling | Cost per request, p99 under load | Bigger machine, replicas, caches, a worker pool inside the monolith | One part needs very different hardware or scale (a 50x hot spot, GPUs) |
| Fault isolation | Blast radius of one bug | Bulkheads, separate worker processes from the same codebase | A failure in one part must not share memory, runtime or deploy with the rest |
| Team autonomy | Number of cross-team approvals per change | Module ownership (CODEOWNERS), module APIs | Teams need their own release cadence, stack or on-call |
| Regulatory isolation | Audit scope (PCI DSS, HIPAA, data residency) | Separate database schema and role | The auditor's scope must exclude everything else |
| Cost | Infra plus people-hours per month | Monolith | Rarely the reason; usually the opposite (see Prime Video) |
Signals, both directions (unpacked in split signals and merge signals):
| Signal to split one part out | Signal to merge services back |
|---|---|
| Deploy contention: changes to X wait in a shared release queue | Nanoservices: services too small to own a business capability |
| Scaling hot spot: X needs 10x+ the capacity of the rest | Chatty call graph: one user request fans out into many synchronous hops |
| Team coupling: one team's changes mostly touch X, and X only | Services that always deploy together (a distributed monolith) |
| Blast radius: X's failures take down unrelated features | Duplicated data and reconciliation jobs between services |
| Different compliance or security level for X | Operational burden: on-call load per engineer grows with every service |
Why the decision exists
Every system has a deployment shape, chosen or not. The shape decides what is cheap: in one process, calls, refactors across modules and transactions are cheap; across processes, independent deploys and independent scaling are cheap. You cannot have both sets of cheap things at once. That is why this is a decision and not a fashion.
| Fewer deployables (monolith side) | More deployables (microservice side) |
|---|---|
| Function calls: nanoseconds, never "partially" fail | Network calls: milliseconds, can time out after doing the work |
| One database transaction | Sagas, outbox, eventual consistency |
| Refactoring across modules is one commit | Changing a published API is a multi-release migration |
| One pipeline, one runtime to patch, one thing to monitor | N pipelines, N runtimes, distributed tracing |
| Everyone deploys together: one bad change blocks all | Each team deploys alone |
| Scaling is all-or-nothing | Each part scales on its own |
| Boundaries erode unless tooling enforces them | The network enforces boundaries (and freezes them) |
The analogy we reuse on this page: food service. A single kitchen where everyone cooks everything is the unstructured monolith: fast for three cooks, chaos for thirty. One kitchen with stations (grill, pastry, salad), each with its own counter and a pass where plates are handed over, is the modular monolith: same building, same gas line, clear ownership. A food court of separate restaurants is microservices: each opens, closes and hires on its own, but now there are N leases, N health inspections, and an order that needs a burger and a crêpe needs two queues and someone to combine them. Most restaurants should be one kitchen with stations. A food court makes sense when the volume and variety are huge and the tenants really are different businesses.
Three common misunderstandings, up front
- "Microservices are the modern way; monoliths are legacy." They are trade-offs, not generations. Fowler's Microservice Trade-Offs (2015) lists strong module boundaries, independent deployment and technology diversity as benefits, and distribution, eventual consistency and operational complexity as costs. Shopify kept one Rails codebase and modularised it; Segment and an Amazon Prime Video team moved from services to one process.
- "Microservices give us modularity." Only if the boundaries are right. Fowler writes of strong module boundaries: "there is no reason, in theory, why a microservices should have stronger module boundaries than a monolith". Wrong boundaries across a network are a distributed monolith, which is worse than either.
- "We will need microservices eventually, so start with them." You may not. And if you will, Fowler's Monolith First argues that "even experienced architects working in familiar domains have great difficulty getting boundaries right at the beginning". The counter-argument exists (Tilkov, below); read both.
Where it comes from
Conway, 1968. Melvin Conway's How Do Committees Invent? (Datamation, April 1968) is the root of every "team structure" argument on this page:
"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." — Melvin E. Conway, How Do Committees Invent?, Datamation, April 1968
SOA, 2000s. Service-oriented architecture already split systems into services, usually around an enterprise service bus (SOA). Lewis and Fowler note that Adrian Cockcroft at Netflix described the newer approach as "fine grained SOA".
Lewis and Fowler, 25 March 2014. Microservices named the style: "suites of independently deployable services", organised "around business capability, automated deployment, intelligence in the endpoints, and decentralized control of languages and data."
Microservice Prerequisites, 28 August 2014. Fowler: "if you don't have certain baseline competencies, you shouldn't consider using the microservice style": rapid provisioning, basic monitoring, rapid application deployment, and a DevOps culture.
The 2015 debate. Microservice Premium (13 May 2015) and Monolith First (3 June 2015) by Fowler; Sam Newman's Microservices For Greenfield? (7 April 2015); Stefan Tilkov's counterpoint Don't start with a monolith (9 June 2015); Fowler's Microservice Trade-Offs (1 July 2015).
Segment, July 2018. Goodbye Microservices (Alexandra Noonan) told how a team consolidated "over 140 services into a single service".
Shopify, 2019 and 2020. Deconstructing the Monolith (Kirsten Westeinde, 21 Feb 2019) and Under Deconstruction (Philip Müller, 16 Sep 2020): a monolith of "over 2.8 million lines of Ruby code" turned into a modular monolith, with the Wedge and then Packwerk tools to enforce boundaries.
Newman, Monolith to Microservices (O'Reilly). The whole book is on the migration decision; its chapter 2 Planning a Migration opens with Understanding the Goal, Why Might You Choose Microservices? and When Might Microservices Be A Bad Idea?, and chapter 3 catalogues Strangler Fig, Branch by Abstraction and Parallel Run. We read the book's table of contents on samnewman.io, not the chapters (they are behind O'Reilly's login), so we cite headings only.
Ford, Richards, Sadalage, Dehghani, Software Architecture: The Hard Parts (2022). Chapter 7 Service Granularity (free from Thoughtworks) gives six disintegrators and four integrators (below). The book's earlier chapter on architectural modularity, with its modularity drivers for breaking a monolith apart, sits behind O'Reilly's login; we did not read it and use only chapter 7.
Google, HotOS 2023. Ghemawat et al., Towards Modern Development of Cloud Applications, argue that "microservices conflate logical boundaries (how code is written) with physical boundaries (how code is deployed)", and report a prototype that "reduces application latency by up to 15×" and "reduces cost by up to 9×". The framework, Service Weaver, went into maintenance mode on 5 December 2024 and its GitHub repository was archived on 4 March 2026; the idea outlived the tool.
Amazon Prime Video, 22 March 2023. Marcin Kolny: moving one monitoring service "from a distributed microservices architecture to a monolith application" "reduced our infrastructure cost by over 90%".
Year Event What it added to the decision
1 1968 Conway: systems copy communication structures Team shape is an input, not an afterthought
2 2014 Lewis & Fowler name microservices Independent deployability as the defining trait
3 2014 Microservice Prerequisites Platform maturity is a gate
4 2015 Premium, Monolith First, Tilkov, Trade-Offs The default and its counter-argument
5 2018 Segment: 140+ services -> 1 Merging back is a legitimate move
6 2019 Shopify: monolith -> modular monolith The third option at large scale
7 2022 Hard Parts: disintegrators vs integrators A balanced checklist for granularity
8 2023 Google HotOS; Prime Video Logical vs physical boundaries; cost of distributionThe concepts, one by one
Each block: plain words, the usual wrong belief, a definition, a timeline, real scenarios, what provides it, and how to use it.
The question behind the question Must-know
In plain words: before choosing a shape, say which outcome you want to improve and how you will measure it.
Common misunderstanding: "Microservices are a goal." They are a means. Newman's migration book puts Understanding the Goal as the first section of Planning a Migration, before any pattern. Without a goal you cannot tell whether the migration worked, and you cannot stop.
Definition: a decision goal is a measurable quality outcome (DORA lead time, cost per 1,000 requests, p99 of one endpoint, number of teams blocked per release, audit scope) with a target and a deadline. The shape is chosen because it is the cheapest way to move that number.
Step Conversation in a scale-up (45 engineers, Laravel monolith)
1 CTO "We need microservices."
2 Arch "What hurts?" -> "Releases take 2 days; 6 teams wait for one train."
3 Arch Goal: change lead time from 2 days to under 4 hours for every team, by Q3.
4 Arch Cheapest options: merge queue, parallel CI, module ownership, feature flags.
5 Q2 Lead time 6 hours; the payments team still waits on full-suite tests (40 min).
6 Q3 Extract payments only (own compliance scope + its own cadence). Goal met.Real scenario: a team wanted "microservices for scale" while the database was at 15% CPU and the app servers were stateless behind a load balancer; adding replicas cost nothing. A second team wanted "microservices for autonomy" but had one team. A third had a real goal: the image pipeline needed GPUs and would have forced GPU nodes on the whole app.
What provides it:
| Goal | Leading indicator to watch | Where the method is taught |
|---|---|---|
| Delivery speed | DORA change lead time, deployment frequency | DORA |
| Reliability | Change fail rate, failed deployment recovery time, SLO burn | SLOs |
| Scaling | Cost per request, saturation of the hot part | Capacity estimation |
| Autonomy | Cross-team PR approvals per change | Cognitive load |
| Isolation | Incidents where an unrelated feature broke | Blast radius |
Fix / how to use it: write the goal in the Context section of the ADR with a number, and the opposite signal in Consequences as "revisit if" (see the three ADRs).
The microservice premium Must-know
In plain words: running many services costs extra every day, whether or not you get the benefits. Pay it only when the system's complexity is larger than the premium.
Common misunderstanding: "The cost is a one-time migration." The premium is recurring: every service needs a pipeline, dashboards, alerts, on-call, dependency upgrades, API versioning and contract tests, forever.
Definition: Fowler's term: microservices "introduce complexity on their own account. This adds a premium to a project's cost and risk". The items he lists: "automated deployment, monitoring, dealing with failure, eventual consistency, and other factors that a distributed system introduces." Itemised in the cost model.
Month A 5-person team adopting 12 services on day one
1 M1 Week 1-6: Kubernetes, Helm charts, 12 pipelines, service template
2 M2 First feature crosses 3 services; contract changes need 3 PRs, 3 deploys
3 M3 Local dev needs 12 containers + broker; laptops swap
4 M4 Bug: order created, stock not reserved (no shared transaction) -> saga
5 M5 On-call: 2 people for 12 services; alerts per service
6 M6 Feature throughput is below the 2-person competitor running one Laravel appReal scenario: Segment's post describes "3 full-time engineers spending most of their time just keeping the system alive" and "operational overhead increased linearly with each added destination"; a SaaS startup spends its first quarter on platform work instead of product; a regulated bank pays the premium knowingly because isolation is mandatory.
What provides it (who pays which part):
| Premium item | Paid by | Can a platform team amortise it? |
|---|---|---|
| Pipelines, templates, service scaffolding | Platform team | Yes, mostly |
| Observability (traces, metrics, logs per service) | Platform + every team | Partly |
| API versioning, contract tests | Every team, per API | No |
| Distributed failure handling (timeouts, retries, idempotency) | Every team, per call | Libraries help; design cannot be outsourced |
| Eventual consistency (sagas, outbox, reconciliation) | Every team, per workflow | No |
| On-call per service | Every team | No |
Fix / how to use it: price the premium before you decide: count services × (pipeline + dashboards + on-call share + upgrade work), and compare with the measured pain you are trying to remove.
Monolith first, and "Don't start with a monolith" Must-know
In plain words: most experts advise starting with one deployable and splitting later; a respected minority advises cutting a known domain into independent parts from day one. Both agree you must know the domain well before you cut.
Common misunderstanding: "Monolith first means don't think about structure." Microservice Premium says "Do pay attention to good modularity within that monolith". Monolith First calls designing the monolith carefully, "paying attention to modularity within the software, both at the API boundaries and how the data is stored", "the logical way" to execute the strategy, and then adds: "However I'd feel much more comfortable with this approach if I'd heard a decent number of stories where it worked out that way." So the modular route is the recommended one, and Fowler is candid that it is hard to pull off.
Definition: Monolith First (Fowler, 3 June 2015): "Almost all the successful microservice stories have started with a monolith that got too big and was broken up" and "you shouldn't start a new project with microservices, even if you're sure your application will be big enough to make it worthwhile." Reasons: YAGNI (you do not know yet if the product works) and boundaries ("By building a monolith first, you can figure out what the right boundaries are"). Variants Fowler lists: peel services off the edges; treat the monolith as a sacrificial architecture; or start with a few coarse-grained services (his footnote calls two of them a "duolith").
The counterpoint, in Fowler's own site:
"I'm firmly convinced that starting with a monolith is usually exactly the wrong thing to do." — Stefan Tilkov, Don't start with a monolith … when your goal is a microservices architecture, 9 June 2015
Tilkov's argument: inside a monolith "the parts will become extremely tightly coupled to each other"; "It's extremely hard to split up an existing monolith into separate pieces." He agrees on the condition: "you should know the domain you're building a system for very well before trying to partition it"; his ideal case is "building a second version of an existing system". Newman, quoted by Tilkov, sits on the other side: "I remain convinced that it is much easier to partition an existing", brownfield system "than to do so up front with a new, greenfield system."
Situation Lean towards
1 New product, unknown market fit Monolith first (modular inside)
2 Rewrite of a system you have run for 5 years Tilkov: cut by known domains (a few coarse services)
3 New product, 3 teams from day one, known domain Coarse-grained services or modular monolith + strict ownership
4 Team has never run a distributed system Monolith first, build the platform in parallelReal scenario: a startup ships its MVP in a modular Laravel app and extracts nothing for two years; a company rewriting its ten-year-old claims system starts with three coarse services along domains it already knows; a scale-up hires three teams at once and gives each a module with a published API inside one repo.
What provides it:
| Position | Source | Key condition |
|---|---|---|
| Monolith first | Fowler 2015; Newman 2015 (greenfield post) | Boundaries are unknown; product may fail |
| Don't start with a monolith | Tilkov 2015 | Domain well known; goal is a microservices architecture |
| Coarse services ("duolith") | Fowler 2015 footnote | Learn the platform with little inter-service refactoring |
| Logical monolith, physical decision later | Google HotOS 2023 | A runtime decides placement (Service Weaver, now archived) |
Fix / how to use it: decide which situation you are in (table above) and say it in the ADR; whatever you pick, enforce module boundaries in code from day one, because both camps agree boundaries are the hard part.
The modular monolith as the default Must-know
In plain words: one deployable, but cut inside into modules that own their code and their tables and talk only through public APIs. You get most of the boundary benefits without the network.
Common misunderstanding: "A modular monolith is a halfway house on the way to microservices." For most systems it is the destination. Shopify chose it for one of the largest Rails codebases and says: "Going from monolith to modular monolith was the next logical step for us."
Definition: Shopify's wording: "keep all of the code in one codebase, but ensure that boundaries were defined and respected between different components." The internals of the style are taught in Modular Monolith; here we care about one property: a module with a published API, private data and an enforced boundary can be extracted later by changing the implementation of its interface, not its callers (Go and Laravel show that change).
Step When the modular monolith is NOT enough (one of these must be true)
1 A part needs a different runtime or hardware (GPU, JVM library, 50x replicas)
2 A part must not share process, memory or deploy with others (PCI scope, untrusted plugins)
3 Teams still block each other after module ownership, merge queue and fast CI
4 The deployable is so big that build+test exceeds the team's lead-time goal despite caching
5 A part's release cadence differs radically (hourly ML model vs quarterly core)Real scenario: Shopify (Packwerk, component boundaries in one Rails app); a 30-engineer Go company with internal/ packages per module and one binary; a Laravel SaaS with app/Modules/*, one schema per module in PostgreSQL, Pest architecture tests in CI.
What provides it:
| Stack | Module boundary tool |
|---|---|
| Go | Packages, internal/ directories (Go 1.4 rule), import tests with go/parser |
| Laravel / PHP | app/Modules/* namespaces, service providers, Pest arch() (not->toUse, toOnlyBeUsedIn) |
| Ruby on Rails | Packwerk (Shopify), Rails engines |
| Java | JPMS module-info.java, ArchUnit, Spring Modulith |
| .NET | Assemblies with internal visibility, NetArchTest |
| Database | One schema and role per module; no cross-schema foreign keys |
Fix / how to use it: default to it, enforce boundaries with a fitness test, and keep each module's data private, because the database is where extraction usually fails (Data Ownership). Drawing the boundary itself is a domain question: Bounded Context; the module-level quality behind it (coupling, cohesion, information hiding) is in Design Quality.
Logical boundaries vs physical boundaries Important
In plain words: how you cut the code (modules) and how you run it (processes) are two separate decisions. Microservices tie them together; you do not have to.
Common misunderstanding: "To get clean boundaries we must deploy separately." Clean boundaries are a code property; separate deployment is a runtime property. Google's paper names the conflation as the root problem.
Definition: Ghemawat et al. (2023): "microservices conflate logical boundaries (how code is written) with physical boundaries (how code is deployed)." Their survey of internal teams found four reasons developers split binaries (performance, fault tolerance, abstraction boundaries, flexible rollouts) and five costs that contradict them: C1 "It hurts performance", C2 "It hurts correctness", C3 "It is hard to manage", C4 "It freezes APIs", C5 "It slows down application development". Their proposal: write a logical monolith of components; let a runtime choose placement; deploy atomically.
Decision axis Options Example in this page's code
1 Logical module with interface, events, private data inventory.API, ordering.Service
2 Physical same process | separate process | separate host cmd/shop/main.go: INVENTORY_URL unset or set
3 Rollout atomic (all together) | independent one binary vs two services
-> The logical cut is made once and kept; the physical choice can change per environment.Real scenario: Service Weaver components ran in one process locally and in many on GKE; a Go team runs the same binary as api and worker roles (one codebase, two physical deployments, one release); a Laravel app runs web, Horizon queue workers and the scheduler as separate processes from one codebase.
What provides it:
| Mechanism | Logical boundary | Physical choice |
|---|---|---|
| Go interface + composition root | inventory.API | Local struct or HTTP client |
| Laravel container binding | InventoryApi contract | DatabaseInventory or HttpInventoryApi |
| Same codebase, several process roles | Modules | Web, worker, scheduler processes |
| Service Weaver (archived 2026) | Components as Go interfaces | Runtime places components |
Fix / how to use it: make the logical cut first, with interfaces at module edges; postpone the physical cut until a measured reason appears; keep the composition root as the only place that knows the difference.
Granularity disintegrators and integrators Must-know
In plain words: there are good reasons to cut a service smaller and good reasons to put services back together; look at both lists before you decide.
Common misunderstanding: "If there is a reason to split, split." The authors of The Hard Parts call that the usual mistake: "One common mistake many development teams make is focusing too much on granularity disintegrators while ignoring granularity integrators."
Definition: from chapter 7 of Software Architecture: The Hard Parts (Ford, Richards, Sadalage, Dehghani, 2022). Disintegrators ("when to break a service into smaller pieces"): service scope and function, code volatility, scalability and throughput, fault tolerance, security, extensibility. Integrators ("putting services back together"): database transactions, workflow and choreography, shared code, data relationships.
| Driver | Kind | Question (Hard Parts wording) | Reason for applying (their Tables 7-2 and 7-3) |
|---|---|---|---|
| Service scope and function | Disintegrator | "Is the service doing too many unrelated things?" | Single-purpose services with tight cohesion |
| Code volatility | Disintegrator | "Are changes isolated to only one part of the service?" | Agility (reduced testing scope and deployment risk) |
| Scalability and throughput | Disintegrator | "Do parts of the service need to scale differently?" | Lower costs and faster responsiveness |
| Fault tolerance | Disintegrator | "Are there errors that cause critical functions to fail within the service?" | Better overall uptime |
| Security | Disintegrator | "Do some parts of the service need higher security levels than others?" | Better security access control to certain functions |
| Extensibility | Disintegrator | "Is the service always expanding to add new contexts?" | Agility (ease of adding new functionality) |
| Database transactions | Integrator | "Is an ACID transaction required between separate services?" | Data integrity and consistency |
| Workflow and choreography | Integrator | "Do services need to talk to one another?" | Fault tolerance, performance, and reliability |
| Shared code | Integrator | "Do services need to share code among one another?" | Maintainability |
| Data relationships | Integrator | "Although a service can be broken apart, can the data it uses be broken apart as well?" | Data integrity and correctness |
Trade-off statement (the book's method: drivers become questions for the business)
1 Disintegrator: code volatility -> payments changes weekly, catalog yearly
2 Integrator: database transactions -> order + payment must commit together today
3 Question to product owner: "Is weekly independent release of payments worth
replacing one transaction with a saga and a reconciliation report?"
4 Answer recorded in the ADR; the losing driver becomes a "revisit if" lineReal scenario: a ticketing team splits notification out (scalability, fault tolerance) but keeps ticket creation and assignment together (workflow: they call each other on every request); a fintech keeps ledger and account balance in one service (database transactions) and isolates card data (security).
What provides it: the modularity drivers here are the chapter-7 tables only, and they are tool-agnostic; the evidence comes from your repository (co-change analysis, see Mechanics), your load tests and your incident log.
Fix / how to use it: for each candidate split, write one line per disintegrator and one per integrator; if any integrator is strong (a transaction or chatty workflow), either keep the parts together or plan the saga and data duplication explicitly.
Team cognitive load and Conway's law Important
In plain words: a team can only hold so much in its head; the architecture should give each team a part it can fully own. And your system will end up shaped like your communication lines whether you plan it or not.
Common misunderstanding: "Microservices reduce cognitive load." Smaller code per service, yes; but each team now also owns a pipeline, a runtime, dashboards, on-call and API compatibility. Without a platform team, total load per team often goes up.
Definition: Team Topologies (Skelton and Pais) names four team types (stream-aligned, enabling, complicated-subsystem, platform) and three interaction modes (collaboration, X-as-a-Service, facilitating). The book's site: "Teams can only handle so much complexity before breaking down. Each new tool, responsibility or domain your team is given taxes their mental bandwidth." Conway's law and the Inverse Conway Maneuver ("deliberately alter the development team's organization structure to encourage the desired software architecture", Fowler's Conway's Law page) are taught in Service Boundaries; here they are decision inputs.
Org change Architecture consequence
1 1 team, 6 people One module map is enough; any form works, cheapest wins
2 4 stream-aligned teams, no platform team Modular monolith; services would put platform load on every team
3 8 stream-aligned teams + platform team Services for teams that need own cadence; platform pays the premium once
4 Re-org merges two teams Consider merging their services (Conway in reverse)Real scenario: a team of five owns nine services and spends Mondays on dependency bumps; a platform team provides a "golden path" template so a new service takes a day, not a month; two teams always editing the same module are merged, or the module is split along their work.
What provides it:
| Mechanism | Reduces which load |
|---|---|
Module ownership (CODEOWNERS) in a modular monolith | Coordination without platform cost |
| Platform team, X-as-a-Service | Per-service pipeline and runtime load |
| Thinnest viable platform | Prevents the platform itself becoming a load |
| Stream-aligned team per business capability | Cross-team hand-offs |
Fix / how to use it: count, per team, the things it must operate (services, databases, queues, dashboards, on-call rotations); if a split would raise that count without a platform to absorb it, do not split.
DORA metrics as the scoreboard Important
In plain words: measure delivery before and after, or you cannot say the new shape helped.
Common misunderstanding: "DORA has four keys." The original model had four; DORA's current guide describes five metrics, and replaced MTTR with failed deployment recovery time.
Definition: DORA's guide divides the metrics into throughput (change lead time: "The amount of time it takes for a change to go from committed to version control to deployed in production"; deployment frequency; failed deployment recovery time) and instability (change fail rate: "The ratio of deployments that require immediate intervention following a deployment"; deployment rework rate).
Quarter Lead time Deploys/week Change fail rate Decision
1 Q1 3 days 2 18% Baseline in a tangled monolith
2 Q2 9 hours 15 9% Modular monolith + merge queue + module tests
3 Q3 8 hours 17 8% Plateau: payments waits for full suite
4 Q4 8 h / 1 h 17 / 40 8% / 4% Payments extracted; others unchangedReal scenario: a migration "succeeded" by count of services while lead time doubled; another team proved with lead-time data that modularising was enough and cancelled a two-year rewrite.
What provides it: a deployments table and commit timestamps (SQL in Mechanics); GitHub/GitLab deployment APIs; DORA's Four Keys open-source project is one implementation (we did not read its code).
Fix / how to use it: record the five numbers before the decision, state the target in the ADR, and review them per quarter.
Signals to split Must-know
In plain words: split one part out when you can point at measured pain that only a separate deployable removes.
Common misunderstanding: "The codebase is big, so split." Size alone is solved by modules, ownership and faster builds; Fowler names sheer size as the biggest driver, but in the sense of "a monolith that's too big to modify and deploy", which is a delivery measurement, not a line count.
Definition: the four signals that justify an extraction:
| Signal | How to measure | Threshold you set in the ADR (example, yours to choose) |
|---|---|---|
| Deploy contention | Hours a ready change waits for the shared release; % of releases blocked by another team | A team waits more than its lead-time goal for others |
| Scaling hot spot | CPU/memory/requests per module from profiling or APM | One module needs over 10x the replicas or different hardware |
| Team coupling | Co-change: % of a team's commits that touch only module X | Over 80% of team A's changes are inside X, under 10% of others' |
| Blast radius | Incidents where a fault in X broke unrelated features | Two or more per quarter after bulkheads and timeouts |
Week Blast-radius signal in a monolith
1 W1 PDF export leaks memory under a big report
2 W1 Same pods serve checkout -> OOMKilled -> checkout 502s
3 W2 Fix: move PDF export to queue workers (same codebase, separate process)
4 W6 Recurs via a new export type; still contained to workers -> no service needed
-> A separate process from the same codebase was enough; extraction was not.Real scenario: search traffic is 20x checkout traffic and needs a different datastore; a payments module must sit in a reduced PCI scope; a data-science team deploys a model hourly while the core deploys daily.
What provides it: profilers (pprof, Blackfire), APM per route, git log co-change analysis, incident tags.
Fix / how to use it: extract one part, with the strangler fig approach, and measure the same signal afterwards (Solving).
Signals to merge Must-know
In plain words: if services always change together, call each other on every request, or cost more to run than they save, put them back together.
Common misunderstanding: "Merging services is a failure." Hard Parts makes integrators first-class; Segment and Prime Video published their consolidations as wins.
Definition: the signals:
| Signal | How it looks | Integrator it maps to |
|---|---|---|
| Nanoservices | Services smaller than a business capability; one entity per service | Service scope |
| Chatty call graph | One request makes many synchronous hops; latency adds up | Workflow and choreography |
| Lock-step deploys | Services that must be released together (a distributed monolith) | Shared code, data relationships |
| Duplicated data | Reconciliation jobs, "source of truth" debates | Data relationships, database transactions |
| Operational burden | On-call pages per engineer rise with service count | (cost, not in the book's list) |
Step Segment's consolidation (from the 2018 post)
1 Before one service and queue per destination; over 140 services
2 Pain "operational overhead increased linearly with each added destination"
3 Pain on-call paged for load spikes; 3 engineers keeping the system alive
4 Move "consolidate the now over 140 services into a single service"
5 Move monorepo: "For each of the 120 unique dependencies, we committed to having one version"
6 Result shared-library improvements: 32 in the microservice era, 46 one year after
7 Cost "Fault isolation is difficult": one bad destination can crash the service for allReal scenario: Segment's destinations; Prime Video's monitoring service, where "the high number of Tier-1 calls to the S3 bucket was expensive" and the orchestration hit "a hard scaling limit at around 5% of the expected load"; a team that split users, profiles and preferences into three services merges them into one "accounts" service.
What provides it: distributed traces (hops per request), deploy logs (co-deploy frequency), cost reports per service.
Fix / how to use it: merge with the same care as a split, in reverse: route, inline, migrate data, delete (Solving).
Distributed monolith and nanoservices Good to know
In plain words: a distributed monolith has the network costs of microservices and the coupling of a monolith; nanoservices are services too small to stand alone.
Common misunderstanding: "If each service has its own repo, we are decoupled." If they must deploy together, they are not. Fowler: "a suite of services that must have its deployments coordinated is not a microservice architecture".
Definition and depth: taught in Service Boundaries. For this decision, the point is that it is the worst quadrant: pay the premium, get none of the benefits.
Release of "add a discount field"
1 pricing-svc v2 adds field -> must deploy first
2 cart-svc v5 reads field -> waits for pricing
3 checkout-svc v9 shows field -> waits for cart
4 Rollback of pricing -> breaks cart and checkout => coordinated rollbackReal scenario: three services share one database schema and a "common" library that changes weekly; every release is a train.
What provides it / fix: merge them (merge signals) or redraw the boundary around the business capability.
Sacrificial architecture Good to know
In plain words: build the first version knowing you may throw it away once it succeeds.
Common misunderstanding: "Throwing code away means we failed." Fowler: "often the best code you can write now is code you'll discard in a couple of years time."
Definition: Fowler's SacrificialArchitecture: accept that an architecture fit for today's scale will be replaced; Monolith First lists replacing the monolith entirely as one route: "Don't be afraid of building a monolith that you will discard, particularly if a monolith can get you to market quickly."
Year Sacrificial plan
1 Y0 Laravel monolith, modular folders, ships in 8 weeks
2 Y2 Product proven; data model understood; 4 teams
3 Y2 Decide: modularise in place (default) or rewrite core around known domains (Tilkov's "second version")Real scenario: an MVP built to test the market; a hackathon project promoted to production with an explicit expiry date in its ADR.
What provides it / fix: an ADR that says "expected lifetime" and the signal that triggers replacement.
Decision drivers
The full checklist. Score each in the scorecard; a driver that does not apply gets weight 1.
| Driver | Question to ask | Favours monolith / modular | Favours microservices | Evidence to collect |
|---|---|---|---|---|
| Team size and number | How many teams must ship independently? | 1-4 teams | Many stream-aligned teams with distinct cadence | Org chart, CODEOWNERS, co-change |
| Domain clarity | Are the boundaries stable and known? | New or shifting domain | Well-understood domain (second version) | Event storming, months of co-change data |
| Release cadence | Do parts need very different release rhythms? | Same cadence | Hourly vs quarterly parts | Deploy log per module |
| Scaling asymmetry | Does one part need different scale or hardware? | Uniform load | 10x+ hot spot, GPU, special datastore | Profiling, APM per route |
| Fault isolation | Must a failure in X never touch Y? | Bulkheads and worker processes suffice | Separate runtime required | Incident log |
| Regulatory isolation | Does an auditor need a smaller scope? | No special scope | PCI DSS cardholder data, health data, residency | Compliance requirements |
| Technology heterogeneity (tech heterogeneity) | Does a part need another language or runtime? | One stack | ML in Python, a JVM-only library | Library constraints |
| Platform maturity | Can we provision, deploy, monitor and trace a new service in a day? | No | Yes (Fowler's prerequisites) | Time-to-first-deploy of a new service |
| Observability maturity | Distributed tracing, per-service SLOs, log correlation? | Not yet | In place | Trace coverage % |
| CI maturity | Pipeline per service, contract tests, fast builds? | One pipeline | Templates and contract testing | Pipeline duration |
| Data coupling | Do parts need one transaction or joins? | Strong (integrator) | Weak; events suffice | Schema foreign keys, queries crossing modules |
| Budget | Can we pay infra + platform people? | Tight | Funded platform team | Cost model |
| Time to market | Is the next 6 months about product discovery? | Yes | No, scale is the problem | Roadmap |
Cost model: the microservice premium item by item
The curves are a picture of the argument, not measured data: the tangled monolith is cheapest for one team and gets expensive with contention; the modular monolith rises slowly; microservices start with a fixed premium and stay flatter. No source we read gives crossover numbers; yours come from your own measurements.
| Cost item | Monolith | Modular monolith | Microservices | Why it differs |
|---|---|---|---|---|
| Infrastructure | 1 app tier + DB | Same | N runtimes, N databases, broker, gateway, mesh/sidecars | Each service has fixed overhead (min replicas, memory baseline) |
| Operations | One deploy, one set of alerts | Same + module-level metrics | Per-service dashboards, alerts, on-call, upgrades | Fowler: "You need a mature operations team" |
| Latency | Function calls | Same | Network hop per call, serialization, retries | Google C1 "It hurts performance" |
| Consistency | ACID transaction | ACID (modules can share a transaction) | Sagas, outbox, eventual consistency | Fowler's trade-offs: "everyone has to manage eventual consistency" |
| Testing | Unit + integration in one process | + fitness tests, module fakes | + contract tests, network fault tests, end-to-end environments | Google C3: local end-to-end tests become "an engineering feat" |
| API change | Rename in IDE | Change module API in one PR | Versioned API, expand/contract across releases | Google C4 "It freezes APIs" |
| Cognitive load | Whole codebase | One module + its API neighbours | One service + its platform | Team Topologies |
| Debugging | Stack trace | Stack trace | Distributed trace across services | Need trace propagation |
| Security surface | One perimeter | One perimeter | Service-to-service auth (mTLS, tokens) | More network edges |
| Data | One DB, joins | One DB, schema per module | DB per service, data duplication, CDC | Data Ownership |
Timelines: startup → scale-up → enterprise
Stage Engineers Typical form Move when
1 Pre-PMF startup 1-8 Monolith with module folders Never split before product-market fit
2 Early growth 8-30 Modular monolith, enforced boundaries Teams > 3: add CODEOWNERS, merge queue, module CI
3 Scale-up 30-150 Modular core + 1-5 extracted services A split signal is measured and a platform exists
4 Enterprise 150+ Several modular cores or many services Per domain: each line of business decides again
5 Any stage - Merge back Merge signals: nanoservices, chatty graph, ops burden| Stage | Main goal | Main risk | What to build now | What to postpone |
|---|---|---|---|---|
| Pre-PMF startup | Learning speed | Building the wrong product | One deployable, CI, error tracking | Kubernetes, service mesh, event bus |
| Early growth | Keep speed as the team triples | Tangled code | Module APIs, schema per module, fitness tests | Extracting services |
| Scale-up | Team independence, one or two hot spots | Platform debt, premature splits | Platform team, tracing, templates; extract the hot spot | Splitting everything |
| Enterprise | Governance, compliance, many products | Distributed monolith across departments | Domain-level ownership, API standards, isolation where regulated | One mandated style for all |
Mechanics
What changes in the code when the boundary moves
| Aspect | 1. In-process call | 2. Module interface + event | 3. HTTP/gRPC client |
|---|---|---|---|
| Call | s.stock[sku] -= qty | inv.Reserve(ctx, orderID, sku, qty) | Same call; implemented by inventoryclient.Client |
| Failure modes | Error or panic | Error from the module | Timeout, connection refused, 5xx, partial success (work done, reply lost) |
| Latency | Nanoseconds | Nanoseconds | Milliseconds plus retries |
| Transaction | One | Can still be one | None across services; saga or outbox |
| Idempotency | Not needed | Cheap and recommended | Required (Idempotency-Key) |
| Events | Not needed | In-process bus, synchronous | Broker, at-least-once, consumers deduplicate |
| Tests | One integration test | Module fakes + fitness test | + HTTP fakes, retry and timeout tests, contract tests |
| Deploy | One | One | Two, with version compatibility |
Measuring the signals in SQL
The split/merge signals are data. A PostgreSQL schema fed by your CI and Git hooks:
-- One row per production deployment and per changed file in each commit.
CREATE TABLE deployments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
service text NOT NULL, -- 'monolith' or a service name
commit_sha text NOT NULL,
committed_at timestamptz NOT NULL,
deployed_at timestamptz NOT NULL,
failed boolean NOT NULL DEFAULT false -- needed immediate intervention
);
CREATE TABLE commit_files (
commit_sha text NOT NULL,
author_team text NOT NULL,
module text NOT NULL, -- derived from path: app/Modules/<X>/...
PRIMARY KEY (commit_sha, module)
);
-- DORA: change lead time (median), deployment frequency, change fail rate per service, last 90 days.
SELECT service,
percentile_cont(0.5) WITHIN GROUP (ORDER BY deployed_at - committed_at) AS median_lead_time,
count(*) / 13.0 AS deploys_per_week,
round(100.0 * avg(failed::int), 1) AS change_fail_rate_pct
FROM deployments
WHERE deployed_at > now() - interval '90 days'
GROUP BY service;
-- Team coupling: share of each team's commits that touch exactly one module, and which one.
WITH per_commit AS (
SELECT commit_sha, author_team, count(*) AS modules, min(module) AS only_module
FROM commit_files GROUP BY commit_sha, author_team
)
SELECT author_team, only_module,
round(100.0 * count(*) / sum(count(*)) OVER (PARTITION BY author_team), 1) AS pct_of_team_commits
FROM per_commit
WHERE modules = 1
GROUP BY author_team, only_module
ORDER BY author_team, pct_of_team_commits DESC;
-- Merge signal: pairs of modules or services that change together most often.
SELECT a.module AS m1, b.module AS m2, count(*) AS co_changes
FROM commit_files a JOIN commit_files b
ON a.commit_sha = b.commit_sha AND a.module < b.module
GROUP BY 1, 2
ORDER BY co_changes DESC
LIMIT 10;The same queries run on MySQL 8.0 with small changes (percentile_cont does not exist there; use a window with ROW_NUMBER() to find the median, and TIMESTAMPDIFF for the interval).
Error messages you will actually see
| Where | Message | What it tells you about the decision |
|---|---|---|
Go net/http client | context deadline exceeded | The timeout budget of a remote call was spent; in-process this never happens |
Go net/http client | dial tcp ...: connect: connection refused | The other service is down or not ready; retry with backoff |
| Go compiler | use of internal package ... not allowed | The module boundary held (Go 1.4 internal/ rule) |
| Go fitness test (this page) | ordering/ordering.go imports .../modular/inventory/internal (only inventory's public API and events are allowed) | Someone reached into another module |
| Laravel HTTP client | Illuminate\Http\Client\ConnectionException | Connection failed; thrown after the last retry even with throw: false |
| Laravel HTTP client | Illuminate\Http\Client\RequestException | A 4xx/5xx after ->throw() |
| HTTP | 409 Conflict (this page's contract) | Business error, do not retry; maps to OutOfStock |
| HTTP | 503 Service Unavailable, 502 Bad Gateway | Transient; retry with the same idempotency key |
| Pest | failed arch() expectation naming the class and the forbidden namespace (wording varies by Pest version; not verified here) | Boundary violated in the modular monolith |
Go
One feature, place an order and reserve stock, in the three forms. The code is one Go module (docs/snippets/architecture/monolith-vs-microservices-vs-modular/go); gofmt -l ., go vet ./... and go test ./... pass, and go run ./cmd/shop runs it.
go/
├── go.mod module academy/monolith-vs-microservices-vs-modular
├── monolith/ FORM 1
│ ├── shop.go PlaceOrder decrements stock inline
│ └── shop_test.go one test, real state
├── modular/ FORM 2
│ ├── arch_test.go fitness test: ordering imports only public APIs
│ ├── events/bus.go in-process event bus
│ ├── inventory/inventory.go module API (inventory.API) + in-process Module
│ └── ordering/
│ ├── ordering.go depends on inventory.API, publishes OrderPlaced
│ └── ordering_test.go fake inventory at the interface
├── micro/ FORM 3
│ ├── inventorysvc/handler.go the same Module behind POST /reservations
│ └── inventoryclient/
│ ├── client.go inventory.API over HTTP: timeout, retries, Idempotency-Key
│ └── client_test.go httptest: 503 then success, 409 mapping, deadline
├── cmd/shop/main.go composition root: INVENTORY_URL picks the form
└── scorecard/ weighted scorecard used in "Choosing"Form 1: monolith, in-process call
Ordering reaches into stock directly. Correct, fast and fine for one team; nothing marks where inventory ends.
// Package monolith shows form 1: one package, one data store, one transaction.
// Ordering touches stock directly; nothing stops any other code from doing the same.
package monolith
import (
"context"
"errors"
"fmt"
"sync"
)
// ErrOutOfStock is returned when the requested quantity is not available.
var ErrOutOfStock = errors.New("out of stock")
// Order is the result of a successful checkout.
type Order struct {
ID string
SKU string
Qty int
}
// Shop stands in for one process with one database. The mutex plays the role of
// the single database transaction (BEGIN ... SELECT ... FOR UPDATE ... COMMIT).
type Shop struct {
mu sync.Mutex
stock map[string]int
orders []Order
nextID int
}
// New returns a shop with the given stock levels.
func New(stock map[string]int) *Shop {
return &Shop{stock: stock}
}
// PlaceOrder checks stock, decrements it and records the order atomically.
// The call to the "inventory" logic is a plain in-process statement.
func (s *Shop) PlaceOrder(ctx context.Context, sku string, qty int) (Order, error) {
if err := ctx.Err(); err != nil {
return Order{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.stock[sku] < qty {
return Order{}, fmt.Errorf("place order %s x%d: %w", sku, qty, ErrOutOfStock)
}
s.stock[sku] -= qty // inventory logic inlined: no boundary at all
s.nextID++
o := Order{ID: fmt.Sprintf("ord-%d", s.nextID), SKU: sku, Qty: qty}
s.orders = append(s.orders, o)
return o, nil
}
// Stock reports the current level of one SKU.
func (s *Shop) Stock(sku string) int {
s.mu.Lock()
defer s.mu.Unlock()
return s.stock[sku]
}package monolith
import (
"context"
"errors"
"testing"
)
// In the monolith one test exercises the whole path with real state; no fakes are needed.
func TestPlaceOrder(t *testing.T) {
s := New(map[string]int{"book": 2})
if _, err := s.PlaceOrder(context.Background(), "book", 2); err != nil {
t.Fatalf("first order: %v", err)
}
if got := s.Stock("book"); got != 0 {
t.Fatalf("stock = %d, want 0", got)
}
_, err := s.PlaceOrder(context.Background(), "book", 1)
if !errors.Is(err, ErrOutOfStock) {
t.Fatalf("second order err = %v, want ErrOutOfStock", err)
}
}Form 2: modular monolith, module interface + event
Inventory publishes inventory.API; its state is unexported. Reserve is idempotent per order id already, which costs nothing here and becomes essential in form 3.
// Package inventory is a module of the modular monolith. Its exported API is the
// only thing other modules may use; the stock map and the reservation log are private.
package inventory
import (
"context"
"errors"
"fmt"
"sync"
)
// ErrOutOfStock is part of the module's public contract.
var ErrOutOfStock = errors.New("inventory: out of stock")
// Reservation is the data the module hands out. It is a value, not a pointer into our state.
type Reservation struct {
ID string `json:"id"`
OrderID string `json:"order_id"`
SKU string `json:"sku"`
Qty int `json:"qty"`
}
// API is the module interface. The in-process Module and the remote HTTP client
// (package micro/inventoryclient) both satisfy it, so callers never change.
type API interface {
Reserve(ctx context.Context, orderID, sku string, qty int) (Reservation, error)
}
// Module is the in-process implementation.
type Module struct {
mu sync.Mutex
levels map[string]int
byOrder map[string]Reservation // idempotency: one reservation per order id
sequence int
}
// New builds the module with initial stock levels.
func New(levels map[string]int) *Module {
return &Module{levels: levels, byOrder: map[string]Reservation{}}
}
// Reserve is idempotent per orderID: calling it twice returns the first reservation.
// That property costs nothing in-process and becomes essential once retries cross a network.
func (m *Module) Reserve(ctx context.Context, orderID, sku string, qty int) (Reservation, error) {
if err := ctx.Err(); err != nil {
return Reservation{}, err
}
m.mu.Lock()
defer m.mu.Unlock()
if r, ok := m.byOrder[orderID]; ok {
return r, nil
}
if m.levels[sku] < qty {
return Reservation{}, fmt.Errorf("reserve %s x%d: %w", sku, qty, ErrOutOfStock)
}
m.levels[sku] -= qty
m.sequence++
r := Reservation{ID: fmt.Sprintf("res-%d", m.sequence), OrderID: orderID, SKU: sku, Qty: qty}
m.byOrder[orderID] = r
return r, nil
}
// Level reports the stock level of one SKU (used by tests and the admin screen).
func (m *Module) Level(sku string) int {
m.mu.Lock()
defer m.mu.Unlock()
return m.levels[sku]
}Ordering depends on the interface and announces a fact through a tiny in-process bus:
// Package events is a tiny in-process, synchronous event bus. Modules publish facts;
// other modules subscribe without the publisher knowing who listens.
package events
import (
"context"
"sync"
)
// Handler reacts to one event value.
type Handler func(ctx context.Context, event any) error
// Bus maps an event name to its handlers.
type Bus struct {
mu sync.RWMutex
handlers map[string][]Handler
}
// NewBus returns an empty bus.
func NewBus() *Bus { return &Bus{handlers: map[string][]Handler{}} }
// Subscribe registers a handler for an event name.
func (b *Bus) Subscribe(name string, h Handler) {
b.mu.Lock()
defer b.mu.Unlock()
b.handlers[name] = append(b.handlers[name], h)
}
// Publish calls every handler in order and returns the first error.
// In-process delivery is exactly-once and synchronous; a broker would make it
// at-least-once and asynchronous, which is the change consumers must be ready for.
func (b *Bus) Publish(ctx context.Context, name string, event any) error {
b.mu.RLock()
hs := append([]Handler(nil), b.handlers[name]...)
b.mu.RUnlock()
for _, h := range hs {
if err := h(ctx, event); err != nil {
return err
}
}
return nil
}// Package ordering depends on inventory.API (the module interface) and announces
// OrderPlaced through a publisher. It never touches inventory's state.
package ordering
import (
"context"
"fmt"
"academy/monolith-vs-microservices-vs-modular/modular/inventory"
)
// EventOrderPlaced is the event name other modules subscribe to.
const EventOrderPlaced = "ordering.order_placed"
// OrderPlaced is the fact published after a successful checkout.
type OrderPlaced struct {
OrderID string
SKU string
Qty int
ReservationID string
}
// Publisher is what ordering needs from the event bus.
type Publisher interface {
Publish(ctx context.Context, name string, event any) error
}
// Service is the ordering module's use case.
type Service struct {
Inventory inventory.API
Events Publisher
NewID func() string
}
// PlaceOrder reserves stock through the module interface, then publishes a fact.
func (s *Service) PlaceOrder(ctx context.Context, sku string, qty int) (OrderPlaced, error) {
orderID := s.NewID()
res, err := s.Inventory.Reserve(ctx, orderID, sku, qty)
if err != nil {
return OrderPlaced{}, fmt.Errorf("place order %s: %w", orderID, err)
}
ev := OrderPlaced{OrderID: orderID, SKU: sku, Qty: qty, ReservationID: res.ID}
if err := s.Events.Publish(ctx, EventOrderPlaced, ev); err != nil {
return OrderPlaced{}, fmt.Errorf("publish %s: %w", EventOrderPlaced, err)
}
return ev, nil
}Tests that change: ordering is tested with a fake at the interface, and a fitness test keeps the boundary honest.
package ordering
import (
"context"
"errors"
"testing"
"academy/monolith-vs-microservices-vs-modular/modular/events"
"academy/monolith-vs-microservices-vs-modular/modular/inventory"
)
// fakeInventory replaces the other module at its interface: the test that changed
// from the monolith version. Ordering is tested alone, in microseconds.
type fakeInventory struct{ err error }
func (f fakeInventory) Reserve(_ context.Context, orderID, sku string, qty int) (inventory.Reservation, error) {
if f.err != nil {
return inventory.Reservation{}, f.err
}
return inventory.Reservation{ID: "res-fake", OrderID: orderID, SKU: sku, Qty: qty}, nil
}
func TestPlaceOrderPublishesEvent(t *testing.T) {
bus := events.NewBus()
var got []OrderPlaced
bus.Subscribe(EventOrderPlaced, func(_ context.Context, e any) error {
got = append(got, e.(OrderPlaced))
return nil
})
svc := &Service{Inventory: fakeInventory{}, Events: bus, NewID: func() string { return "ord-1" }}
if _, err := svc.PlaceOrder(context.Background(), "book", 1); err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0].ReservationID != "res-fake" {
t.Fatalf("events = %+v", got)
}
}
func TestPlaceOrderOutOfStockPublishesNothing(t *testing.T) {
bus := events.NewBus()
published := 0
bus.Subscribe(EventOrderPlaced, func(context.Context, any) error { published++; return nil })
svc := &Service{Inventory: fakeInventory{err: inventory.ErrOutOfStock}, Events: bus, NewID: func() string { return "ord-2" }}
_, err := svc.PlaceOrder(context.Background(), "book", 9)
if !errors.Is(err, inventory.ErrOutOfStock) || published != 0 {
t.Fatalf("err = %v, published = %d", err, published)
}
}
// The real module still gets one integration test, wired exactly as main would.
func TestPlaceOrderWithRealModule(t *testing.T) {
inv := inventory.New(map[string]int{"book": 1})
svc := &Service{Inventory: inv, Events: events.NewBus(), NewID: func() string { return "ord-3" }}
if _, err := svc.PlaceOrder(context.Background(), "book", 1); err != nil {
t.Fatal(err)
}
if inv.Level("book") != 0 {
t.Fatalf("level = %d", inv.Level("book"))
}
}// Package modular_test holds a fitness test: ordering may import inventory's public
// package and events, nothing else from the sibling modules.
package modular_test
import (
"go/parser"
"go/token"
"path/filepath"
"strconv"
"strings"
"testing"
)
const root = "academy/monolith-vs-microservices-vs-modular/"
var allowed = map[string]bool{
root + "modular/inventory": true,
root + "modular/events": true,
}
func TestOrderingImportsOnlyPublicAPIs(t *testing.T) {
files, err := filepath.Glob("ordering/*.go")
if err != nil {
t.Fatal(err)
}
fset := token.NewFileSet()
for _, f := range files {
parsed, err := parser.ParseFile(fset, f, nil, parser.ImportsOnly)
if err != nil {
t.Fatal(err)
}
for _, imp := range parsed.Imports {
path, _ := strconv.Unquote(imp.Path.Value)
if strings.HasPrefix(path, root) && !allowed[path] {
t.Errorf("%s imports %s (only inventory's public API and events are allowed)", f, path)
}
}
}
}Form 3: microservices, HTTP client with retries
The inventory module is unchanged; a handler exposes it:
// Package inventorysvc exposes the unchanged inventory module over HTTP.
// The module code moved; its logic did not.
package inventorysvc
import (
"encoding/json"
"errors"
"net/http"
"academy/monolith-vs-microservices-vs-modular/modular/inventory"
)
// Handler serves POST /reservations.
func Handler(inv inventory.API) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /reservations", func(w http.ResponseWriter, r *http.Request) {
var in struct {
OrderID string `json:"order_id"`
SKU string `json:"sku"`
Qty int `json:"qty"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Qty <= 0 {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if key := r.Header.Get("Idempotency-Key"); key != "" && key != in.OrderID {
http.Error(w, "Idempotency-Key must equal order_id", http.StatusUnprocessableEntity)
return
}
res, err := inv.Reserve(r.Context(), in.OrderID, in.SKU, in.Qty)
switch {
case errors.Is(err, inventory.ErrOutOfStock):
http.Error(w, err.Error(), http.StatusConflict)
return
case err != nil:
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(res)
})
return mux
}The client implements the same inventory.API. What is new is everything the network forces: a deadline, retries only on transport errors and 5xx, exponential backoff that respects ctx, a request body rebuilt per attempt, an Idempotency-Key, and mapping 409 back to inventory.ErrOutOfStock so callers see the same contract.
// Package inventoryclient implements inventory.API over HTTP. Ordering's code does not
// change when the module moves out of process; only the wiring in main does.
package inventoryclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
"academy/monolith-vs-microservices-vs-modular/modular/inventory"
)
// Client calls the inventory service. Zero values are replaced by safe defaults.
type Client struct {
BaseURL string
HTTP *http.Client // set Timeout here: every remote call needs a deadline
MaxAttempts int // total attempts including the first (default 3)
Backoff time.Duration // first wait; doubles per attempt (default 100ms)
}
var _ inventory.API = (*Client)(nil)
type reserveRequest struct {
OrderID string `json:"order_id"`
SKU string `json:"sku"`
Qty int `json:"qty"`
}
// errRetryable marks failures worth another attempt: transport errors and 5xx.
var errRetryable = errors.New("retryable")
// Reserve sends POST /reservations with an Idempotency-Key equal to the order id,
// so a retry after a lost response cannot reserve stock twice.
func (c *Client) Reserve(ctx context.Context, orderID, sku string, qty int) (inventory.Reservation, error) {
attempts, wait := c.MaxAttempts, c.Backoff
if attempts <= 0 {
attempts = 3
}
if wait <= 0 {
wait = 100 * time.Millisecond
}
payload, err := json.Marshal(reserveRequest{OrderID: orderID, SKU: sku, Qty: qty})
if err != nil {
return inventory.Reservation{}, err
}
var lastErr error
for attempt := 1; attempt <= attempts; attempt++ {
res, err := c.once(ctx, orderID, payload)
if err == nil || !errors.Is(err, errRetryable) {
return res, err
}
lastErr = err
if attempt == attempts {
break
}
select {
case <-ctx.Done():
return inventory.Reservation{}, ctx.Err()
case <-time.After(wait):
wait *= 2
}
}
return inventory.Reservation{}, fmt.Errorf("inventory unavailable after %d attempts: %w", attempts, lastErr)
}
func (c *Client) once(ctx context.Context, key string, payload []byte) (inventory.Reservation, error) {
// The body reader is rebuilt on every attempt; a consumed reader would send an empty body.
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/reservations", bytes.NewReader(payload))
if err != nil {
return inventory.Reservation{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", key)
hc := c.HTTP
if hc == nil {
hc = &http.Client{Timeout: 2 * time.Second}
}
resp, err := hc.Do(req)
if err != nil {
if ctx.Err() != nil {
return inventory.Reservation{}, ctx.Err()
}
return inventory.Reservation{}, fmt.Errorf("%w: %v", errRetryable, err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusOK:
var r inventory.Reservation
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
return inventory.Reservation{}, fmt.Errorf("decode reservation: %w", err)
}
return r, nil
case resp.StatusCode == http.StatusConflict:
return inventory.Reservation{}, inventory.ErrOutOfStock // same contract as in-process
case resp.StatusCode >= 500:
return inventory.Reservation{}, fmt.Errorf("%w: status %d", errRetryable, resp.StatusCode)
default:
return inventory.Reservation{}, fmt.Errorf("inventory: unexpected status %d", resp.StatusCode)
}
}Tests that exist only in form 3:
package inventoryclient
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"academy/monolith-vs-microservices-vs-modular/micro/inventorysvc"
"academy/monolith-vs-microservices-vs-modular/modular/inventory"
)
// The tests that appear only in the microservice form: transient failure, idempotent
// retry, contract mapping (409 -> ErrOutOfStock) and deadlines.
func TestSameOrderTwiceReservesOnce(t *testing.T) {
// A caller that lost the first response repeats the call with the same order id.
inv := inventory.New(map[string]int{"book": 5})
srv := httptest.NewServer(inventorysvc.Handler(inv))
defer srv.Close()
c := &Client{BaseURL: srv.URL, HTTP: srv.Client(), Backoff: time.Millisecond}
for i := 0; i < 2; i++ {
if _, err := c.Reserve(context.Background(), "ord-1", "book", 2); err != nil {
t.Fatal(err)
}
}
if got := inv.Level("book"); got != 3 {
t.Fatalf("level = %d, want 3 (one reservation despite two calls)", got)
}
}
func TestRetriesOn503ThenSucceeds(t *testing.T) {
inv := inventory.New(map[string]int{"book": 1})
real := inventorysvc.Handler(inv)
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if calls.Add(1) == 1 {
http.Error(w, "overloaded", http.StatusServiceUnavailable)
return
}
real.ServeHTTP(w, r)
}))
defer srv.Close()
c := &Client{BaseURL: srv.URL, HTTP: srv.Client(), Backoff: time.Millisecond}
res, err := c.Reserve(context.Background(), "ord-2", "book", 1)
if err != nil || res.OrderID != "ord-2" || calls.Load() != 2 {
t.Fatalf("res = %+v, err = %v, calls = %d", res, err, calls.Load())
}
}
func TestConflictMapsToSameError(t *testing.T) {
srv := httptest.NewServer(inventorysvc.Handler(inventory.New(map[string]int{})))
defer srv.Close()
c := &Client{BaseURL: srv.URL, HTTP: srv.Client()}
_, err := c.Reserve(context.Background(), "ord-3", "book", 1)
if !errors.Is(err, inventory.ErrOutOfStock) {
t.Fatalf("err = %v, want inventory.ErrOutOfStock", err)
}
}
func TestDeadlineStopsRetries(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusBadGateway)
}))
defer srv.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
c := &Client{BaseURL: srv.URL, HTTP: srv.Client(), MaxAttempts: 10, Backoff: 50 * time.Millisecond}
if _, err := c.Reserve(ctx, "ord-4", "book", 1); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v, want deadline exceeded", err)
}
}The composition root is the only file that knows which form runs:
// Command shop is the composition root. The same ordering code runs against the
// in-process module (modular monolith) or the remote service (microservices);
// INVENTORY_URL is the only switch.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"sync/atomic"
"time"
"academy/monolith-vs-microservices-vs-modular/micro/inventoryclient"
"academy/monolith-vs-microservices-vs-modular/modular/events"
"academy/monolith-vs-microservices-vs-modular/modular/inventory"
"academy/monolith-vs-microservices-vs-modular/modular/ordering"
)
func main() {
var inv inventory.API
if url := os.Getenv("INVENTORY_URL"); url != "" {
inv = &inventoryclient.Client{
BaseURL: url,
HTTP: &http.Client{Timeout: 800 * time.Millisecond},
MaxAttempts: 3,
Backoff: 100 * time.Millisecond,
}
} else {
inv = inventory.New(map[string]int{"book": 10})
}
bus := events.NewBus()
bus.Subscribe(ordering.EventOrderPlaced, func(_ context.Context, e any) error {
log.Printf("notifications: send confirmation for %+v", e)
return nil
})
var seq atomic.Int64
svc := &ordering.Service{
Inventory: inv,
Events: bus,
NewID: func() string { return fmt.Sprintf("ord-%d", seq.Add(1)) },
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
placed, err := svc.PlaceOrder(ctx, "book", 1)
if err != nil {
log.Fatal(err)
}
fmt.Printf("placed %s (reservation %s)\n", placed.OrderID, placed.ReservationID)
}The Go angle
| Go feature | What it does for this decision |
|---|---|
Packages and internal/ | Module boundaries the compiler enforces; the cheapest modular monolith tooling there is |
| Implicit interfaces | inventory.API is satisfied by *Module and *Client without either importing the other |
context.Context | Deadlines and cancellation flow across in-process and remote calls the same way |
net/http + httptest | A remote client and its failure tests with no dependencies |
| One static binary | Cheap to run the same binary in several roles (API, worker) before splitting code |
gRPC (google.golang.org/grpc) | The common choice when form 3 needs typed contracts and streaming (gRPC in Go) |
Laravel
The same feature in Laravel 13 (PHP 8.4). Files are under docs/snippets/architecture/monolith-vs-microservices-vs-modular/php; PHP is not installed on the authoring machine, so the code was reviewed against the Laravel 13 HTTP client, events and Pest architecture-testing docs, not run.
php/
├── monolith/app/Actions/PlaceOrder.php FORM 1: DB::transaction + lockForUpdate
├── monolith/tests/PlaceOrderTest.php
├── modular/app/Modules/Inventory/Api/InventoryApi.php FORM 2: the module contract
├── modular/app/Modules/Inventory/Api/Reservation.php
├── modular/app/Modules/Inventory/Api/OutOfStock.php
├── modular/app/Modules/Inventory/Internal/DatabaseInventory.php
├── modular/app/Modules/Inventory/InventoryServiceProvider.php
├── modular/app/Modules/Ordering/PlaceOrder.php
├── modular/app/Modules/Ordering/Events/OrderPlaced.php ShouldDispatchAfterCommit
├── modular/tests/PlaceOrderTest.php fake at the contract, Event::fake
├── modular/tests/ArchTest.php Pest arch(): fitness functions
├── micro/app/Modules/Inventory/Http/HttpInventoryApi.php FORM 3: Http::retry, timeouts, Idempotency-Key
├── micro/app/Modules/Inventory/InventoryServiceProvider.php binding switches on INVENTORY_URL
└── micro/tests/HttpInventoryApiTest.php Http::fake, Http::sequence, assertSentForm 1: monolith
<?php
namespace App\Actions;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Support\Facades\DB;
// Form 1: one Laravel app, one database, one transaction.
// Ordering reads and writes the products table directly.
final class PlaceOrder
{
public function handle(int $customerId, int $productId, int $qty): Order
{
return DB::transaction(function () use ($customerId, $productId, $qty): Order {
$product = Product::query()->lockForUpdate()->findOrFail($productId);
if ($product->stock < $qty) {
throw new \DomainException("Product {$productId} is out of stock.");
}
$product->decrement('stock', $qty);
return Order::create([
'customer_id' => $customerId,
'product_id' => $productId,
'qty' => $qty,
]);
});
}
}<?php
use App\Actions\PlaceOrder;
use App\Models\Product;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
// One feature test with a real database covers the whole path.
test('placing an order decrements stock in the same transaction', function () {
$product = Product::factory()->create(['stock' => 2]);
app(PlaceOrder::class)->handle(customerId: 1, productId: $product->id, qty: 2);
expect($product->fresh()->stock)->toBe(0);
expect(fn () => app(PlaceOrder::class)->handle(1, $product->id, 1))
->toThrow(DomainException::class);
});Form 2: modular monolith
The contract, a value object and the module's exception:
<?php
namespace App\Modules\Inventory\Api;
// The module interface. Ordering depends on this and nothing else from Inventory.
interface InventoryApi
{
/**
* Idempotent per $orderId: a second call returns the first reservation.
*
* @throws OutOfStock
*/
public function reserve(string $orderId, string $sku, int $qty): Reservation;
}<?php
namespace App\Modules\Inventory\Api;
final readonly class Reservation
{
public function __construct(
public string $id,
public string $orderId,
public string $sku,
public int $qty,
) {}
}<?php
namespace App\Modules\Inventory\Api;
final class OutOfStock extends \DomainException {}The private implementation and the module's only wiring:
<?php
namespace App\Modules\Inventory\Internal;
use App\Modules\Inventory\Api\InventoryApi;
use App\Modules\Inventory\Api\OutOfStock;
use App\Modules\Inventory\Api\Reservation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
// Private to the module: only this class touches inventory.* tables.
final class DatabaseInventory implements InventoryApi
{
public function reserve(string $orderId, string $sku, int $qty): Reservation
{
return DB::transaction(function () use ($orderId, $sku, $qty): Reservation {
$existing = DB::table('inventory_reservations')->where('order_id', $orderId)->first();
if ($existing !== null) {
return new Reservation($existing->id, $orderId, $existing->sku, $existing->qty);
}
$level = DB::table('inventory_stock')->where('sku', $sku)->lockForUpdate()->value('level');
if ($level === null || $level < $qty) {
throw new OutOfStock("SKU {$sku} has insufficient stock.");
}
DB::table('inventory_stock')->where('sku', $sku)->decrement('level', $qty);
$id = (string) Str::ulid();
DB::table('inventory_reservations')->insert([
'id' => $id, 'order_id' => $orderId, 'sku' => $sku, 'qty' => $qty, 'created_at' => now(),
]);
return new Reservation($id, $orderId, $sku, $qty);
});
}
}<?php
namespace App\Modules\Inventory;
use App\Modules\Inventory\Api\InventoryApi;
use App\Modules\Inventory\Internal\DatabaseInventory;
use Illuminate\Support\ServiceProvider;
// Listed in bootstrap/providers.php. The binding is the module's only wiring.
final class InventoryServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind(InventoryApi::class, DatabaseInventory::class);
}
}Ordering uses the contract and dispatches an event that waits for the commit (Laravel 13 docs: ShouldDispatchAfterCommit "instructs Laravel to not dispatch the event until the current database transaction is committed"):
<?php
namespace App\Modules\Ordering\Events;
use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
use Illuminate\Foundation\Events\Dispatchable;
// Published by Ordering; Notifications and Analytics listen. Dispatched only after
// the surrounding transaction commits, so listeners never see a rolled-back order.
final class OrderPlaced implements ShouldDispatchAfterCommit
{
use Dispatchable;
public function __construct(
public readonly string $orderId,
public readonly string $sku,
public readonly int $qty,
public readonly string $reservationId,
) {}
}<?php
namespace App\Modules\Ordering;
use App\Modules\Inventory\Api\InventoryApi;
use App\Modules\Ordering\Events\OrderPlaced;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
// Form 2: Ordering calls Inventory through its interface and announces a fact.
final class PlaceOrder
{
public function __construct(private readonly InventoryApi $inventory) {}
public function handle(int $customerId, string $sku, int $qty): string
{
$orderId = (string) Str::ulid();
// One process, one database: the transaction still spans both modules.
// That is the convenience you give up in form 3.
DB::transaction(function () use ($orderId, $customerId, $sku, $qty): void {
$reservation = $this->inventory->reserve($orderId, $sku, $qty);
DB::table('ordering_orders')->insert([
'id' => $orderId, 'customer_id' => $customerId, 'sku' => $sku,
'qty' => $qty, 'reservation_id' => $reservation->id, 'created_at' => now(),
]);
OrderPlaced::dispatch($orderId, $sku, $qty, $reservation->id);
});
return $orderId;
}
}Tests that change: the contract is faked in the container, the event is asserted, and Pest guards the boundary.
<?php
use App\Modules\Inventory\Api\InventoryApi;
use App\Modules\Inventory\Api\OutOfStock;
use App\Modules\Inventory\Api\Reservation;
use App\Modules\Ordering\Events\OrderPlaced;
use App\Modules\Ordering\PlaceOrder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
uses(RefreshDatabase::class);
// What changed from form 1: Inventory is replaced at its interface, and the event is asserted.
test('ordering reserves through the interface and publishes OrderPlaced', function () {
Event::fake([OrderPlaced::class]);
$this->app->instance(InventoryApi::class, new class implements InventoryApi {
public function reserve(string $orderId, string $sku, int $qty): Reservation
{
return new Reservation('res-fake', $orderId, $sku, $qty);
}
});
$orderId = app(PlaceOrder::class)->handle(customerId: 7, sku: 'book', qty: 1);
Event::assertDispatched(OrderPlaced::class, fn (OrderPlaced $e) => $e->orderId === $orderId);
});
test('out of stock publishes nothing', function () {
Event::fake([OrderPlaced::class]);
$this->app->instance(InventoryApi::class, new class implements InventoryApi {
public function reserve(string $orderId, string $sku, int $qty): Reservation
{
throw new OutOfStock('none left');
}
});
expect(fn () => app(PlaceOrder::class)->handle(7, 'book', 9))->toThrow(OutOfStock::class);
Event::assertNotDispatched(OrderPlaced::class);
});<?php
// Fitness functions (Pest arch testing): the boundary is enforced in CI, not hoped for.
arch('ordering uses only the inventory API')
->expect('App\Modules\Ordering')
->not->toUse('App\Modules\Inventory\Internal');
arch('inventory internals stay inside the module')
->expect('App\Modules\Inventory\Internal')
->toOnlyBeUsedIn('App\Modules\Inventory');Form 3: microservices
HttpInventoryApi implements the same InventoryApi. retry(3, ...) with a when callback retries only ConnectionException and 5xx; throw: false returns the last response, but the docs warn that "If all of the requests fail because of a connection issue, a Illuminate\Http\Client\ConnectionException will still be thrown even when the throw argument is set to false."
<?php
namespace App\Modules\Inventory\Http;
use App\Modules\Inventory\Api\InventoryApi;
use App\Modules\Inventory\Api\OutOfStock;
use App\Modules\Inventory\Api\Reservation;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
// Form 3: the same InventoryApi, implemented as an HTTP client of inventory-svc.
// Ordering's PlaceOrder class is unchanged; only the container binding differs.
final class HttpInventoryApi implements InventoryApi
{
public function __construct(private readonly string $baseUrl) {}
public function reserve(string $orderId, string $sku, int $qty): Reservation
{
$response = Http::baseUrl($this->baseUrl)
->acceptJson()
->withHeaders(['Idempotency-Key' => $orderId]) // safe to retry
->connectTimeout(1)
->timeout(2)
->retry(
3,
fn (int $attempt): int => 100 * (2 ** ($attempt - 1)),
fn (Throwable $e, PendingRequest $request): bool => $e instanceof ConnectionException
|| ($e instanceof RequestException && $e->response->serverError()),
throw: false,
)
->post('/reservations', ['order_id' => $orderId, 'sku' => $sku, 'qty' => $qty]);
// With throw: false a ConnectionException is still thrown after the last attempt.
if ($response->conflict()) {
throw new OutOfStock("SKU {$sku} has insufficient stock."); // same contract as in-process
}
$response->throw(); // any other 4xx/5xx becomes a RequestException
return new Reservation(
$response->json('id'),
$response->json('order_id'),
$response->json('sku'),
(int) $response->json('qty'),
);
}
}<?php
namespace App\Modules\Inventory;
use App\Modules\Inventory\Api\InventoryApi;
use App\Modules\Inventory\Http\HttpInventoryApi;
use App\Modules\Inventory\Internal\DatabaseInventory;
use Illuminate\Support\ServiceProvider;
// The only file that changes between form 2 and form 3 inside the ordering app.
// config/services.php: 'inventory' => ['url' => env('INVENTORY_URL')]
final class InventoryServiceProvider extends ServiceProvider
{
public function register(): void
{
$url = config('services.inventory.url');
if (is_string($url) && $url !== '') {
$this->app->bind(InventoryApi::class, fn () => new HttpInventoryApi($url));
return;
}
$this->app->bind(InventoryApi::class, DatabaseInventory::class);
}
}Tests that exist only in form 3:
<?php
use App\Modules\Inventory\Api\OutOfStock;
use App\Modules\Inventory\Http\HttpInventoryApi;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
// Tests that exist only in form 3: transient failures, retries, the idempotency
// header, and mapping HTTP status codes back onto the module contract.
beforeEach(fn () => Http::preventStrayRequests());
test('retries a 503 and sends the same idempotency key every time', function () {
Http::fake([
'inventory.test/*' => Http::sequence()
->pushStatus(503)
->push(['id' => 'res-1', 'order_id' => 'ord-1', 'sku' => 'book', 'qty' => 1], 201),
]);
$reservation = (new HttpInventoryApi('http://inventory.test'))->reserve('ord-1', 'book', 1);
expect($reservation->id)->toBe('res-1');
Http::assertSentCount(2);
Http::assertSent(fn (Request $r) => $r->hasHeader('Idempotency-Key', 'ord-1'));
});
test('409 maps to the same OutOfStock exception as the in-process module', function () {
Http::fake(['inventory.test/*' => Http::response(['error' => 'insufficient'], 409)]);
expect(fn () => (new HttpInventoryApi('http://inventory.test'))->reserve('ord-2', 'book', 9))
->toThrow(OutOfStock::class);
Http::assertSentCount(1); // 4xx is not retried
});The Laravel angle
| Laravel feature | Role in the decision |
|---|---|
Service container bind() | Swaps in-process and remote implementations of one contract |
Service providers in bootstrap/providers.php | One provider per module = the module's wiring |
DB::transaction, lockForUpdate() | The atomicity forms 1 and 2 keep for free |
Events + ShouldDispatchAfterCommit | In-process events that never announce a rolled-back write |
| Queued listeners, Horizon | Separate worker processes from one codebase (a physical split without a code split) |
HTTP client: timeout, connectTimeout, retry, Http::fake, Http::sequence, preventStrayRequests | Form 3 client and its tests |
Pest arch() | Fitness functions that keep a modular monolith modular |
| Octane | Long-lived workers; lowers per-request overhead before anyone blames the architecture |
Cost per form
Illustrative, for this one feature in a team of about 10; numbers are the author's estimates to show proportions, not measurements from a source.
| Item | 1. Monolith | 2. Modular monolith | 3. Microservices |
|---|---|---|---|
| Files touched to add the feature | 1-2 | 6-8 (API, impl, provider, event, tests) | 10-14 (+ client, handler, service config, pipeline) |
| Deployables | 1 | 1 | 2 (+ broker for events) |
| Pipelines | 1 | 1 | 2 |
| Databases | 1 | 1 (2 schemas) | 2 |
| Failure modes of the reserve call | 2 (ok, out of stock) | 2 | 5+ (ok, out of stock, timeout, refused, 5xx, lost reply) |
| Tests | 1 integration | 2 unit + 1 fitness + 1 integration | + 4 network tests + contract test |
| p50 added latency of reserve | ~0 | ~0 | network RTT + serialization per attempt |
| Consistency | ACID | ACID | Idempotent retries + outbox for events |
| Extra monthly infra | 0 | 0 | 1 more service's minimum replicas, DB, monitoring |
| Time to extract later | Days to weeks (find the boundary first) | Hours to days (swap the binding) | n/a |
Solving the classic problems
Moving from monolith to services, safely
Step Extracting inventory with strangler fig + branch by abstraction + parallel run
1 Abstraction introduce inventory.API in the monolith; route all callers through it (branch by abstraction)
2 Data give inventory its own schema; remove cross-schema joins and foreign keys
3 Build inventory-svc behind the same API; deploy dark
4 Parallel run call both; serve the monolith's answer; log differences (GitHub Scientist style)
5 Switch flag on for 1% -> 10% -> 100% of traffic (the strangler fig grows)
6 Contract expand/contract the API as callers move; remove the old path
7 Measure the goal metric from the ADR; stop extracting if it is met| Technique | How | Advantage | Cost / limitation |
|---|---|---|---|
| Strangler fig | Route a slice of functionality to the new system at the edge (proxy, gateway); grow it until the old part is gone | Always shippable; reversible per route | Two systems in production for a while (Strangler Fig) |
| Branch by abstraction | Fowler: a technique "for making a large-scale change to a software system in gradual way that allows you to release the system regularly while the change is still in-progress" | No long-lived branch; the interface becomes the seam | Needs a clean seam; step 1 is often the hardest |
| Parallel run | Run old and new, compare outputs, serve the old one | Finds behaviour differences on real traffic | Double load; side effects must be suppressed in the candidate |
| Expand and contract (parallel change) | Danilo Sato's three phases: "expand, migrate, and contract" | Backward-incompatible API change without coordinated deploys | More releases |
| Change data capture | Stream the monolith's table changes to the new service | Data sync without dual writes | Schema coupling to the old tables (CDC) |
| Decorating collaborator, UI composition | Newman's other chapter-3 patterns (headings only read) | More seams | Situational |
GitHub's Move Fast and Fix Things (Vicent Martí, December 2015) describes the parallel-run tool: "Scientist is a library for testing refactorings, rewrites and performance improvements in Ruby", declaring "the old code path as a control sample and the new code path as a candidate".
Consolidating services back
Step Merging users-svc, profiles-svc, preferences-svc into accounts (a modular monolith)
1 Pick the service everyone calls (profiles) as the host process
2 Inline move the other services' code in as modules; keep their HTTP API as a facade
3 Switch callers' clients to in-process bindings (the reverse of form 2 -> 3)
4 Data move tables into schemas of one database; replace reconciliation jobs with joins or one transaction
5 Retire old services' pipelines, dashboards, alerts, on-call rotations
6 Measure p99 latency, cost, pages per week (Segment and Prime Video both measured)| Technique | How | Advantage | Cost / limitation |
|---|---|---|---|
| Reverse strangler | Route old service endpoints to the merged process one by one | Reversible | Two hosts for a while |
| Keep the contract, change the binding | Callers keep the interface; implementation becomes in-process | No caller change | Network-era API shapes (pagination, DTOs) remain |
| Schema per former service | Merge databases but keep schemas and roles | Boundaries survive the merge | Joins across schemas tempt people; add fitness tests |
| Worker pool consolidation | One pool processes all event types (Segment) | Better utilisation, fewer pages | Fault isolation: one poison input can crash all; add bulkheads |
Keeping the modular monolith modular
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Compiler visibility | Go internal/, Java modules, .NET internal | Cannot be bypassed casually | Package granularity |
| Fitness tests | arch_test.go, Pest arch(), ArchUnit | Custom rules in CI | Must not be disabled under deadline |
| Static reference checkers | Shopify Packwerk ("analyze static constant references") | Works on Ruby where the language has no visibility | Rails-specific |
| Schema per module + DB roles | GRANT only on the module's schema | The database enforces data ownership | Migration of existing cross-module queries |
CODEOWNERS | Module owners review every change to their paths | Social enforcement | Bottleneck with few owners |
Hybrid topologies
Most real systems end up here, a hybrid topology: a modular core (a core monolith, kept modular) that holds the tightly related business capabilities, plus a few services for the parts with a measured reason. Fowler describes the gradual version: "start with a monolith and gradually peel off microservices at the edges. Such an approach can leave a substantial monolith at the heart of the microservices architecture".
| Candidate for a satellite service | Reason (driver) | Keep in the core when |
|---|---|---|
| Search | Different datastore and scale | Search is a simple SQL LIKE on a small table |
| Media transcoding, PDF/report generation | CPU/GPU, long jobs, blast radius | A queue worker from the same codebase isolates it enough |
| Payments, card data | PCI DSS scope reduction, security | A PSP's hosted fields keep card data out of your system anyway |
| ML inference | Python/GPU stack, hourly model releases | A hosted API is called from the core |
| Notifications (email, push) | Different reliability profile, vendor integrations | Laravel notifications + queues cover it |
| Public API for partners | Separate rate limits, versioning cadence | Same team, same cadence |
Bad reasons, and what to ask instead
| Bad reason | Why it is bad | Ask instead |
|---|---|---|
| Hype ("everyone does microservices") | Fowler's premium post opens with the "over-hyped" warning | Which metric will improve, by how much? |
| Résumé-driven development | Optimises the engineer's next job, not the product | Who will be on call for this in two years? |
| "Netflix does it" | Netflix has thousands of engineers and a platform built for it | Do we have their problem, their team count, their platform? |
| Org politics ("our team wants its own service") | Encodes a political boundary; Conway's law makes it permanent | Is there a business capability boundary here? |
| "Monoliths can't scale" | Monoliths scale horizontally behind a load balancer; Shopify runs one of the largest Rails codebases | Which part fails to scale, measured where? |
| "Microservices force clean code" | Wrong boundaries over a network = distributed monolith | Can we keep a clean module boundary in one process first? |
| "Rewrite to fix the mess" | A rewrite reproduces the mess unless the cause (boundaries, tests) is fixed | Can we modularise in place behind tests? |
| "Kubernetes is already here" | Platform presence lowers but does not remove the premium | Who owns API versioning, sagas, contract tests? |
Choosing
The flowchart is the author's synthesis of Fowler's prerequisites, the premium and Monolith First, and the Hard Parts drivers; the order matters: goal first, cheaper options second, prerequisites third, boundary stability last.
The weighted scorecard
Weights 1-5 say how much each driver matters to you; scores 1-5 say how well each form serves it in your context. The scorecard Go package computes the totals (its test encodes the first five startup rows); the value is in arguing about the inputs in an ADR review, not in the arithmetic.
// Package scorecard turns a team's weighted decision drivers into a ranking of the
// three forms. Weights and scores are the team's judgement; the code only keeps the
// arithmetic honest and the inputs reviewable in an ADR.
package scorecard
import (
"fmt"
"sort"
)
// Form is one of the candidate architectures.
type Form string
const (
Monolith Form = "monolith"
ModularMonolith Form = "modular-monolith"
Microservices Form = "microservices"
)
// Driver is one decision driver with a weight (1-5) and a score per form (1-5,
// where 5 means "this form serves the driver best in OUR context").
type Driver struct {
Name string
Weight int
Scores map[Form]int
}
// Result is the weighted total for one form.
type Result struct {
Form Form
Total int
Max int
}
// Evaluate validates the inputs and returns forms ordered by weighted total.
func Evaluate(drivers []Driver) ([]Result, error) {
forms := []Form{Monolith, ModularMonolith, Microservices}
totals := map[Form]int{}
maxTotal := 0
for _, d := range drivers {
if d.Weight < 1 || d.Weight > 5 {
return nil, fmt.Errorf("driver %q: weight %d outside 1-5", d.Name, d.Weight)
}
maxTotal += 5 * d.Weight
for _, f := range forms {
s, ok := d.Scores[f]
if !ok || s < 1 || s > 5 {
return nil, fmt.Errorf("driver %q: score for %s missing or outside 1-5", d.Name, f)
}
totals[f] += s * d.Weight
}
}
out := make([]Result, 0, len(forms))
for _, f := range forms {
out = append(out, Result{Form: f, Total: totals[f], Max: maxTotal})
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Total > out[j].Total })
return out, nil
}package scorecard
import "testing"
// The 4-person startup from the ADR examples: delivery speed and cost dominate.
func TestStartupPrefersMonolithicForms(t *testing.T) {
drivers := []Driver{
{"delivery speed now", 5, map[Form]int{Monolith: 5, ModularMonolith: 4, Microservices: 2}},
{"infra and ops cost", 4, map[Form]int{Monolith: 5, ModularMonolith: 5, Microservices: 1}},
{"team autonomy", 1, map[Form]int{Monolith: 2, ModularMonolith: 3, Microservices: 5}},
{"independent scaling", 1, map[Form]int{Monolith: 2, ModularMonolith: 2, Microservices: 5}},
{"room to split later", 3, map[Form]int{Monolith: 2, ModularMonolith: 5, Microservices: 4}},
}
got, err := Evaluate(drivers)
if err != nil {
t.Fatal(err)
}
if got[0].Form != ModularMonolith || got[len(got)-1].Form != Microservices {
t.Fatalf("ranking = %+v", got)
}
}
func TestRejectsBadWeights(t *testing.T) {
_, err := Evaluate([]Driver{{"x", 9, map[Form]int{Monolith: 1, ModularMonolith: 1, Microservices: 1}}})
if err == nil {
t.Fatal("want error for weight 9")
}
}| Driver | Weight (startup) | Monolith | Modular | Micro | Weight (scale-up) | Monolith | Modular | Micro |
|---|---|---|---|---|---|---|---|---|
| Delivery speed now | 5 | 5 | 4 | 2 | 4 | 2 | 4 | 3 |
| Infra and ops cost | 4 | 5 | 5 | 1 | 2 | 5 | 5 | 2 |
| Team autonomy | 1 | 2 | 3 | 5 | 5 | 1 | 3 | 5 |
| Independent scaling | 1 | 2 | 2 | 5 | 3 | 2 | 2 | 5 |
| Room to split later | 3 | 2 | 5 | 4 | 3 | 1 | 5 | 4 |
| Platform readiness | 2 | 5 | 5 | 1 | 3 | 5 | 5 | 4 |
| Weighted total | 65 | 70 | 38 | 47 | 77 | 80 |
Read the scale-up column carefully: microservices lead the modular monolith by only 3 points (80 vs 77). That is a signal to go hybrid (modular core plus the one or two parts where autonomy and scaling scores are driven by a specific module), not to pick a winner for the whole system.
Three ADRs, filled
ADR structure and review are in Architecture Decisions; these three show the decision content.
ADR-0001 (4-person startup): One deployable, modular inside.
| Section | Content |
|---|---|
| Status | Accepted |
| Context | 4 engineers, pre product-market fit, B2B scheduling SaaS, Laravel, one PostgreSQL. Goal: ship weekly experiments; lead time under 1 day. No platform team, no on-call rotation beyond the founders. |
| Decision | One Laravel app with app/Modules/{Scheduling,Billing,Accounts}; each module has a contract in Api/, its own schema; Pest arch() tests forbid Internal imports. Queue workers run from the same codebase. |
| Consequences | Easier: refactors, one transaction, one deploy, cheap infra. Harder: nothing scales independently; one bad deploy affects all. |
| Revisit if | A module needs over 10x the capacity of the rest; or the team exceeds 3 teams and lead time rises above 1 day for 2 consecutive months. |
ADR-0014 (60-engineer scale-up): Modular core plus extracted payments and search.
| Section | Content |
|---|---|
| Status | Accepted, supersedes ADR-0003 ("all services by 2026") |
| Context | 8 stream-aligned teams + 1 platform team. DORA: median lead time 30 h; payments waits on full test suite; search traffic is 20x checkout and needs OpenSearch. Co-change: payments team's commits touch only Payments 85% of the time. Platform can create a new service with tracing and a pipeline in one day. |
| Decision | Keep the core as a modular monolith (schemas per module, merge queue, module-level CI). Extract payments (own cadence, PCI scope) and search (scaling asymmetry) with strangler fig and parallel run. All others stay in the core. |
| Consequences | Easier: payments releases independently; search scales alone. Harder: payments↔orders becomes a saga with outbox; contract tests; two more on-call rotations. |
| Revisit if | Core lead time exceeds 8 h after the merge queue; or an extracted service needs a synchronous call to the core on every request (merge signal). |
ADR-0042 (regulated enterprise bank): Isolation by regulation, modular inside each line of business.
| Section | Content |
|---|---|
| Status | Accepted |
| Context | 400 engineers, 5 lines of business. Card data under PCI DSS; customer data with residency rules in two regions; auditors require separate change approval for the ledger. Mature platform, tracing, SLOs. |
| Decision | Separate deployables (and databases) where regulation draws a line: card vault, ledger, per-region customer data. Inside each line of business, a modular monolith owned by 3-8 teams. Integration via events with an outbox and versioned schemas. |
| Consequences | Easier: audit scope, regional isolation, independent change approval. Harder: cross-domain workflows are sagas; data duplication with reconciliation reports; higher infra cost accepted. |
| Revisit if | A regulatory boundary disappears (scope can shrink); or two deployables always change together for two quarters. |
Decision table
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New product, 1-2 teams | Monolith with modules | Schema per module, fitness tests | YAGNI; boundaries unknown |
| 3-6 teams, one product | Modular monolith | Merge queue, CODEOWNERS, module CI | Coordination solved without the premium |
| One hot spot (search, media, ML) | Hybrid: extract that part | Strangler fig, parallel run | Scaling asymmetry is a real disintegrator |
| PCI / health / residency scope | Separate deployable for the regulated part | Own DB, network policy, mTLS | Auditor's scope is the driver |
| Many teams, distinct cadences, mature platform | Microservices along business capabilities | Platform team, contract tests, outbox | Autonomy outweighs the premium |
| Services that always deploy together | Merge them | Reverse strangler | Distributed monolith |
| Many tiny services, one team | Merge into a modular service | Keep contracts as module APIs | Nanoservices; ops burden |
| Second version of a well-known system | Coarse services along known domains (Tilkov) or modular monolith | Event storming first | Domain knowledge exists |
In architecture: from a single process to a distributed system
The decision is never made once. It is re-made as the system moves along this path, and the same feature looks different at each step.
Monolith: one process, one database
How it shows up: form 1. One deployable, one transaction, boundaries only by convention.
Simplest correct usage: layered or feature folders, a fast CI, error tracking, one ADR that names the expected lifetime and the "revisit if" signal.
Example (simple): a clinic booking app run by two developers: Laravel, PostgreSQL, Horizon for reminders. Nothing to decide yet beyond the database.
Example (production-shaped): an e-commerce shop at 200 orders/minute on three stateless app servers behind a load balancer, one primary and one replica. It scales by adding app servers; the decision to stay is backed by p99 and CPU graphs.
Modular monolith and multiple databases
How it shows up: form 2. Modules with contracts, schema per module, in-process events, fitness tests.
-- PostgreSQL: data ownership made visible; ordering cannot read inventory's tables.
CREATE SCHEMA ordering; CREATE SCHEMA inventory;
CREATE ROLE ordering_app LOGIN; CREATE ROLE inventory_app LOGIN;
GRANT USAGE, CREATE ON SCHEMA ordering TO ordering_app;
GRANT USAGE, CREATE ON SCHEMA inventory TO inventory_app;
CREATE TABLE inventory.stock (sku text PRIMARY KEY, level int NOT NULL CHECK (level >= 0));
CREATE TABLE inventory.reservations (
id text PRIMARY KEY, order_id text NOT NULL UNIQUE, -- UNIQUE = idempotency per order
sku text NOT NULL REFERENCES inventory.stock(sku), qty int NOT NULL CHECK (qty > 0),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE ordering.orders (
id text PRIMARY KEY, customer_id bigint NOT NULL, sku text NOT NULL,
qty int NOT NULL, reservation_id text NOT NULL, -- no FK into inventory: the seam for a later split
created_at timestamptz NOT NULL DEFAULT now()
);Example: a 40-engineer SaaS with 9 modules, each owned by one team, a single release per hour through a merge queue. The data layout above means extracting inventory later moves two tables and one role, not a web of joins. MySQL uses databases instead of schemas for the same effect; SQL Server and Oracle have schemas and roles like PostgreSQL.
Microservices: the boundary gets a network
What survives: the contract (inventory.API, InventoryApi), the idempotency per order, the event names.
What breaks: the shared transaction, the free call, the atomic deploy. They are replaced by:
Checkout after extracting inventory-svc
1 POST /orders ordering-svc
2 POST /reservations (Idempotency-Key: ord-81, timeout 800 ms) -> inventory-svc
3 201 {id: res-9} or 409 -> OutOfStock, or 503 -> retry with same key
4 INSERT orders + INSERT outbox(OrderPlaced) in one local transaction
5 relay publishes OrderPlaced -> broker -> notifications, analytics (at-least-once, deduplicated)
Failure: ordering crashes after 3, before 4 -> reservation expires by TTL or a reconciliation job releases itPatterns: Timeouts, retries and jitter, API idempotency, Outbox, Saga, Idempotent consumer, Service Communication.
Distributed data: replicas, caches and many databases
| Where the decision is tested | What breaks | Response |
|---|---|---|
| Read replicas behind any form | Replica lag: "my order is missing" | Read-your-writes from the primary after a write (Replication) |
| Cache of stock levels | Oversell on stale cache | Cache for display only; reserve against the owner |
| Database per service | No joins for reports | Read models, CDC into a warehouse (CDC) |
| Duplicated customer data in 4 services | Divergence, reconciliation jobs | One owner plus events; or merge (a merge signal) |
| Multi-region | Cross-region calls per request | Keep the call graph inside a region; replicate reference data |
Scaling path: 1×, 10×, 100×
| Scale | Structure | What the decision looks like |
|---|---|---|
| 1× (one team, thousands of users) | Monolith, modular folders | Stay; invest in tests and CI |
| 10× (several teams, one hot spot) | Modular monolith, schema per module, workers by role | Extract only the hot spot if bulkheads and workers do not suffice |
| 100× (many teams, many products) | Modular cores per domain + services for regulated or asymmetric parts | Platform team, contracts as products, per-domain ADRs; merge back where services are chatty |
Lab: measure, score, and move a boundary
Everything runs offline with Go 1.24+.
Setup.
cd docs/snippets/architecture/monolith-vs-microservices-vs-modular/go
go vet ./... && go test ./...
go run ./cmd/shop
# placed ord-1 (reservation res-1)- Run form 3 for real. Write a 10-line
mainthat servesinventorysvc.Handler(inventory.New(map[string]int{"book": 10}))on:8081, thenINVENTORY_URL=http://localhost:8081 go run ./cmd/shop. Expected: same output; ordering code unchanged. - Feel the premium. Add
time.Sleep(300 * time.Millisecond)in the handler and set the client timeout to200ms. Expected:inventory unavailable after 3 attempts. In form 2 this failure mode does not exist. - Break the boundary. Create
modular/inventory/internal/x/x.go(package x) and import it frommodular/ordering/ordering.go. Expected: the compiler refuses withuse of internal package ... not allowed, andgo test ./modular/fails with the fitness-test message. Two independent guards. - Idempotency proof. Run
go test -run TestSameOrderTwiceReservesOnce -v ./micro/.... Remove thebyOrdercheck ininventory.go; the test fails withlevel = 1, want 3. - Score your system. Copy
scorecard_test.go, replace the drivers with your team's weights and scores, and present the result with the inputs in an ADR draft. - Measure signals. Load your last 90 days of deploys and commits into the SQL tables from Mechanics; report lead time, deploys/week, change fail rate and the top 3 co-changing module pairs.
Common misconceptions
| Belief | Reality |
|---|---|
| Microservices are the modern default | Fowler: "The majority of software systems should be built as a single monolithic application" with good modularity |
| A monolith cannot scale | It scales horizontally; what does not scale is usually one hot spot or the team process |
| Microservices give modularity | Only with right boundaries; wrong ones give a distributed monolith |
| Modular monolith is a stepping stone only | For most systems it is the destination (Shopify) |
| Merging services back is failure | Segment and Prime Video published consolidations as improvements |
| Splitting is a one-time cost | The premium is recurring: pipelines, on-call, versioning, consistency |
| Microservices reduce cognitive load | Code per service shrinks; operational load per team grows without a platform |
| Independent services means independent deploys | Only if contracts are versioned; lock-step deploys mean a distributed monolith |
| You must choose one form for the whole system | Hybrids (modular core plus a few services) are the common end state |
| Clean boundaries need separate deployment | Logical and physical boundaries are separate decisions (Google 2023) |
| DORA has four metrics | The current DORA guide uses five |
| Prime Video abandoned microservices | One monitoring service moved to a monolith; the post says the choice "has to be made on a case-by-case basis" |
Cheat sheet
| Topic | Remember |
|---|---|
| First question | What are we optimising, measured how? |
| Default | Modular monolith, boundaries enforced in CI |
| Premium | Deployment automation, monitoring, failure handling, eventual consistency, ops |
| Prerequisites | Rapid provisioning, basic monitoring, rapid deployment, DevOps culture |
| Monolith first | Boundaries are hard to get right early; Tilkov disagrees when the domain is known |
| Logical vs physical | Cut code once; choose processes later |
| Disintegrators | Scope, volatility, scalability, fault tolerance, security, extensibility |
| Integrators | Transactions, workflow, shared code, data relationships |
| Split signals | Deploy contention, scaling hot spot, team coupling, blast radius |
| Merge signals | Nanoservices, chatty graph, lock-step deploys, duplicated data, ops burden |
| Split safely | Branch by abstraction, strangler fig, parallel run, expand/contract |
| Remote client | Timeout, retry only transient errors, backoff, idempotency key, same error contract |
| Measure | DORA lead time, deploy frequency, change fail rate, recovery time, rework rate |
| ADR | Goal with a number; "revisit if" signal; superseded, never deleted |
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 — A CTO asks for microservices "to go faster". What do you ask first, and which metric do you propose? Must-know
Answer
Answer: What hurts, and for whom. Propose DORA change lead time and deployment frequency per team, with a target. Then check whether a modular monolith with a merge queue and module CI reaches it. See the question behind the question.
2 — Name four items of the microservice premium Fowler lists. Important
Answer
Answer: Automated deployment, monitoring, dealing with failure, eventual consistency (and "other factors that a distributed system introduces"). See premium.
3 — What is Fowler's main reason against starting with microservices, and Tilkov's main reason against starting with a monolith? Important
Answer
Answer: Fowler: boundaries are hard to get right at the beginning, even for experienced architects. Tilkov: parts of a monolith become tightly coupled and it is "extremely hard to split up an existing monolith". Both agree you need good domain knowledge before cutting. See monolith first.
4 — What does Google's HotOS 2023 paper say microservices conflate, and what follows for the decision? Good to know
Answer
Answer: Logical boundaries (how code is written) with physical boundaries (how it is deployed). Decide the logical cut first; keep the physical choice in the composition root. See logical vs physical.
5 — List the four granularity integrators from The Hard Parts. Good to know
Answer
Answer: Database transactions, workflow and choreography, shared code, data relationships. See granularity.
6 — Which four signals justify extracting one service? Must-know
Answer
Answer: Deploy contention, scaling hot spot, team coupling (co-change), blast radius, each measured, with a threshold in the ADR. See split signals.
7 — Three services always deploy together and call each other on every request. What are they and what do you do? Must-know
Answer
Answer: A distributed monolith with a chatty call graph. Merge them into one deployable (keep their contracts as module APIs) with a reverse strangler. See merge signals and consolidating.
8 — In the Go example, which file changes when inventory moves out of process, and why does ordering not change? Important
Answer
Answer: cmd/shop/main.go (the composition root) picks inventoryclient.Client instead of inventory.Module. Ordering depends on inventory.API, which both satisfy. See Go.
9 — Why must the remote client send an Idempotency-Key, and why rebuild the request body per attempt? Must-know
Answer
Answer: A retry after a lost response would otherwise reserve stock twice; the server deduplicates by key. A consumed body reader would send an empty body on the retry. See form 3.
10 — Laravel: you set retry(3, 100, throw: false). Can an exception still escape? Important
Answer
Answer: Yes. If every attempt fails with a connection problem, ConnectionException is still thrown. See Laravel form 3.
11 — What did Prime Video's 2023 post actually say? Good to know
Answer
Answer: One audio/video monitoring service moved from distributed components (Step Functions, Lambda, S3 between steps) into a single process on ECS, cutting infrastructure cost "by over 90%". It also says the choice "has to be made on a case-by-case basis". See history.
12 — Your scorecard gives microservices 80 and the modular monolith 77. What do you decide? Important
Answer
Answer: Not a whole-system winner: look at which modules drive the microservice score (autonomy, scaling) and extract only those; keep the core modular. See scorecard.
Glossary
| Term | Meaning |
|---|---|
| Monolith | One deployable unit containing all functionality |
| Modular monolith | One deployable cut into modules with public APIs, private internals and owned data |
| Microservices | Independently deployable services organised around business capabilities, each owning its data |
| Microservice premium | Recurring extra cost of running a distributed system (Fowler) |
| Monolith first | Start with one deployable, split by observed boundaries (Fowler) |
| Duolith | Fowler's joke name for starting with two coarse-grained services |
| Sacrificial architecture | An architecture built expecting to be replaced once it succeeds |
| Logical boundary | How code is divided: modules, interfaces |
| Physical boundary | How code is deployed: processes, hosts |
| Service Weaver | Google's framework for logical monoliths with runtime placement; maintenance mode Dec 2024, archived Mar 2026 |
| Granularity disintegrator | A reason to split a service (Hard Parts) |
| Granularity integrator | A reason to keep or put services together (Hard Parts) |
| Conway's law | Systems copy the communication structure of the organisation that builds them |
| Inverse Conway maneuver | Shaping teams to get the architecture you want |
| Cognitive load | How much a team must hold in mind to own its part |
| Stream-aligned team | Team aligned to a flow of business work (Team Topologies) |
| Platform team | Team providing internal services that reduce other teams' load |
| DORA metrics | Change lead time, deployment frequency, failed deployment recovery time, change fail rate, deployment rework rate |
| Deploy contention | Changes waiting for a shared release |
| Scaling asymmetry / hot spot | One part needs much more or different capacity |
| Blast radius | How much breaks when one part fails |
| Fault isolation | Keeping a failure inside one part |
| Distributed monolith | Services that must change or deploy together |
| Nanoservice | A service too small to own a business capability |
| Chatty call graph | Many synchronous hops per user request |
| Strangler fig | Grow a new system around the old one route by route |
| Branch by abstraction | Introduce an interface as a seam, swap implementations behind it while releasing |
| Parallel run | Run old and new paths, compare, serve the old result |
| Expand and contract | Parallel change: expand the API, migrate callers, contract |
| Change data capture (CDC) | Streaming database changes to other systems |
| Fitness function | Automated check that an architectural rule holds |
| Packwerk | Shopify's static checker for Rails component boundaries |
| Idempotency key | Client-supplied key letting the server deduplicate retried requests |
| Outbox | Writing events in the same local transaction as the data, relayed later |
| Hybrid topology | Modular core plus a few extracted services |
| Regulatory isolation | Separate deployables/data so an audit scope (PCI DSS, residency) stays small |
| Technology heterogeneity | Different languages or runtimes per part |
| ADR | Architecture Decision Record: one short file per significant decision |
References
- Martin Fowler, "Microservice Premium", 13 May 2015; "Monolith First", 3 June 2015; "Microservice Prerequisites", 28 August 2014; "Microservice Trade-Offs", 1 July 2015; "Sacrificial Architecture"; "Strangler Fig Application"; "Branch By Abstraction", 7 January 2014; "Conway's Law"
- Danilo Sato, "Parallel Change", 13 May 2014
- James Lewis and Martin Fowler, "Microservices", 25 March 2014
- Stefan Tilkov, "Don't start with a monolith", 9 June 2015
- Sam Newman, "Microservices For Greenfield?", 7 April 2015; Monolith To Microservices (O'Reilly; table of contents read, chapters not)
- Neal Ford, Mark Richards, Pramod Sadalage, Zhamak Dehghani, Software Architecture: The Hard Parts, O'Reilly 2022, chapter 7 "Service Granularity" (free PDF via Thoughtworks). Richards & Ford, Fundamentals of Software Architecture, is in the section canon; its chapters were not accessible (HTTP 403) and nothing here is quoted from it.
- Sanjay Ghemawat et al., "Towards Modern Development of Cloud Applications", HotOS '23, June 2023; Service Weaver docs; ServiceWeaver/weaver on GitHub (maintenance-mode notice, archived)
- Melvin E. Conway, "How Do Committees Invent?", Datamation, April 1968
- Alexandra Noonan, "Goodbye Microservices: From 100s of problem children to 1 superstar", Segment/Twilio, 10 July 2018
- Marcin Kolny, "Scaling up the Prime Video audio/video monitoring service and reducing costs by 90%", Prime Video Tech, 22 March 2023 (archived copy; the original URL now redirects)
- Kirsten Westeinde, "Deconstructing the Monolith", Shopify, 21 Feb 2019; Philip Müller, "Under Deconstruction: The State of Shopify's Monolith", 16 Sep 2020
- Vicent Martí, "Move Fast and Fix Things", GitHub, 15 December 2015
- DORA, "DORA's software delivery performance metrics"
- Team Topologies, Key concepts (Skelton & Pais)
- Chris Richardson, microservices.io: Monolithic architecture, Microservice architecture, Strangler application
- Laravel 13: HTTP Client, Events; Pest: Architecture testing