Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 1

Why modular first: cost of distribution versus cost of coupling

Separate the two bills a growing codebase runs up, the cost of coupling and the cost of distribution, measure the first one from version control history, and decide when a modular monolith is the right first step and when it is the wrong one.

Contentsand lesson path

What you will learn

  • Map bounded contexts to modules, each with a public API, hidden internals and a module-owned schema.

01. Why it matters

Suppose a bike-rental company, Spokes, runs its platform as one Python application with one PostgreSQL database and nine developers. Last month a change to the per-minute tariff broke the ride-history screen, and a fix for dock sensors failed twelve unrelated tests. In the retrospective someone says what many teams say at this point: "Let's move to microservices."

Before agreeing, separate two bills that a growing system runs up. The cost of coupling is what one change drags along with it: other files to edit, other tests to fix, other people to ask. The cost of distribution is what every process boundary charges, all the time: calls that fail or slow down, one more thing to deploy and watch, data that no longer changes in one transaction. Microservices can lower the first bill only if their boundaries are in the right places, and they always add the second. A modular monolith keeps one deployable unit and works on the first bill alone.

The single-deployable styles lesson introduced the modular monolith, and the price of distribution measured a network hop. Here the question is which bill your team is actually paying.

02. The cost of coupling, and how to see it

Two pieces of code are coupled when a change to one forces a change to the other; connascence grades the kinds. Coupling shows up as symptoms before anyone measures it: an edit in one area breaks tests in another, and a new developer must understand the whole system before changing one part. Shopify's Rails monolith, which more than a thousand developers have worked on, hit exactly these tripwires in 2016: harmless-looking changes set off cascades of unrelated test failures.

Version control history gives a cheap first measure. If many commits touch the same pair of modules, that pair is coupled, whatever the folder names say. The script below reads git log output, maps each file to a module by its path, and counts the modules each commit touches. It needs Python 3.10 or newer.

Python · cochange.py
"""cochange.py: how often does one change cross module boundaries?

Input: the output of  git log --no-merges --name-only --format=--%h
Usage: python3 cochange.py [depth] < history.txt   (depth 2 = src/<module>/...)
"""
import sys
from collections import Counter
from itertools import combinations

DEPTH = int(sys.argv[1]) if len(sys.argv) > 1 else 2


def module_of(path: str) -> str | None:
    parts = path.split("/")
    return "/".join(parts[:DEPTH]) if len(parts) > DEPTH else None


commits: list[set[str]] = []
for line in sys.stdin:
    line = line.rstrip("\n")
    if line.startswith("--"):  # a new commit starts
        commits.append(set())
    elif line and commits and (module := module_of(line)):
        commits[-1].add(module)

touched = [c for c in commits if c]
if not touched:
    sys.exit("no commits touched a module at this depth")
spread = Counter(min(len(c), 3) for c in touched)
pairs = Counter(p for c in touched for p in combinations(sorted(c), 2))

print(f"commits that touch modules: {len(touched)}")
for size, label in ((1, "1 module"), (2, "2 modules"), (3, "3 or more")):
    print(f"  {label:<10} {spread[size]:>3}  {spread[size] / len(touched):>4.0%}")
print("pairs that most often change together:")
for (a, b), n in pairs.most_common(3):
    print(f"  {a} + {b}: {n} commit{'s' if n > 1 else ''}")

The sample history is a scenario: twelve Spokes commits in the exact format that git log --no-merges --name-only --format=--%h prints.

Text · history.txt (sample data)
--e41c9a0

src/rentals/rides.py
src/billing/tariffs.py
--9b20d17

src/fleet/docks.py
--77fa3e1

src/rentals/rides.py
src/billing/invoices.py
src/notify/receipts.py
--c05d2b8

src/accounts/riders.py
--5a8e6f4

src/rentals/pricing_rules.py
src/billing/tariffs.py
--d3b9915

src/notify/sms.py
--0f61c27

src/rentals/rides.py
src/billing/invoices.py
--8e4472b

src/fleet/bikes.py
src/fleet/docks.py
--4c19ad3

src/rentals/rides.py
src/billing/tariffs.py
tests/test_rides.py
--b6d0e58

src/accounts/riders.py
src/notify/receipts.py
--2f7a3cc

src/billing/invoices.py
--a90b5d1

src/rentals/rides.py
src/fleet/bikes.py
src/billing/tariffs.py
README.md
Terminal
python3 cochange.py < history.txt
Expected output
commits that touch modules: 12
  1 module     5   42%
  2 modules    5   42%
  3 or more    2   17%
pairs that most often change together:
  src/billing + src/rentals: 6 commits
  src/billing + src/notify: 1 commit
  src/notify + src/rentals: 1 commit

Seven of the twelve commits cross a module boundary, and six of those touch billing and rentals together. That is the coupling bill in numbers: either the boundary between the two is in the wrong place, or one reaches into the other's internals. Now predict what splitting would do: if billing became its own service, each of those six commits would become a change to two deployables, with an API version to agree on and two releases to order.

