Your monolith started as one tidy Spring Boot or Rails app. A few years later, shipping code reads the orders table directly, billing calls classes deep inside catalog, and a change to how discounts are stored breaks invoices. Nobody can say with confidence what depends on what.
The usual proposal is microservices. They bring hard boundaries, but also network calls, distributed transactions, a broker and a pipeline per service, often long before you need them. A modular monolith keeps the boundaries and skips the rest: one deployable, split into modules that own their data and talk only through small public APIs.
This post covers module anatomy, communication, data, boundary tools, the comparison with microservices and extracting a module later, with a diagram of a four-module shop.
What a modular monolith is
A modular monolith is one deployable unit (one build artifact, one process, usually one database) whose code is split into modules along business capabilities, with explicit, checked boundaries. Shopify described its move to this style in Deconstructing the Monolith (2019): keep all of the code in one codebase, but make sure boundaries between components are defined and respected.
Two parts of that definition matter:
- Modules follow the business, not technical layers. Orders and Billing are modules; controllers and repositories are not. A module can still have layers inside, and it is a good unit for hexagonal architecture.
- Boundaries are checked. A folder named
billingis a convention. A build that fails when Shipping imports a class from inside Billing is a boundary.
You still build, release and scale one artifact. What changes is the dependency graph inside it.
The anatomy of a module
| Part | What it holds | Who may use it |
|---|---|---|
| Public API | A facade such as OrdersApi, its types and the events it publishes |
Other modules, through declared dependencies |
| Internal code | Domain model, persistence, jobs, adapters | Only the module itself |
| Data | The module's tables, in its own schema | Only the module's code |
| Tests | Tests that start the module on its own | The team that owns the module |
In Spring Modulith, each direct sub-package of the application's main package is a module by default; the module's top-level package is its API and its sub-packages are internal:
com.example.shop
├── ShopApplication.java
├── orders module "orders": this package is the API
│ ├── OrdersApi.java
│ ├── OrderPaid.java
│ └── internal hidden from other modules
│ ├── Order.java
│ └── OrderRepository.java
├── billing
│ ├── BillingApi.java
│ └── internal
└── shipping
└── internal
Keep the API small: a module that makes every service public has no boundary.
How modules talk to each other
Modules communicate in two ways:
Calls through the public API. Orders calls CatalogApi.price(sku) and gets an answer in the same thread. Use a call when the caller needs the result to continue.
Domain events. Orders publishes OrderPaid; Catalog reduces stock and Shipping creates a shipment, and Orders knows neither of them. Use events for side effects.
The dependencies between modules must form a directed acyclic graph. If Billing calls OrdersApi while Orders calls BillingApi, the two modules have merged in all but name; pass the data Billing needs in the call, or turn one direction into an event.
In Spring Modulith, a listener in another module looks like this:
// shipping module, internal package
@Component
class ShipmentCreator {
@ApplicationModuleListener
void on(OrderPaid event) {
shipments.createFor(event.orderId());
}
}
@ApplicationModuleListener combines @Async, a new transaction and @TransactionalEventListener: the listener runs after the Orders transaction commits, and a failure in Shipping does not roll back the order. The event publication registry logs each delivery inside the original transaction and keeps failed ones for resubmission, a transactional outbox inside one process.
Give every module its own data
Shared tables are where most monoliths lose their boundaries: perfect package rules do not help if one JOIN couples every module. Shopify's boundary tracking tool counted every ActiveRecord association across components as a violation. The rules that work:
- One schema per module in the shared database.
- No joins or foreign keys across schemas. Billing stores
order_idas a plain column. - Copy what you need. If Billing needs the order total, the
charge()call or theOrderPaidevent carries it.
The database can enforce ownership. In PostgreSQL, a role cannot access objects in a schema it does not own unless the owner grants USAGE on it (PostgreSQL docs). Give each module its own role:
CREATE ROLE billing_rw LOGIN;
CREATE SCHEMA billing AUTHORIZATION billing_rw;
-- No GRANT USAGE ON SCHEMA orders TO billing_rw,
-- so any query from Billing against orders.* fails with a permission error.
The cost is one connection pool per module, which multiplies connections; a lighter start is a CI check that scans SQL for other modules' schemas. Feed cross-module reports from events into a reporting module or a warehouse instead of joining schemas.
Enforcing module boundaries with tooling
Package names alone stop nobody: as the Spring Modulith documentation notes, the Java compiler will not prevent other modules from using a public class in an internal package. A check in CI will:
| Stack | Tool | What it checks | Where it fails |
|---|---|---|---|
| Spring Boot | Spring Modulith | Module cycles, access only through API packages, allowed dependencies | ApplicationModules.of(App.class).verify() in a test |
| Java, Kotlin | ArchUnit | Package rules you write, such as cycle-free slices | JUnit tests |
| Ruby on Rails | Packwerk | Constant references to undeclared packages | bin/packwerk check |
| .NET | One project per module | internal types stay inside their assembly |
Compiler errors |
| Go | internal/ directories |
Imports from outside the parent tree | The go command |
| TypeScript, JavaScript | dependency-cruiser | forbidden path rules, circular dependencies |
CLI in CI |
| Python | Import Linter | Independence, layers and forbidden-import contracts | CLI in CI |
On the JVM, the Spring Modulith verification is one line, and ArchUnit covers codebases without Spring:
@AnalyzeClasses(packages = "com.example.shop")
class ModuleRulesTest {
@ArchTest
static final ArchRule noModuleCycles =
slices().matching("com.example.shop.(*)..").should().beFreeOfCycles();
@ArchTest
static final ArchRule billingInternalsStayInside =
classes().that().resideInAPackage("..billing.internal..")
.should().onlyBeAccessed().byAnyPackage("..billing..");
}
Know the limits: Packwerk sees static constant references only, and its public API checks now live in the separate packwerk-extensions gem.
In an existing codebase, turn the checks on before you fix everything: bin/packwerk update-todo records current violations in package_todo.yml, and ArchUnit's FreezingArchRule reports only new ones. The list shrinks as you work it off.
Modular monolith vs monolith vs microservices
| Classic monolith | Modular monolith | Microservices | |
|---|---|---|---|
| Deployable units | One | One | One per service |
| Boundaries | Conventions | Module APIs, checked in CI | Network APIs |
| Data | Shared tables | Schema per module | Database per service |
| Communication | Any class to any class | In-process calls and events | Network calls, broker |
| Cross-module work | One transaction | One transaction, best avoided | Sagas, outbox |
| Scaling and failure isolation | Whole app | Whole app | Per service |
| Operational overhead | Low | Low | High |
| Moving a boundary | Easy, unchecked | Refactoring in one repository | API migration across teams |
A modular monolith fits when one or a few teams release together, domain boundaries are still moving, and you want one pipeline and local transactions. Split a module out when it needs something the rest does not: very different scaling, stricter isolation, a different runtime, or its own release schedule.
Martin Fowler's MonolithFirst (2015) notes that almost all the successful microservice stories he heard started with a monolith that got too big and was broken up, though he had not heard many stories of a carefully modular monolith splitting cleanly. An online store split into five microservices shows the other end.
Extracting a module into a service later
Good boundaries make extraction mostly mechanical:
- Pick a module with a clean record: no recorded violations, no cycles, no cross-schema joins.
- Keep the interface, change the transport.
BillingApibecomes an HTTP or gRPC client with timeouts, retries and idempotency keys; callers do not change. - Move events to a broker. Spring Modulith can externalize events annotated with
@Externalizedto Kafka, AMQP or JMS, and the registry keeps failed sends for resubmission. - Move the schema. Nothing outside Billing references the
billingschema, so it moves to its own database by dump and restore or logical replication. - Shift traffic and delete. Route calls to the new service with the strangler fig pattern, then remove the module from the monolith.
What gets harder: work that relied on one transaction across modules now needs a saga with compensating steps, and every call can fail or time out. Find those spots before you extract.
The modular monolith diagram
Diagram contents
- Shop application: one deployable, one process
- In-process event bus
- Catalog
- Orders
- Billing
- Shipping
- Postgres
- catalog schema
- orders schema
- billing schema
- shipping schema
- CatalogApi.price()
- BillingApi.charge()
- publish OrderPaid
- OrderPaid: reduce stock
- OrderPaid: create shipment
- SQL as catalog_rw
- SQL as orders_rw
- SQL as billing_rw
- SQL as shipping_rw
- direct table read: blocked
How to read it:
- The container boundary is the single deployable.
- Four modules, each labeled with the interface it exposes.
- Solid gray arrows are calls through public APIs. Orders depends on Catalog and Billing, and nothing calls back, so there are no cycles.
- Dashed amber arrows are in-process events: Orders publishes OrderPaid, and Catalog and Shipping react after the order commits.
- The Postgres frame holds one schema per module, each reached through the module's own role. The red dashed line is access that the boundary checks and the missing grant block.
- The Markdown block lists the boundary rules, the event behavior and the grant.
Drawing modular monolith diagrams clearly
- Draw the deployable boundary. In C4 model terms, the monolith is one container and its modules are components.
- Name modules after business capabilities and write the public interface on each.
- Show data ownership with one line from each module to its schema. A schema reached by two modules is a finding.
- Separate calls from events with solid and dashed lines, labeled with the method or event name.
- Draw one forbidden path at most, in red, to make a rule visible.
- Leave out classes and layers; module internals get their own diagrams, such as a clean architecture diagram of a module's layers.
- Check the arrows for cycles. A cycle in the drawing usually means a cycle in the code.
Build it in Archboard
- Sign in with Google or GitHub and create a diagram.
- Add a Container Boundary from the C4 Model pack for the deployable.
- Inside it, add a wide Component from the C4 Model pack for the event bus, and four Component nodes below it: Catalog, Orders, Billing and Shipping, with the exposed interface in each technology field.
- Below the boundary, add a Frame from the Core pack named Postgres, holding four Postgres nodes from the Data pack, one per module schema.
- Draw solid gray edges for the API calls, dashed amber edges for OrderPaid, one colored edge from each module to its schema and a red dashed edge from Billing to the orders schema.
- Add a Markdown block from the Core pack with the rules, and four Text nodes as a legend.
To start from text, paste a Mermaid flowchart of the modules into the Mermaid to editable diagram tool for a first draft, then keep editing in Archboard.
The example uses 12 diagram nodes, within the Free plan. Six modules with their schemas would exceed the Free limit of 15; Pro removes it.
FAQ
What is a modular monolith? An application built and deployed as one unit but divided into modules along business capabilities. Each module owns its data and exposes a small public API, and a build check stops other modules from reaching into its internals.
Is a modular monolith better than microservices? For one or a few teams that release together, usually yes: clear boundaries without network calls, a broker or distributed transactions. Microservices win when parts need independent scaling, stronger isolation, a different runtime or their own release schedule.
Can modules in a modular monolith share a database? They can share a database server and one database, but not tables. Give each module its own schema and pass data through APIs or events, not joins or foreign keys.
How do modules in a modular monolith communicate? Through in-process calls to public APIs when the caller needs an answer, and in-process domain events for side effects. Dependencies between modules should have no cycles.
How do you enforce module boundaries? With a check in CI, such as Spring Modulith or ArchUnit on the JVM, Packwerk in Rails or Import Linter in Python. Record existing violations first, then fail the build on new ones.