# Modular Monolith

**Also known as:** Structured monolith  
**Category:** System Architecture (Macro)  
**Complexity:** 2/5  
**Fit:** 3–30 engineers  
**Guide:** https://layra4.dev/architectures/system/modular-monolith

*One deployable, with module walls inside that the build enforces.*

A modular monolith is one deployable made of modules with strict walls. Each module owns its data, exposes a small public API, and may not reach into another module's code or tables. A build check enforces the walls, not the network. Shopify split its main Rails app (about 2.8 million lines of Ruby in 2020) into components this way and built the Packwerk tool to check them.

You keep in-process calls, local transactions and one deploy. You also get clear team ownership and an easy exit: a module with clean walls can later become its own service by replacing a function call with a network call. The cost is discipline. Someone must design the walls and keep the check green.

> **In one sentence.** Give each module its own data and one public API, and fail the build on any other import, so a later split is a refactor, not a rewrite.

## Origin

Grew out of the “monolith-first” movement: Simon Brown's talks, Kamil Grzybek's reference implementation, and the DDD view that a bounded context is a logical boundary, not a deployment one.

## What makes it modular

### Module = business area

Each module covers one part of the domain, such as orders or billing, and owns everything about it. It follows a bounded context (one consistent model with its own language), not a technical layer.

- One module per capability
- Owns its logic and its data
- Cut vertically, not by layer

### Public API only

A module exposes one small entry file and nothing else. Everything behind it is private. Other modules may import only that file.

- A narrow, deliberate contract
- Internals cannot be imported
- The only point of coupling

