Skip to content

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 forGo to
The whole decision in three tablesEverything in one minute
Why this is a decision at allWhy the decision exists
Conway 1968 to Google 2023 and Prime Video 2023Where it comes from
Goal, premium, monolith-first, logical vs physical, granularity, cognitive load, DORA, split and merge signalsThe concepts, one by one
Every driver in one tableDecision drivers
What microservices cost, line by lineCost model
Startup, scale-up, enterpriseTimelines
What changes in code, measuring signals in SQL, error messagesMechanics
One feature in three formsGo, Laravel, Cost per form
Splitting, merging back, keeping modules clean, hybrids, bad reasonsSolving the classic problems
Flowchart, scorecard, three filled ADRsChoosing
Monolith to distributed systemIn architecture
Exercise with measurable outputLab
Wrong beliefs, cheat sheet, self-check, termsMisconceptions, 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.

FormIn plain wordsUnit of deploymentBoundary enforced byCross-boundary callTransaction across partsBest when
Monolith (unstructured or layered)One app, code organised by technical layer or not at allOneNothing but disciplineFunction callYes, one database transactionOne small team, unclear domain, speed to market
Modular monolithOne app, cut into modules with public APIs and private internalsOneLanguage visibility, fitness tests (Go internal/, Pest arch(), Shopify Packwerk)Function call through a module interface; in-process eventsYes, when you need itMost systems, most of the time: several teams, one platform
MicroservicesMany apps, each owning its data, deployed independentlyManyThe network and separate repositories or pipelinesHTTP/gRPC or messages, with timeouts and retriesNo; sagas, outbox, eventual consistencyMany 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 optimiseMeasured byCheapest form that usually reaches itMicroservices needed when
Delivery speed of one teamDORA change lead time, deployment frequencyMonolith or modular monolith with a fast pipelinePractically never for one team
Delivery speed of many teamsLead time per team, merge/deploy queue waitModular monolith with module ownership and a merge queueTeams still block each other on one release train after modularising
ScalingCost per request, p99 under loadBigger machine, replicas, caches, a worker pool inside the monolithOne part needs very different hardware or scale (a 50x hot spot, GPUs)
Fault isolationBlast radius of one bugBulkheads, separate worker processes from the same codebaseA failure in one part must not share memory, runtime or deploy with the rest
Team autonomyNumber of cross-team approvals per changeModule ownership (CODEOWNERS), module APIsTeams need their own release cadence, stack or on-call
Regulatory isolationAudit scope (PCI DSS, HIPAA, data residency)Separate database schema and roleThe auditor's scope must exclude everything else
CostInfra plus people-hours per monthMonolithRarely the reason; usually the opposite (see Prime Video)

Signals, both directions (unpacked in split signals and merge signals):

Signal to split one part outSignal to merge services back
Deploy contention: changes to X wait in a shared release queueNanoservices: services too small to own a business capability
Scaling hot spot: X needs 10x+ the capacity of the restChatty call graph: one user request fans out into many synchronous hops
Team coupling: one team's changes mostly touch X, and X onlyServices that always deploy together (a distributed monolith)
Blast radius: X's failures take down unrelated featuresDuplicated data and reconciliation jobs between services
Different compliance or security level for XOperational 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" failNetwork calls: milliseconds, can time out after doing the work
One database transactionSagas, outbox, eventual consistency
Refactoring across modules is one commitChanging a published API is a multi-release migration
One pipeline, one runtime to patch, one thing to monitorN pipelines, N runtimes, distributed tracing
Everyone deploys together: one bad change blocks allEach team deploys alone
Scaling is all-or-nothingEach part scales on its own
Boundaries erode unless tooling enforces themThe 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 ​

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

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

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

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

GoalLeading indicator to watchWhere the method is taught
Delivery speedDORA change lead time, deployment frequencyDORA
ReliabilityChange fail rate, failed deployment recovery time, SLO burnSLOs
ScalingCost per request, saturation of the hot partCapacity estimation
AutonomyCross-team PR approvals per changeCognitive load
IsolationIncidents where an unrelated feature brokeBlast 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.

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

