Skip to content

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.

12 min read0/4 questions

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:

  1. A public API: a small set of functions, types and events other modules may use.
  2. Private internals: everything else, which no other module may import.
  3. 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 mudModular monolithDistributed monolith
DeployablesOneOneMany
BoundariesNoneEnforced in code and dataOn paper only
A change to billingRipples anywhereStays in billing unless its API changesNeeds coordinated deploys of several services
Cross-module callAny functionPublic facade or eventNetwork 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.

A Python modular monolith
  • 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
shop/billing/__init__.py
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.

packages/billing/package.json
{
  "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).

Python
from collections import defaultdictfrom dataclasses import dataclass # ---- shared kernel: a tiny in-process event busclass EventBus: def __init__(self): self.handlers = defaultdict(list) self.after_commit = [] def subscribe(self, event_type, handler): self.handlers[event_type].append(handler) def publish(self, event): # Queue it. Handlers run only after the publisher's transaction commits. self.after_commit.append(event) def flush(self): while self.after_commit: event = self.after_commit.pop(0) for handler in self.handlers[type(event)]: try: handler(event) except Exception as e: print(f" handler {handler.__name__} failed: {e} (retry later)") bus = EventBus() # ---- billing module: public API is create_invoice + the InvoicePaid event@dataclass(frozen=True)class InvoicePaid: order_id: int cents: int _invoices: dict[int, int] = {} # billing's private table def create_invoice(order_id: int, cents: int) -> int: _invoices[order_id] = cents return order_id def mark_paid(order_id: int) -> None: bus.publish(InvoicePaid(order_id, _invoices[order_id])) # ---- orders module: calls billing's facade, reacts to billing's events_orders: dict[int, str] = {} # orders' private table def place_order(order_id: int, cents: int) -> None: _orders[order_id] = "awaiting_payment" create_invoice(order_id, cents) # synchronous call through the facade def on_invoice_paid(event: InvoicePaid) -> None: _orders[event.order_id] = "paid" # ---- notifications module: only listensdef send_receipt(event: InvoicePaid) -> None: if event.cents > 100_000: raise RuntimeError("email provider timeout") print(f" receipt sent for order {event.order_id}") bus.subscribe(InvoicePaid, on_invoice_paid)bus.subscribe(InvoicePaid, send_receipt) for order_id, cents in [(1, 4_999), (2, 250_000)]: place_order(order_id, cents) mark_paid(order_id) print(f"order {order_id}: billing committed") bus.flush() print(f"order {order_id}: status = {_orders[order_id]}")
Output
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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.invoices welds 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_id column 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:

  1. Compose in code: fetch orders, then call billing.invoice_statuses(order_ids) with one batched call.
  2. A read-only view owned by the module that publishes it (billing.invoice_summary), treated as part of its public API.
  3. A read model: a reporting module that listens to events from both and keeps its own denormalised table.
migrations/001_billing_schema.sql
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.

Quick check
The orders module needs to show each order's payment status on a page. Which approach keeps the modules independent?
Need a nudge? A hint rules out a wrong answer.

Enforcement: make CI fail

Boundaries you only document will erode under deadline pressure. Make a boundary breach a red build.

  • Python: import-linter. An independence contract says listed modules must not import each other at all. A forbidden contract bans imports of another module's _internal.
  • TypeScript: dependency-cruiser or Nx. Nx's @nx/enforce-module-boundaries ESLint 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.
pyproject.toml
[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.

Extracting billing into a service
  1. 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.

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

  3. Step 3

    Move the data

    Point the billing schema at its own database. Because nobody else touched it, nothing else changes.

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

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

Put it in order5 steps

Order these steps for turning a big ball of mud into a modular monolith.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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 the pairs0/5 matched

Match each tool to what it enforces.

Choose an item, then its match on the other side.
Key terms
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.