> modules/billing/index.ts exports BillingApi; the rest of billing/** is private.

### Data owned per module

Each module owns its tables. Others ask through its API and never join across the wall. One database with one schema per module is common and fine.

- No cross-module joins
- No cross-module foreign keys
- The data has walls too

### Enforced boundaries

A tool checks the walls on every build: dependency-cruiser or ESLint rules in TypeScript, Packwerk in Ruby, ArchUnit in Java. An illegal import fails CI instead of passing review.

- An illegal import fails the build
- Not left to memory or goodwill
- The most important practice

### Three ways across a wall

Call another module's public API when you need an answer. Publish an in-process event to announce a fact. Wrap a foreign model in a small translating adapter so its types do not spread.

- Need an answer → call the API
- Announce a fact → publish an event
- Foreign model → translate at the seam

## Rules that keep the walls standing

### Fail the build on an illegal import

Check module walls in CI with a tool like dependency-cruiser, Packwerk or ArchUnit. Walls kept only by code review erode; a red build does not.

### Import only another module's public API

Each module exposes one entry file, and everything else is private. Every shortcut past that file is coupling you will pay to undo when you split.

### Keep each module's tables private

No joins or foreign keys across modules. Read another module's data through its API. Then the data can move with the module when it becomes a service.

### Call for answers, publish events for facts

Call a public API when you need a result now. Publish an in-process event when you only announce that something happened. Matching the channel to the intent avoids needless dependencies.

## Diagrams

Rendered as geometry on the guide page; not reproducible as text.

- `module-communication` — see https://layra4.dev/architectures/system/modular-monolith

## Sealed modules in one deployable

```
src/
modules/                        # one folder per business area
  orders/                       # owns its logic and its data
    index.ts                    # the ONLY public file; exports OrdersApi
    domain/                     # private
    application/
    infrastructure/
  billing/                      # same shape; reaches orders only via its index
shared/                         # small kernel; no business logic
index.ts                        # composition root; wires every module, one process
```

Each module is a sealed box with one index.ts. A boundary check fails CI if billing imports anything else from orders.

## Examples

### A call through the module's public contract

```typescript
// modules/billing/index.ts — the ONLY thing other modules may import
export type { Invoice } from "./public/types";
export interface BillingApi {
  invoiceFor(orderId: string): Promise<Invoice>;
}
export const makeBilling = (db: Db): BillingApi => billingService(db);
// everything else under modules/billing/** is private

// modules/orders/confirmOrder.ts — depends on the contract only
export const confirmOrder = (billing: BillingApi) => async (id: string) => {
  const invoice = await billing.invoiceFor(id);   // in-process call, public API
  // ...no access to billing's tables, repositories or domain objects
};
```

Orders imports only billing's public surface. To extract billing later, you replace the in-process call with an HTTP client that implements the same interface.

### Enforcing the wall: an illegal import fails CI

```javascript
// .dependency-cruiser.js — reach another module only through its index.ts
module.exports = {
  forbidden: [
    {
      name: "no-cross-module-deep-import",
      severity: "error",
      from: { path: "^src/modules/([^/]+)/" },
      to: {
        path: "^src/modules/([^/]+)/",
        pathNot: [
          "^src/modules/$1/",               // your own module: fine
          "^src/modules/[^/]+/index\\.ts$", // another module's index: fine
        ],
      },
    },
  ],
};
// Importing past another module's index.ts now fails the build.
```

The boundary becomes a build failure, not a guideline. This one rule separates a modular monolith from a plain one with the same name.

## When to use

- You want clear team ownership without running many services
- Domain boundaries still move, and modules are cheap to redraw
- You expect to extract a few services later and want that to be easy

## When not to use

- One module must scale or deploy on its own schedule today
- A crash in one area must never stop the others (hard fault isolation)
- Nobody will maintain the boundary check, so it decays into a plain monolith

## Benefits

- Most of the decoupling of services, with none of the network
- One deploy, one process and local ACID transactions
- A later split is a mechanical extraction, not a rewrite

## Costs

- The walls need an automated check and someone who keeps it green
- Still one deployable: no independent scaling or release cadence
- One process, so a crash or memory leak still affects every module

## Pitfalls

- Walls kept only by convention; within months, imports cross them everywhere
- Cross-module joins and foreign keys that quietly tie the data back together
- A “shared” module that grows into a dumping ground every module depends on
- Treating it as a short stop and extracting services before any need appears

## Similar patterns, compared

Two neighbours get mixed up with this one: the monorepo, which sounds similar but answers a different question, and service-based architecture, which is the usual next step.

### Modular Monolith vs Monorepo

Not alternatives: this is a runtime architecture, that is a repository layout. A modular monolith in many repos and fifty microservices in one repo are both normal. — [Monorepo](https://layra4.dev/architectures/repository-strategy/monorepo)

**What is genuinely the same**

- Both react to coordination pain, not to technical limits
- Both need clear internal boundaries to stay healthy

**What actually differs**

- This decides how many artifacts deploy; that decides how many repositories hold the code
- Breaking this one can cause an outage; breaking that one costs build time
- Changing this is a re-architecture; changing that is a repository migration

### Modular Monolith vs Service-Based

The same module boundaries; service-based just deploys each big module on its own. Moving from here to there is mostly packaging, if the walls held. — [Service-Based](https://layra4.dev/architectures/system/service-based)

**What is genuinely the same**

- Coarse units, each covering a whole business area
- Often one database, with one schema per unit
- Local transactions inside a unit

**What actually differs**

- Here a call is in-process; there it crosses the network and can fail
- Here one deploy ships everything; there each service ships alone
- Here one crash stops every module; there one service can crash alone

**Pick Modular Monolith when:** Teams do not yet block each other on the release, and no module needs its own scaling or fault isolation.

## Related patterns

- [Monolithic](https://layra4.dev/architectures/system/monolith) — the starting point; add the walls to get here
- [Service-Based](https://layra4.dev/architectures/system/service-based) — the next step: deploy the big modules separately
- [Microservices](https://layra4.dev/architectures/system/microservices) — the same modules, later split finer across the network
- [Bounded Context](https://layra4.dev/architectures/strategic/bounded-context) — what a module should be drawn around
- [Event-Driven](https://layra4.dev/architectures/application/event-driven-app) — in-process events let modules work together without coupling

## Further reading

- *Modular Monolith: A Primer* — Kamil Grzybek — A clear article on module design; his modular-monolith-with-ddd repository shows it in code.
- *Deconstructing the Monolith* — Kirsten Westeinde (Shopify Engineering, 2019) — How Shopify split its Rails app into components.
- *Modular Monoliths (talk)* — Simon Brown — The case for logical modules over early distribution.