Real 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 itemPaid byCan a platform team amortise it?
Pipelines, templates, service scaffoldingPlatform teamYes, mostly
Observability (traces, metrics, logs per service)Platform + every teamPartly
API versioning, contract testsEvery team, per APINo
Distributed failure handling (timeouts, retries, idempotency)Every team, per callLibraries help; design cannot be outsourced
Eventual consistency (sagas, outbox, reconciliation)Every team, per workflowNo
On-call per serviceEvery teamNo

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

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

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

PositionSourceKey condition
Monolith firstFowler 2015; Newman 2015 (greenfield post)Boundaries are unknown; product may fail
Don't start with a monolithTilkov 2015Domain well known; goal is a microservices architecture
Coarse services ("duolith")Fowler 2015 footnoteLearn the platform with little inter-service refactoring
Logical monolith, physical decision laterGoogle HotOS 2023A 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).

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

StackModule boundary tool
GoPackages, internal/ directories (Go 1.4 rule), import tests with go/parser
Laravel / PHPapp/Modules/* namespaces, service providers, Pest arch() (not->toUse, toOnlyBeUsedIn)
Ruby on RailsPackwerk (Shopify), Rails engines
JavaJPMS module-info.java, ArchUnit, Spring Modulith
.NETAssemblies with internal visibility, NetArchTest
DatabaseOne 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.

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

MechanismLogical boundaryPhysical choice
Go interface + composition rootinventory.APILocal struct or HTTP client
Laravel container bindingInventoryApi contractDatabaseInventory or HttpInventoryApi
Same codebase, several process rolesModulesWeb, worker, scheduler processes
Service Weaver (archived 2026)Components as Go interfacesRuntime 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.

DriverKindQuestion (Hard Parts wording)Reason for applying (their Tables 7-2 and 7-3)
Service scope and functionDisintegrator"Is the service doing too many unrelated things?"Single-purpose services with tight cohesion
Code volatilityDisintegrator"Are changes isolated to only one part of the service?"Agility (reduced testing scope and deployment risk)
Scalability and throughputDisintegrator"Do parts of the service need to scale differently?"Lower costs and faster responsiveness
Fault toleranceDisintegrator"Are there errors that cause critical functions to fail within the service?"Better overall uptime
SecurityDisintegrator"Do some parts of the service need higher security levels than others?"Better security access control to certain functions
ExtensibilityDisintegrator"Is the service always expanding to add new contexts?"Agility (ease of adding new functionality)
Database transactionsIntegrator"Is an ACID transaction required between separate services?"Data integrity and consistency
Workflow and choreographyIntegrator"Do services need to talk to one another?"Fault tolerance, performance, and reliability
Shared codeIntegrator"Do services need to share code among one another?"Maintainability
Data relationshipsIntegrator"Although a service can be broken apart, can the data it uses be broken apart as well?"Data integrity and correctness
text
     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" line

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

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

MechanismReduces which load
Module ownership (CODEOWNERS) in a modular monolithCoordination without platform cost
Platform team, X-as-a-ServicePer-service pipeline and runtime load
Thinnest viable platformPrevents the platform itself becoming a load
Stream-aligned team per business capabilityCross-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).

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

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

SignalHow to measureThreshold you set in the ADR (example, yours to choose)
Deploy contentionHours a ready change waits for the shared release; % of releases blocked by another teamA team waits more than its lead-time goal for others
Scaling hot spotCPU/memory/requests per module from profiling or APMOne module needs over 10x the replicas or different hardware
Team couplingCo-change: % of a team's commits that touch only module XOver 80% of team A's changes are inside X, under 10% of others'
Blast radiusIncidents where a fault in X broke unrelated featuresTwo or more per quarter after bulkheads and timeouts
text
     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:

SignalHow it looksIntegrator it maps to
NanoservicesServices smaller than a business capability; one entity per serviceService scope
Chatty call graphOne request makes many synchronous hops; latency adds upWorkflow and choreography
Lock-step deploysServices that must be released together (a distributed monolith)Shared code, data relationships
Duplicated dataReconciliation jobs, "source of truth" debatesData relationships, database transactions
Operational burdenOn-call pages per engineer rise with service count(cost, not in the book's list)
text
     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 all

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

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

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

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

DriverQuestion to askFavours monolith / modularFavours microservicesEvidence to collect
Team size and numberHow many teams must ship independently?1-4 teamsMany stream-aligned teams with distinct cadenceOrg chart, CODEOWNERS, co-change
Domain clarityAre the boundaries stable and known?New or shifting domainWell-understood domain (second version)Event storming, months of co-change data
Release cadenceDo parts need very different release rhythms?Same cadenceHourly vs quarterly partsDeploy log per module
Scaling asymmetryDoes one part need different scale or hardware?Uniform load10x+ hot spot, GPU, special datastoreProfiling, APM per route
Fault isolationMust a failure in X never touch Y?Bulkheads and worker processes sufficeSeparate runtime requiredIncident log
Regulatory isolationDoes an auditor need a smaller scope?No special scopePCI DSS cardholder data, health data, residencyCompliance requirements
Technology heterogeneity (tech heterogeneity)Does a part need another language or runtime?One stackML in Python, a JVM-only libraryLibrary constraints
Platform maturityCan we provision, deploy, monitor and trace a new service in a day?NoYes (Fowler's prerequisites)Time-to-first-deploy of a new service
Observability maturityDistributed tracing, per-service SLOs, log correlation?Not yetIn placeTrace coverage %
CI maturityPipeline per service, contract tests, fast builds?One pipelineTemplates and contract testingPipeline duration
Data couplingDo parts need one transaction or joins?Strong (integrator)Weak; events sufficeSchema foreign keys, queries crossing modules
BudgetCan we pay infra + platform people?TightFunded platform teamCost model
Time to marketIs the next 6 months about product discovery?YesNo, scale is the problemRoadmap

Cost model: the microservice premium item by item ​

cost per engineer (coordination + platform)number of engineers / teams1 team3-6 teamsmany teamsTangled monolith (solid)merge and deploy contentionModular monolith (dashed)boundaries cut coordinationMicroservices (dotted)fixed premium from day onemodular monolith cheapest hereIllustrative shape, not measured data

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 itemMonolithModular monolithMicroservicesWhy it differs
Infrastructure1 app tier + DBSameN runtimes, N databases, broker, gateway, mesh/sidecarsEach service has fixed overhead (min replicas, memory baseline)
OperationsOne deploy, one set of alertsSame + module-level metricsPer-service dashboards, alerts, on-call, upgradesFowler: "You need a mature operations team"
LatencyFunction callsSameNetwork hop per call, serialization, retriesGoogle C1 "It hurts performance"
ConsistencyACID transactionACID (modules can share a transaction)Sagas, outbox, eventual consistencyFowler's trade-offs: "everyone has to manage eventual consistency"
TestingUnit + integration in one process+ fitness tests, module fakes+ contract tests, network fault tests, end-to-end environmentsGoogle C3: local end-to-end tests become "an engineering feat"
API changeRename in IDEChange module API in one PRVersioned API, expand/contract across releasesGoogle C4 "It freezes APIs"
Cognitive loadWhole codebaseOne module + its API neighboursOne service + its platformTeam Topologies
DebuggingStack traceStack traceDistributed trace across servicesNeed trace propagation
Security surfaceOne perimeterOne perimeterService-to-service auth (mTLS, tokens)More network edges
DataOne DB, joinsOne DB, schema per moduleDB per service, data duplication, CDCData Ownership

Timelines: startup → scale-up → enterprise ​

text
     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
StageMain goalMain riskWhat to build nowWhat to postpone
Pre-PMF startupLearning speedBuilding the wrong productOne deployable, CI, error trackingKubernetes, service mesh, event bus
Early growthKeep speed as the team triplesTangled codeModule APIs, schema per module, fitness testsExtracting services
Scale-upTeam independence, one or two hot spotsPlatform debt, premature splitsPlatform team, tracing, templates; extract the hot spotSplitting everything
EnterpriseGovernance, compliance, many productsDistributed monolith across departmentsDomain-level ownership, API standards, isolation where regulatedOne mandated style for all

Mechanics ​

What changes in the code when the boundary moves ​

1. MonolithPlaceOrderUPDATE stock inlineone DB, one txorders + products2. Modular monolithOrderingevent busInventoryInventoryApione DB, schema per moduletx may span modules3. Microservicesordering-svcinventory-svcHTTP + retryorders DB+ outboxstock DBidempotencyno shared transaction
Aspect1. In-process call2. Module interface + event3. HTTP/gRPC client
Calls.stock[sku] -= qtyinv.Reserve(ctx, orderID, sku, qty)Same call; implemented by inventoryclient.Client
Failure modesError or panicError from the moduleTimeout, connection refused, 5xx, partial success (work done, reply lost)
LatencyNanosecondsNanosecondsMilliseconds plus retries
TransactionOneCan still be oneNone across services; saga or outbox
IdempotencyNot neededCheap and recommendedRequired (Idempotency-Key)
EventsNot neededIn-process bus, synchronousBroker, at-least-once, consumers deduplicate
TestsOne integration testModule fakes + fitness test+ HTTP fakes, retry and timeout tests, contract tests
DeployOneOneTwo, with version compatibility

Measuring the signals in SQL ​

The split/merge signals are data. A PostgreSQL schema fed by your CI and Git hooks:

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

WhereMessageWhat it tells you about the decision
Go net/http clientcontext deadline exceededThe timeout budget of a remote call was spent; in-process this never happens
Go net/http clientdial tcp ...: connect: connection refusedThe other service is down or not ready; retry with backoff
Go compileruse of internal package ... not allowedThe 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 clientIlluminate\Http\Client\ConnectionExceptionConnection failed; thrown after the last retry even with throw: false
Laravel HTTP clientIlluminate\Http\Client\RequestExceptionA 4xx/5xx after ->throw()
HTTP409 Conflict (this page's contract)Business error, do not retry; maps to OutOfStock
HTTP503 Service Unavailable, 502 Bad GatewayTransient; retry with the same idempotency key
Pestfailed 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.

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

go
// 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]
}
go
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.

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

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

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

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

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

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

go
// 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 featureWhat it does for this decision
Packages and internal/Module boundaries the compiler enforces; the cheapest modular monolith tooling there is
Implicit interfacesinventory.API is satisfied by *Module and *Client without either importing the other
context.ContextDeadlines and cancellation flow across in-process and remote calls the same way
net/http + httptestA remote client and its failure tests with no dependencies
One static binaryCheap 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.

text
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, assertSent

Form 1: monolith ​

php
<?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
<?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
<?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
<?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
<?php

namespace App\Modules\Inventory\Api;

final class OutOfStock extends \DomainException {}

The private implementation and the module's only wiring:

php
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 featureRole in the decision
Service container bind()Swaps in-process and remote implementations of one contract
Service providers in bootstrap/providers.phpOne provider per module = the module's wiring
DB::transaction, lockForUpdate()The atomicity forms 1 and 2 keep for free
Events + ShouldDispatchAfterCommitIn-process events that never announce a rolled-back write
Queued listeners, HorizonSeparate worker processes from one codebase (a physical split without a code split)
HTTP client: timeout, connectTimeout, retry, Http::fake, Http::sequence, preventStrayRequestsForm 3 client and its tests
Pest arch()Fitness functions that keep a modular monolith modular
OctaneLong-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.

Item1. Monolith2. Modular monolith3. Microservices
Files touched to add the feature1-26-8 (API, impl, provider, event, tests)10-14 (+ client, handler, service config, pipeline)
Deployables112 (+ broker for events)
Pipelines112
Databases11 (2 schemas)2
Failure modes of the reserve call2 (ok, out of stock)25+ (ok, out of stock, timeout, refused, 5xx, lost reply)
Tests1 integration2 unit + 1 fitness + 1 integration+ 4 network tests + contract test
p50 added latency of reserve~0~0network RTT + serialization per attempt
ConsistencyACIDACIDIdempotent retries + outbox for events
Extra monthly infra001 more service's minimum replicas, DB, monitoring
Time to extract laterDays to weeks (find the boundary first)Hours to days (swap the binding)n/a

Solving the classic problems ​

Moving from monolith to services, safely ​

text
     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
TechniqueHowAdvantageCost / limitation
Strangler figRoute a slice of functionality to the new system at the edge (proxy, gateway); grow it until the old part is goneAlways shippable; reversible per routeTwo systems in production for a while (Strangler Fig)
Branch by abstractionFowler: 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 seamNeeds a clean seam; step 1 is often the hardest
Parallel runRun old and new, compare outputs, serve the old oneFinds behaviour differences on real trafficDouble 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 deploysMore releases
Change data captureStream the monolith's table changes to the new serviceData sync without dual writesSchema coupling to the old tables (CDC)
Decorating collaborator, UI compositionNewman's other chapter-3 patterns (headings only read)More seamsSituational

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 ​

text
     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)
TechniqueHowAdvantageCost / limitation
Reverse stranglerRoute old service endpoints to the merged process one by oneReversibleTwo hosts for a while
Keep the contract, change the bindingCallers keep the interface; implementation becomes in-processNo caller changeNetwork-era API shapes (pagination, DTOs) remain
Schema per former serviceMerge databases but keep schemas and rolesBoundaries survive the mergeJoins across schemas tempt people; add fitness tests
Worker pool consolidationOne pool processes all event types (Segment)Better utilisation, fewer pagesFault isolation: one poison input can crash all; add bulkheads

Keeping the modular monolith modular ​

SolutionHowAdvantageCost / limitation
Compiler visibilityGo internal/, Java modules, .NET internalCannot be bypassed casuallyPackage granularity
Fitness testsarch_test.go, Pest arch(), ArchUnitCustom rules in CIMust not be disabled under deadline
Static reference checkersShopify Packwerk ("analyze static constant references")Works on Ruby where the language has no visibilityRails-specific
Schema per module + DB rolesGRANT only on the module's schemaThe database enforces data ownershipMigration of existing cross-module queries
CODEOWNERSModule owners review every change to their pathsSocial enforcementBottleneck with few owners

Hybrid topologies ​

API gateway / reverse proxyModular core (one deployable)CatalogOrderingBillingAccountsin-process calls via module APIs, one transaction when neededPostgreSQL: one schema per module+ outbox tableSearch serviceown index; read-heavy, scales aloneMedia workersCPU/GPU bound; queue-drivenPayments serviceown DB; PCI scope isolatedBroker (events from the outbox)OrderPlaced, ProductChanged ... consumed by servicesHTTP/gRPC+ retry

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 serviceReason (driver)Keep in the core when
SearchDifferent datastore and scaleSearch is a simple SQL LIKE on a small table
Media transcoding, PDF/report generationCPU/GPU, long jobs, blast radiusA queue worker from the same codebase isolates it enough
Payments, card dataPCI DSS scope reduction, securityA PSP's hosted fields keep card data out of your system anyway
ML inferencePython/GPU stack, hourly model releasesA hosted API is called from the core
Notifications (email, push)Different reliability profile, vendor integrationsLaravel notifications + queues cover it
Public API for partnersSeparate rate limits, versioning cadenceSame team, same cadence

Bad reasons, and what to ask instead ​

Bad reasonWhy it is badAsk instead
Hype ("everyone does microservices")Fowler's premium post opens with the "over-hyped" warningWhich metric will improve, by how much?
Résumé-driven developmentOptimises the engineer's next job, not the productWho will be on call for this in two years?
"Netflix does it"Netflix has thousands of engineers and a platform built for itDo 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 permanentIs there a business capability boundary here?
"Monoliths can't scale"Monoliths scale horizontally behind a load balancer; Shopify runs one of the largest Rails codebasesWhich part fails to scale, measured where?
"Microservices force clean code"Wrong boundaries over a network = distributed monolithCan 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 fixedCan we modularise in place behind tests?
"Kubernetes is already here"Platform presence lowers but does not remove the premiumWho owns API versioning, sagas, contract tests?

Choosing ​

What are we optimising?Can we name one measurable goal?(lead time, scale hot spot, autonomy, isolation)Can a modular monolith reach it?(modules, faster CI, bigger box, replicas)Platform prerequisites in place?(provisioning, monitoring, pipelines, on-call)Is the boundary of that part stable?(few cross-boundary changes for months)Extract ONE service (strangler fig)measure the goal; keep the rest a modular coreNo: stay putmodular monolithYes: modularmonolith is enoughNo: build them firstpremium not affordable yetNo: waitharden module API firstHow to readmiddle column = questionsright column = stop herethick box = acteach arrow is labelledwith the answer it takesyesnoyesyesstartnoyesnono

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.

go
// 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
}
go
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")
	}
}
DriverWeight (startup)MonolithModularMicroWeight (scale-up)MonolithModularMicro
Delivery speed now55424243
Infra and ops cost45512552
Team autonomy12355135
Independent scaling12253225
Room to split later32543154
Platform readiness25513554
Weighted total657038477780

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.

SectionContent
StatusAccepted
Context4 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.
DecisionOne 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.
ConsequencesEasier: refactors, one transaction, one deploy, cheap infra. Harder: nothing scales independently; one bad deploy affects all.
Revisit ifA 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.

SectionContent
StatusAccepted, supersedes ADR-0003 ("all services by 2026")
Context8 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.
DecisionKeep 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.
ConsequencesEasier: payments releases independently; search scales alone. Harder: payments↔orders becomes a saga with outbox; contract tests; two more on-call rotations.
Revisit ifCore 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.

SectionContent
StatusAccepted
Context400 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.
DecisionSeparate 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.
ConsequencesEasier: audit scope, regional isolation, independent change approval. Harder: cross-domain workflows are sagas; data duplication with reconciliation reports; higher infra cost accepted.
Revisit ifA regulatory boundary disappears (scope can shrink); or two deployables always change together for two quarters.

Decision table ​

SituationRecommendationExtra techniqueReason
New product, 1-2 teamsMonolith with modulesSchema per module, fitness testsYAGNI; boundaries unknown
3-6 teams, one productModular monolithMerge queue, CODEOWNERS, module CICoordination solved without the premium
One hot spot (search, media, ML)Hybrid: extract that partStrangler fig, parallel runScaling asymmetry is a real disintegrator
PCI / health / residency scopeSeparate deployable for the regulated partOwn DB, network policy, mTLSAuditor's scope is the driver
Many teams, distinct cadences, mature platformMicroservices along business capabilitiesPlatform team, contract tests, outboxAutonomy outweighs the premium
Services that always deploy togetherMerge themReverse stranglerDistributed monolith
Many tiny services, one teamMerge into a modular serviceKeep contracts as module APIsNanoservices; ops burden
Second version of a well-known systemCoarse services along known domains (Tilkov) or modular monolithEvent storming firstDomain 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.

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

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

Patterns: Timeouts, retries and jitter, API idempotency, Outbox, Saga, Idempotent consumer, Service Communication.

Distributed data: replicas, caches and many databases ​

Where the decision is testedWhat breaksResponse
Read replicas behind any formReplica lag: "my order is missing"Read-your-writes from the primary after a write (Replication)
Cache of stock levelsOversell on stale cacheCache for display only; reserve against the owner
Database per serviceNo joins for reportsRead models, CDC into a warehouse (CDC)
Duplicated customer data in 4 servicesDivergence, reconciliation jobsOne owner plus events; or merge (a merge signal)
Multi-regionCross-region calls per requestKeep the call graph inside a region; replicate reference data

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

ScaleStructureWhat the decision looks like
1× (one team, thousands of users)Monolith, modular foldersStay; invest in tests and CI
10× (several teams, one hot spot)Modular monolith, schema per module, workers by roleExtract 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 partsPlatform 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.

bash
cd docs/snippets/architecture/monolith-vs-microservices-vs-modular/go
go vet ./... && go test ./...
go run ./cmd/shop
# placed ord-1 (reservation res-1)
  1. Run form 3 for real. Write a 10-line main that serves inventorysvc.Handler(inventory.New(map[string]int{"book": 10})) on :8081, then INVENTORY_URL=http://localhost:8081 go run ./cmd/shop. Expected: same output; ordering code unchanged.
  2. Feel the premium. Add time.Sleep(300 * time.Millisecond) in the handler and set the client timeout to 200ms. Expected: inventory unavailable after 3 attempts. In form 2 this failure mode does not exist.
  3. Break the boundary. Create modular/inventory/internal/x/x.go (package x) and import it from modular/ordering/ordering.go. Expected: the compiler refuses with use of internal package ... not allowed, and go test ./modular/ fails with the fitness-test message. Two independent guards.
  4. Idempotency proof. Run go test -run TestSameOrderTwiceReservesOnce -v ./micro/.... Remove the byOrder check in inventory.go; the test fails with level = 1, want 3.
  5. 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.
  6. 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 ​

BeliefReality
Microservices are the modern defaultFowler: "The majority of software systems should be built as a single monolithic application" with good modularity
A monolith cannot scaleIt scales horizontally; what does not scale is usually one hot spot or the team process
Microservices give modularityOnly with right boundaries; wrong ones give a distributed monolith
Modular monolith is a stepping stone onlyFor most systems it is the destination (Shopify)
Merging services back is failureSegment and Prime Video published consolidations as improvements
Splitting is a one-time costThe premium is recurring: pipelines, on-call, versioning, consistency
Microservices reduce cognitive loadCode per service shrinks; operational load per team grows without a platform
Independent services means independent deploysOnly if contracts are versioned; lock-step deploys mean a distributed monolith
You must choose one form for the whole systemHybrids (modular core plus a few services) are the common end state
Clean boundaries need separate deploymentLogical and physical boundaries are separate decisions (Google 2023)
DORA has four metricsThe current DORA guide uses five
Prime Video abandoned microservicesOne monitoring service moved to a monolith; the post says the choice "has to be made on a case-by-case basis"

Cheat sheet ​

TopicRemember
First questionWhat are we optimising, measured how?
DefaultModular monolith, boundaries enforced in CI
PremiumDeployment automation, monitoring, failure handling, eventual consistency, ops
PrerequisitesRapid provisioning, basic monitoring, rapid deployment, DevOps culture
Monolith firstBoundaries are hard to get right early; Tilkov disagrees when the domain is known
Logical vs physicalCut code once; choose processes later
DisintegratorsScope, volatility, scalability, fault tolerance, security, extensibility
IntegratorsTransactions, workflow, shared code, data relationships
Split signalsDeploy contention, scaling hot spot, team coupling, blast radius
Merge signalsNanoservices, chatty graph, lock-step deploys, duplicated data, ops burden
Split safelyBranch by abstraction, strangler fig, parallel run, expand/contract
Remote clientTimeout, retry only transient errors, backoff, idempotency key, same error contract
MeasureDORA lead time, deploy frequency, change fail rate, recovery time, rework rate
ADRGoal with a number; "revisit if" signal; superseded, never deleted

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — 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 ​

TermMeaning
MonolithOne deployable unit containing all functionality
Modular monolithOne deployable cut into modules with public APIs, private internals and owned data
MicroservicesIndependently deployable services organised around business capabilities, each owning its data
Microservice premiumRecurring extra cost of running a distributed system (Fowler)
Monolith firstStart with one deployable, split by observed boundaries (Fowler)
DuolithFowler's joke name for starting with two coarse-grained services
Sacrificial architectureAn architecture built expecting to be replaced once it succeeds
Logical boundaryHow code is divided: modules, interfaces
Physical boundaryHow code is deployed: processes, hosts
Service WeaverGoogle's framework for logical monoliths with runtime placement; maintenance mode Dec 2024, archived Mar 2026
Granularity disintegratorA reason to split a service (Hard Parts)
Granularity integratorA reason to keep or put services together (Hard Parts)
Conway's lawSystems copy the communication structure of the organisation that builds them
Inverse Conway maneuverShaping teams to get the architecture you want
Cognitive loadHow much a team must hold in mind to own its part
Stream-aligned teamTeam aligned to a flow of business work (Team Topologies)
Platform teamTeam providing internal services that reduce other teams' load
DORA metricsChange lead time, deployment frequency, failed deployment recovery time, change fail rate, deployment rework rate
Deploy contentionChanges waiting for a shared release
Scaling asymmetry / hot spotOne part needs much more or different capacity
Blast radiusHow much breaks when one part fails
Fault isolationKeeping a failure inside one part
Distributed monolithServices that must change or deploy together
NanoserviceA service too small to own a business capability
Chatty call graphMany synchronous hops per user request
Strangler figGrow a new system around the old one route by route
Branch by abstractionIntroduce an interface as a seam, swap implementations behind it while releasing
Parallel runRun old and new paths, compare, serve the old result
Expand and contractParallel change: expand the API, migrate callers, contract
Change data capture (CDC)Streaming database changes to other systems
Fitness functionAutomated check that an architectural rule holds
PackwerkShopify's static checker for Rails component boundaries
Idempotency keyClient-supplied key letting the server deduplicate retried requests
OutboxWriting events in the same local transaction as the data, relayed later
Hybrid topologyModular core plus a few extracted services
Regulatory isolationSeparate deployables/data so an audit scope (PCI DSS, residency) stays small
Technology heterogeneityDifferent languages or runtimes per part
ADRArchitecture Decision Record: one short file per significant decision

References ​

Built by Morteza Negahi