Lesson 17 of 28Architecture
The Modular Monolith
Build one deployable with real internal boundaries: public module APIs, owned data, events between modules, CI enforcement, and a clean extraction path.
Your company has a three-year-old Django or Next.js monolith. Every feature now touches six folders, a "small" change to orders breaks invoices, and someone has proposed rewriting it as twelve microservices. Monolith vs Microservices made the case for a middle path: keep one deployable, but give it real internal walls. This lesson is the how. You will see how to choose modules, lay out the folders, let modules talk without tangling, split the data, and make CI fail when someone crosses a wall. This is the architecture most growing product companies actually run, and "how would you stop a monolith turning into a big ball of mud?" is a very common senior interview question.
What makes a monolith modular
A modular monolith is one deployable unit, made of modules that each have:
- A public API: a small set of functions, types and events other modules may use.
- Private internals: everything else, which no other module may import.
- Owned data: tables only that module reads and writes.
All three are needed. Folders without enforced imports are just a tidy big ball of mud. Enforced imports with shared tables still couple everything through the database.
Compare it with the two failure modes on either side:
| Big ball of mud | Modular monolith | Distributed monolith | |
|---|---|---|---|
| Deployables | One | One | Many |
| Boundaries | None | Enforced in code and data | On paper only |
| A change to billing | Ripples anywhere | Stays in billing unless its API changes | Needs coordinated deploys of several services |
| Cross-module call | Any function | Public facade or event | Network call |
The distributed monolith is what teams often get when they split too early: services that must be deployed together, share a database, and call each other synchronously in long chains. It has all the costs of microservices and none of the independence. A modular monolith is the safer place to learn where the boundaries really are.
Choosing the modules
Draw boundaries around business capabilities, not technical layers. orders, billing, catalog, shipping and identity are modules. models, utils and services are not.
Heuristics that work in practice:
- Things that change together live together. Look at the last 50 pull requests. If every billing ticket also edits
orders/, the line is in the wrong place. - One word, one meaning. If "customer" means a person with a basket in one place and a legal entity with a VAT number in another, those are two modules with two models. Domain-driven design calls these bounded contexts, and the next unit covers them in depth.
- One owner per piece of data. Who is allowed to change an invoice's status? That module owns the invoice table.
- Fewer, bigger modules first. Five modules you can defend beat twenty that fight each other. Splitting a module later is easier than merging two that grew apart.
Folder layout and public APIs
In Python, a module is a package. Its __init__.py re-exports the public API, and everything else lives in a private subpackage such as _internal. The leading underscore is a convention, so you back it up with a linter.
- shop/
- orders/
- __init__.pypublic: place_order, get_order, OrderPlaced
- events.pypublic event dataclasses
- _internal/
- models.pyORM tables in the orders schema
- service.pyuse cases
- repository.py
- billing/
- __init__.pypublic: create_invoice, InvoicePaid
- events.py
- _internal/
- models.pytables in the billing schema
- stripe_gateway.py
- catalog/
- __init__.py
- _internal/
- shared/
- event_bus.pythe only shared infrastructure
- money.pya tiny shared kernel
- main.pycomposition root: wires modules and subscriptions
from shop.billing.events import InvoicePaid
from shop.billing._internal.service import create_invoice, invoice_status
__all__ = ["InvoicePaid", "create_invoice", "invoice_status"]In TypeScript, the two common shapes are an Nx (or Turborepo) workspace with one library per module, or plain workspace packages. Either way, each module is a package with an exports field in its package.json. Node and TypeScript (with moduleResolution set to bundler, node16 or nodenext) refuse deep imports that are not listed, so @shop/billing/src/internal/stripe simply does not resolve.
{
"name": "@shop/billing",
"exports": {
".": "./src/index.ts",
"./events": "./src/events.ts"
}
}Keep the public API small and boring: functions that take and return plain data (IDs, DTOs), never ORM objects. If orders gets a live Invoice ORM object back, it can lazy-load billing's tables through it, and the boundary is gone.
How modules talk
Modules have two ways to interact inside one process.
A synchronous call through the facade. orders calls billing.create_invoice(order_id, cents) and gets an ID back. Use this when the caller needs the answer now to continue: a price, a permission check, an ID. It is simple, fast and easy to debug. The cost is coupling: orders now knows billing exists and must handle its errors.
An in-process domain event. billing publishes InvoicePaid and does not know who listens. orders marks the order paid; notifications sends a receipt. Use events when the publisher does not need a reply and several modules may react. The publisher stays ignorant of its listeners, so adding a new reaction touches only the new module.
The subtle part is when handlers run. If handlers run inside the publisher's transaction, a failing email handler rolls back a successful payment. If they run after commit, a crash between commit and dispatch loses the event. The usual answer is: dispatch after commit, make handlers idempotent, and for events that must not be lost, write them to an outbox table in the same transaction (the outbox pattern from Event-Driven Architecture).
Press Run (⌘ Enter) to see what happens.For order 2 the receipt handler fails, but billing has already committed and orders still moves to paid. One listener's failure stays its own problem.
What does this print?
handlers = []
def publish(event):
for h in handlers:
h(event)
log = []
def pay(order):
log.append("charged")
publish(order)
log.append("confirmed")
handlers.append(lambda e: log.append("stock reserved"))
handlers.append(lambda e: 1 / 0)
try:
pay("o1")
except ZeroDivisionError:
log.append("error")
print(log)Data ownership
The database is where most modular monoliths quietly fail. The rules:
- One schema per module in the same database (
orders.*,billing.*). It costs nothing and makes ownership visible in every query. - Only the owner writes to its tables. Others ask through the API or react to events.
- No cross-module joins in application code.
SELECT ... FROM orders.orders JOIN billing.invoiceswelds the two modules together: billing can no longer rename a column, and you can never split them. - Foreign keys across modules are a smell. An
orders.order_idcolumn in billing is fine as a plain ID. A database-enforced foreign key to another module's table is a hidden dependency that will block extraction.
When you genuinely need combined data, say an admin report of orders with payment status, pick one of these, roughly in this order:
- Compose in code: fetch orders, then call
billing.invoice_statuses(order_ids)with one batched call. - A read-only view owned by the module that publishes it (
billing.invoice_summary), treated as part of its public API. - A read model: a reporting module that listens to events from both and keeps its own denormalised table.
CREATE SCHEMA billing;
CREATE TABLE billing.invoices (
id bigint PRIMARY KEY,
order_id bigint NOT NULL, -- a plain id, no FOREIGN KEY into orders
cents bigint NOT NULL,
status text NOT NULL
);
-- Published, read-only surface for other modules
CREATE VIEW billing.invoice_summary AS
SELECT order_id, status FROM billing.invoices;Teams that want the database to enforce it can give each module its own Postgres role with grants only on its own schema. That needs a connection pool per module, so many teams settle for a CI test that scans each module's SQL and migrations for other schemas' names.
Enforcement: make CI fail
Boundaries you only document will erode under deadline pressure. Make a boundary breach a red build.
- Python: import-linter. An
independencecontract says listed modules must not import each other at all. Aforbiddencontract bans imports of another module's_internal. - TypeScript: dependency-cruiser or Nx. Nx's
@nx/enforce-module-boundariesESLint rule uses tags (scope:billing,type:feature) to say which libraries may depend on which. dependency-cruiser does the same with path rules for repos without Nx. - Ruby: Packwerk, which Shopify built and open-sourced for its own monolith. It checks declared dependencies between packages; privacy checks moved to an extension in later versions.
- Java: Spring Modulith. A test calling
ApplicationModules.of(Application.class).verify()fails when one module touches another's internal packages. Worth knowing even if you write Python, because interviewers from Java shops will ask.
[tool.importlinter]
root_package = "shop"
[[tool.importlinter.contracts]]
name = "Feature modules do not import each other's internals"
type = "forbidden"
source_modules = ["shop.orders", "shop.catalog", "shop.notifications"]
forbidden_modules = ["shop.billing._internal"]
[[tool.importlinter.contracts]]
name = "Catalog and notifications are independent"
type = "independence"
modules = ["shop.catalog", "shop.notifications"]When you adopt this in an existing codebase, you will have hundreds of violations on day one. Record them as an allowed baseline (import-linter supports ignored imports, Packwerk has a todo file), fail only on new violations, and burn the list down over time.
The extraction path
A good modular monolith makes extraction boring. If a module's public API already takes and returns plain data and its integration with others is mostly events, turning it into a service is a matter of changing the transport.
Step 1
Clean the seams
Zero import violations into billing. No cross-schema joins or foreign keys. The public API takes and returns only IDs and DTOs.
Step 2
Make calls message-shaped
Replace chatty calls with coarse ones and in-process events. Make every handler idempotent, because the network will deliver some events twice.
Step 3
Move the data
Point the billing schema at its own database. Because nobody else touched it, nothing else changes.
Step 4
Swap the transport
The billing facade inside the monolith becomes a thin HTTP or gRPC client. Events go through the outbox to a broker instead of the in-process bus.
Step 5
Deploy separately
Billing now has its own pipeline, scaling and on-call. Add timeouts, retries and tracing that the in-process call never needed.
Extract only when you can name the reason. The good ones:
- Independent scaling: one module needs 40 instances or a GPU while the rest needs 3.
- Team autonomy: a separate team owns it and is blocked by the shared release train.
- Different release cadence or risk: a payments module under stricter change control than the marketing pages.
- Different technology: an ML model that must run in Python next to a TypeScript app.
"It would be cleaner" is not on the list. A clean module is already clean.
Order these steps for turning a big ball of mud into a modular monolith.
- Tap the steps below in the right order.
Real examples, with nuance
Shopify runs one of the largest Rails monoliths in the world. Rather than split it into services, it reorganised the codebase into components with explicit boundaries (they called it a componentized monolith) and built Packwerk to check dependencies between them. The lesson they shared is that boundaries had to be enforced by tooling, and that untangling existing dependencies was the long, slow part.
Amazon Prime Video published a post in 2023 about its audio and video quality monitoring tool. The first version was distributed: AWS Step Functions orchestrating many serverless components, passing video frames through S3. At scale, the orchestration and data transfer costs and scaling limits hurt. They moved the pipeline into a single process running on containers and reported cutting that tool's infrastructure cost by about 90 percent. It was quoted everywhere as "Amazon goes back to the monolith". The accurate reading is narrower: one data-heavy pipeline, whose parts exchanged large amounts of data at high frequency, was a poor fit for fine-grained network boundaries. Prime Video as a whole still runs many services. The lesson is to put network boundaries where the data flow between parts is small, not to ban services.
Match each tool to what it enforces.
- modular monolith
- One deployable made of modules with enforced public APIs, private internals and owned data.
- module facade
- The small public API a module exposes, usually plain functions that take and return IDs and DTOs.
- in-process event
- A domain event published and handled inside the same process, letting modules react without knowing each other.
- schema per module
- Each module's tables live in their own database schema that only that module writes to.
- distributed monolith
- Services that are deployed separately but still coupled, so they must change and deploy together.
- boundary check
- A CI rule, such as an import-linter contract, that fails the build when one module reaches into another.
- extraction
- Turning a well-bounded module into a separate service by changing its transport and moving its data.