Module anatomy, owned tables and component principles
Give each module a public API, hidden internals and tables only it writes, see in PostgreSQL what a schema per module does and does not enforce, then measure the graph between modules with the acyclic, stable-dependencies and stable-abstractions principles.
Contentsand lesson path
On this page
- Why it matters
- Anatomy of a module
- Owned tables: one writer per table
- Three principles for the graph between modules
- Measuring the graph: instability, abstractness, distance
- Check your understanding
- Apply it
- Review prompt
Lessons of Modular Monolith
- Why modular first: cost of distribution versus cost of coupling Concept · 15 min
- Module anatomy, owned tables and component principles Concept · 25 min
- Enforcing boundaries with architecture tests Lab · 25 min
- Cross-module calls, in-process events and transactions Concept · 20 min
- Carving a big ball of mud into modules Worked example · 30 min
- Modularity check Knowledge check · 6 questions
What you will learn
- Map bounded contexts to modules, each with a public API, hidden internals and a module-owned schema.
- Enforce module boundaries, including acyclic and stable dependency directions, with automated dependency checks that fail the build.
01. Why it matters
Suppose Spokes, the bike-rental platform from lesson 1, creates folders named accounts, fleet, rentals, billing and notify and calls the result modular. A month later a search tells another story: billing imports the ride class from inside rentals, a report joins tables of four modules, and the co-change numbers have not moved. A folder with a business name is not yet a module.
This lesson gives a module its three parts (a public API, hidden internals and data it owns), then turns to the graph between modules, where three principles from Robert C. Martin tell you which dependencies are healthy.
02. Anatomy of a module
spokes/
billing/
__init__.py
api.py public: functions, plain data classes, events it publishes
_tariffs.py private: pricing rules
_store.py private: the only code that touches billing's tables
migrations/ changes to billing's own schema
rentals/ ...
app.py composition root: the one place that wires modules togetherThe public API is the only part other modules may use: in Spokes, api.py with a few functions such as charge_for(ride_id), small frozen data classes for what goes in and out, and the events the module publishes, such as RideEnded. Keep it small and plain. With plain data instead of ORM objects, callers cannot reach through a returned object into your tables, and the API could later travel over a network unchanged.
The internals are everything else: rules, calculations, persistence code. Other modules must not import them, so you can rewrite them without asking anyone. Python has no enforced privacy, so Spokes marks internals with a leading underscore, and lesson 3 turns that hint into a build check; Java, C# and TypeScript have stronger tools, such as package-private classes, internal and package.json exports.
From bounded contexts to modules. Start from the contexts of the context map lab: one context usually becomes one module, because a context is where one model applies and where changes cluster. Avoid one module per table or entity (customer, order, product): a change such as "apply a promotion at checkout" then cuts across all of them. Names mislead too. Shopify's Packwerk retrospective describes a "shop billing settings" model holding a fraud flag; it sat in the billing package because of its name, although every request needed it. Inside a module, organise code as suits it, for example with ports and adapters.
03. Owned tables: one writer per table
Each table has exactly one owning module, and only that module writes to it. Others call the owner's API, react to its events, or read a view the owner publishes on purpose. Owning its data lets a module change its tables, or one day move them, without asking anyone. Two habits break ownership quietly. A join across modules ties a query to two table layouts, so a rename in one breaks the other. A foreign key across modules lets the database refuse the owner's deletes or moves on behalf of a table it does not control. Dropping that key has a price: the database no longer checks that every billing.charges.ride_id names a ride, so the owner's rules must.
In PostgreSQL a schema is a namespace inside one database, so one schema per module shows ownership: rentals.rides, billing.charges. A schema only groups names; it adds no storage or speed. Access control comes from roles: apart from superusers, a role cannot use objects in a schema it does not own until the owner grants USAGE on the schema and privileges on each object. The script gives each module a role, lets billing read only a view that rentals publishes, and tries what billing should not do.
"""ownership.py: what one schema and one role per module block, and what they do not.
Needs a PostgreSQL server at DATABASE_URL, and: pip install "psycopg[binary]"
"""
import os
import psycopg
SETUP = """
CREATE ROLE rentals_app; CREATE ROLE billing_app; CREATE ROLE monolith_app;
CREATE SCHEMA rentals AUTHORIZATION rentals_app;
CREATE SCHEMA billing AUTHORIZATION billing_app;
SET ROLE rentals_app;
CREATE TABLE rentals.rides (id bigint PRIMARY KEY, rider_id text, minutes int);
INSERT INTO rentals.rides VALUES (1, 'r1', 12), (2, 'r2', 31);
CREATE VIEW rentals.ride_minutes AS SELECT id AS ride_id, minutes FROM rentals.rides;
GRANT USAGE ON SCHEMA rentals TO billing_app; -- may look inside ...
GRANT SELECT ON rentals.ride_minutes TO billing_app; -- ... but read only this view
SET ROLE billing_app;
CREATE TABLE billing.charges (ride_id bigint PRIMARY KEY, cents int); -- id, no FK
INSERT INTO billing.charges VALUES (1, 400);
RESET ROLE;
GRANT rentals_app, billing_app TO monolith_app; -- one role that is every module
"""
JOIN = """SELECT c.ride_id, r.rider_id
FROM billing.charges c JOIN rentals.rides r ON r.id = c.ride_id"""
PROBES = [
("billing_app", "read the published view",
"SELECT ride_id, minutes FROM rentals.ride_minutes ORDER BY ride_id"),
("billing_app", "join the private rentals table", JOIN),
("billing_app", "add a foreign key into rentals",
"ALTER TABLE billing.charges ADD FOREIGN KEY (ride_id) REFERENCES rentals.rides"),
("monolith_app", "run the same join", JOIN),
]
with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as conn:
conn.execute(SETUP)
for role, action, sql in PROBES:
conn.execute(f"SET ROLE {role}")
try:
cur = conn.execute(sql)
rows = cur.fetchall() if cur.description else "done"
print(f"{role:<12} {action}: ok {rows}")
except psycopg.Error as err:
print(f"{role:<12} {action}: ERROR {err.diag.message_primary}")
conn.execute("RESET ROLE")It needs a throwaway PostgreSQL server. npx -y @electric-sql/[email protected] --port=5432 starts PGlite, PostgreSQL compiled to WebAssembly, in memory; the output below comes from it (PGlite 0.6.0, reporting PostgreSQL 19.0). A Docker server (docker run --rm -d -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres:18) should behave the same, but it was not used here and may word errors differently.
python3 -m pip install "psycopg[binary]==3.3.9"
export DATABASE_URL=postgresql://postgres:[email protected]:5432/postgres
python3 ownership.pybilling_app read the published view: ok [(1, 12), (2, 31)]
billing_app join the private rentals table: ERROR permission denied for table rides
billing_app add a foreign key into rentals: ERROR permission denied for table rides
monolith_app run the same join: ok [(1, 'r1')]Billing reads the view, but the join and the foreign key are refused, because billing's role was never granted rides. The last line is the warning: a role that may act as every module runs the same join. With one role for the whole application, schemas document ownership without enforcing it; the build check of lesson 3 and code review must do that. One role per module is stronger, but costs separate connection settings or a SET ROLE per transaction.
The view is now part of the rentals API: rentals may change its tables freely as long as the view keeps its columns and their meaning.
04. Three principles for the graph between modules
Robert C. Martin stated three principles for the graph between packages in the mid-1990s, for separately released packages (he later named JAR files and DLLs as examples). Inside one deployable they decide which modules you can change, test or extract on their own.
- Acyclic Dependencies Principle (ADP). No cycles between modules. If
rentalsdepends onbillingandbillingonrentals, neither can be tested or extracted without the other; they are one module with two names. - Stable Dependencies Principle (SDP). Depend in the direction of stability. A module that many others use is hard to change, so it should depend only on modules at least as stable as itself.
- Stable Abstractions Principle (SAP). The more stable a module, the more abstract it should be, so that others can extend it without changing it.
Three common moves break a cycle. Move the shared piece into a lower module that both may use. Invert one dependency: the module that should stay independent defines an interface (in Python, a Protocol) and the other implements it. Or replace a call with an event. Merging the two is honest when they turn out to be one bounded context; switching the check off, or keeping the cycle because both ship together, leaves the knot in place.
05. Measuring the graph: instability, abstractness, distance
Martin's 1994 paper on design quality metrics turns these principles into numbers for each module:
- Ca (afferent couplings): how many classes outside the module depend on classes inside it.
- Ce (efferent couplings): how many classes inside the module depend on classes outside it.
- I = Ce / (Ca + Ce), the instability: 0 means only incoming dependencies (hard to change), 1 means nothing depends on it (free to change).
- A, the abstractness: abstract classes divided by all classes, from 0 (all concrete) to 1.
- D = abs(A + I − 1), the normalised distance from the main sequence, the line A + I = 1. Stable and abstract (I = 0, A = 1) and unstable and concrete (I = 1, A = 0) both lie on it.
The script computes them for Spokes from a hand-written list of which class uses which (scenario data), checks the module graph for cycles with graphlib, and flags every edge from a more stable module to a less stable one.
"""metrics.py: component metrics (Martin, 1994) for the Spokes modules.
Ca = classes outside the module that depend on classes inside it
Ce = classes inside the module that depend on classes outside it
I = Ce / (Ca + Ce) A = abstract classes / all classes D = |A + I - 1|
"""
import sys
from graphlib import CycleError, TopologicalSorter
MODULES = { # module -> {class: is_abstract}
"accounts": {"RiderAccount": False, "AccountsApi": False},
"fleet": {"Bike": False, "Dock": False, "FleetApi": False},
"rentals": {"Ride": False, "RentalsApi": False, "RideEnded": False},
"billing": {"Charge": False, "Tariff": False, "BillingApi": False},
"notify": {"ReceiptMailer": False, "AlertSender": False},
}
USES = [ # (class, class it depends on)
("RentalsApi", "FleetApi"), ("RentalsApi", "AccountsApi"), ("Ride", "Bike"),
("Dock", "Bike"), ("Tariff", "RiderAccount"), ("ReceiptMailer", "Charge"),
("ReceiptMailer", "RiderAccount"),
("RentalsApi", "BillingApi"), # rentals charges the rider when a ride ends
("BillingApi", "Ride"), # billing reads ride minutes
("FleetApi", "AlertSender"), # fleet sends low-battery alerts itself
]
if sys.argv[1:] == ["after"]: # the two fixes described in the lesson
MODULES["billing"]["RideEndedHandler"] = False
MODULES["fleet"]["BatteryAlerts"] = True # a Protocol owned by fleet
USES = USES[:7] + [
("RideEndedHandler", "RideEnded"), ("RideEndedHandler", "Tariff"),
("FleetApi", "BatteryAlerts"), ("AlertSender", "BatteryAlerts"),
]
home = {cls: mod for mod, classes in MODULES.items() for cls in classes}
cross = [(a, b) for a, b in USES if home[a] != home[b]]
metrics = {}
print("module Ca Ce I A D")
for mod, classes in MODULES.items():
ca = len({a for a, b in cross if home[b] == mod})
ce = len({a for a, b in cross if home[a] == mod})
i = ce / (ca + ce) if ca + ce else 0.0
a = sum(classes.values()) / len(classes)
metrics[mod] = i
print(f"{mod:<9}{ca:>3}{ce:>4}{i:>6.2f}{a:>6.2f}{abs(a + i - 1):>6.2f}")
graph = {mod: sorted({home[b] for a, b in cross if home[a] == mod}) for mod in MODULES}
try:
order = list(TopologicalSorter(graph).static_order())
print("cycles: none; stable first:", " < ".join(order))
except CycleError as err:
print("cycle:", " -> ".join(err.args[1]))
for src in MODULES:
for dst in graph[src]:
if metrics[src] < metrics[dst]:
print(f"SDP: {src} (I={metrics[src]:.2f}) depends on less stable "
f"{dst} (I={metrics[dst]:.2f})")python3 metrics.pymodule Ca Ce I A D
accounts 3 0 0.00 0.00 1.00
fleet 2 1 0.33 0.00 0.67
rentals 1 2 0.67 0.00 0.33
billing 2 2 0.50 0.00 0.50
notify 1 1 0.50 0.00 0.50
cycle: rentals -> billing -> rentals
SDP: fleet (I=0.33) depends on less stable notify (I=0.50)
SDP: billing (I=0.50) depends on less stable rentals (I=0.67)accounts is as stable as a module gets (I = 0): three classes elsewhere use it, and it uses nothing. The cycle is the one the co-change data hinted at: rentals calls billing to charge a ride, and billing reads the ride class for its minutes. The SDP lines name two edges that point the wrong way: stable fleet uses notify, which changes with every message edit, and billing's edge back into rentals. python3 metrics.py after applies two fixes:
- Billing subscribes to a
RideEndedevent that carries the minutes, so rentals no longer calls billing and billing no longer reads the ride class. - Fleet defines a small
BatteryAlertsProtocol and calls it, andnotifyimplements it, so the edge now points fromnotifytofleet.
module Ca Ce I A D
accounts 3 0 0.00 0.00 1.00
fleet 3 0 0.00 0.25 0.75
rentals 1 2 0.67 0.00 0.33
billing 1 2 0.67 0.00 0.33
notify 0 2 1.00 0.00 0.00
cycles: none; stable first: accounts < fleet < rentals < billing < notifyThe cycle and both findings are gone, and fleet's abstractness rose to 0.25. Yet accounts and fleet remain far from the main sequence (D = 1.00 and 0.75). Martin's paper warns that "a metric is not a god": a stable, concrete module hurts only when it must change. If accounts changed every week, each change would ripple into three other modules, and the fix would be to shrink what others depend on to a small, stable API and move the volatile rules out. If it barely changes, leave it alone.
Use the numbers to start conversations, not as targets: tools count classes, files or import edges, so compare values only within one tool. For TypeScript, dependency-cruiser computes instability and has a moreUnstable rule that fails the build on SDP violations.
06. Check your understanding
07. Apply it
Continue with the sample monolith of the practice task.
- For each planned module (at least three), write its public API (functions, data classes, events) and the tables it owns, one writer per table. Note every cross-module join or foreign key you find.
- Count Ca and Ce from the imports, by hand or by adapting
metrics.py, and look for cycles and for edges that point towards less stable modules. - For each finding, choose one fix (move, invert, event or merge) and write one line on why it suits that pair.
08. Review prompt
Without looking back, name the three parts of a module and say why its API should use plain data. Explain what a schema per module enforces in PostgreSQL and what it does not, and why cross-module joins and foreign keys break ownership. State ADP, SDP and SAP in your own words, give three ways to break a cycle, define Ca, Ce, I, A and D, and say when a module far from the main sequence is a problem.
References
- Modular Monolith: A Primer (Kamil Grzybek)
- OO Design Quality Metrics: An Analysis of Dependencies (Robert C. Martin, 1994)
- Principle of OOD #8: the stable dependencies principle (Robert C. Martin, comp.object, 1995)
- Schemas: privileges and usage patterns (PostgreSQL documentation)
- Privileges (PostgreSQL documentation)
- A Packwerk Retrospective (Shopify Engineering, 2024)
- PGlite: PostgreSQL in WebAssembly
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.