Treat the numbers as a prompt for questions, not a verdict: a commit can bundle unrelated edits, a rename touches many files, and twelve commits are far too few. On a real repository, pipe git log --no-merges --name-only --format=--%h -n 500 into the script and set the depth to where your modules live (2 for src/billing/...).

03. The cost of distribution, and why splitting moves coupling

The distribution bill is paid per boundary, whether or not the code changes: timeouts, retries and a plan for repeated requests on every call; a pipeline, monitoring and on-call for every deployable; an outbox or a saga wherever a rule spans two services; and a new API version plus ordered releases to move a responsibility between services. Shopify named several of them in 2019 when it chose a modular monolith over microservices: a pipeline and infrastructure for each service, latency and lost reliability on every network call, and tedious refactors across services.

The two bills are not independent, and this is the central point of the lesson: splitting a system does not remove coupling; it moves it onto the network. If billing and rentals change together in half of all commits, two services would change together too, only now with an API negotiation and two deploys each time. Martin Fowler argued in 2015 that refactoring between services is much harder than inside a monolith and that boundaries are rarely right at the start, so it is cheaper to find them inside a monolith first. He also wrote that he had heard fewer stories than he would like of a carefully modular monolith later splitting cleanly, so treat "easy extraction later" as a goal you design for, not a promise.

The bill can push teams back, too. In 2018 Segment described how its event-delivery product had grown to more than 140 services, with three full-time engineers spending most of their time keeping the system alive, and how it merged them into one service.

04. What a modular monolith buys, and what it cannot

A monolith is a system with exactly one deployment unit, as Kamil Grzybek defines it; whether its inside is tangled is a separate question. A modular monolith adds enforced boundaries between business areas: each module has a public interface, hides everything else and owns its data. When the boundaries are in the right places, it buys you this:

  • Most changes stay inside one module.
  • Moving a boundary is a refactoring: one commit and one deploy, checked by the tests.
  • Calls between modules are function calls, and one local transaction is still there when a rule needs it.
  • Boundaries can be checked in every build, and each module is a seam for a later extraction.

Because all modules share one process and one release, it cannot give you:

  • Separate deployment. Every release ships every module.
  • Separate scaling. All modules get the same number of copies, sized for the hungriest one.
  • Fault isolation. A memory leak or a crash in one module stops the process for all of them. Segment accepted this knowingly: after its merge, a bug that crashed one destination crashed the service for every destination.
  • A separate runtime or security perimeter: one language runtime, one set of libraries, one set of credentials.

Note the condition: when the boundaries are in the right places. If Spokes simply merged billing and rentals, the co-change script would count most commits as single-module, yet the coupling would be unchanged, only hidden inside a bigger module. Merging is right when the two really are one bounded context, and wrong when it only improves a number. Enforcement is not free either: Shopify's 2024 retrospective on Packwerk, its boundary checker, reports that isolating one base package took months.

05. When modular first is the wrong choice

Decide on needs you can show today, not on needs you hope to have. These are real signals that at least one part should run on its own:

  • Very different load or hardware, measured, such as a video-transcoding step that needs GPUs.
  • Teams waiting on each other's releases, measured in lead time, and the maturity to run more deployables: automated pipelines, monitoring, an on-call rota.
  • An isolation requirement: card data in a small audited scope, third-party code kept out of your process, or one part that must work while the rest is down.
  • A runtime the rest cannot host, such as a model server with its own hardware.

"We will need to scale", "services are more modern" and "teams want autonomy" are hopes until someone shows the numbers. Even a real signal usually justifies extracting only the part that needs it; Fowler calls this peeling services off at the edges. Choosing a style for three scenarios practises this weighing.

At the other end, a prototype that may be thrown away, or a tool kept by one or two people, gains little from enforced boundaries; tidy folders and code review are enough until the co-change numbers or the team size say otherwise.

06. Check your understanding

Practice check · 2 questions

Coupling, distribution and one process

Two predictions about Spokes. Pick the best answer for each.

Q1. Spokes now has five well-enforced modules running in one process. A bug in the PDF receipt renderer in `notify` leaks memory until the operating system kills the process. What happens to riders who are starting rides at that moment?
Q2. Six months after modularising, the team decides that discount rules belong in `billing`, not in `rentals`. How does the work compare with making the same move between two separate services?
Practice only: not graded, not saved, not evidence.

07. Apply it

The practice task of this skill starts from a sample monolith. Before you split it, find out which bill it pays.

  1. Run cochange.py on the last 300 to 500 commits of a repository you can read (your own, or an open-source application with one folder per feature), at the depth where its modules live.
  2. For the three pairs that change together most, open a few of their commits and decide: one capability split across two folders, a boundary in the wrong place, or one module reaching into another's internals.
  3. Write a short "modular first?" note: which of the real signals from this lesson are present, with evidence, and which are only hopes. Keep it; lesson 5 turns it into a plan.

08. Review prompt

Without looking back, explain the difference between the cost of coupling and the cost of distribution, and why splitting a tangled system into services moves coupling instead of removing it. Say what co-change data can and cannot tell you. Name what a modular monolith gives you only when its boundaries are right, and three things it cannot give you because its modules share a process. Finally, list the real signals that would make you run one part separately, and how you would tell a real signal from a hope.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check