Software ArchitectureVol. 13 · Part XIII
0 / 0

Shelves / Software Architecture

SA·140

Modular Monolith

One deployable, many well-bounded modules: why a modular monolith is often the most effective architecture, finding module boundaries from bounded contexts, designing module APIs (facades, commands, queries, DTOs), dependency rules and how to enforce them in every ecosystem (Spring Modulith, ArchUnit, JPMS, Gradle/Maven modules, Go internal packages, Rust crates, .NET projects, Nx and dependency-cruiser, import-linter), domain ownership, separate persistence per module, internal events with transactional publication, testing modules in isolation, operations, and how to extract a module into a service when the time comes.

23 topics · ~21 min read · 30-question quiz
Updated Suggest a correction

Start here: one deployable, firm boundaries inside

A modular monolith is one application, deployed as one unit, whose code is split into modules with real boundaries: each module (ordering, kitchen, billing) owns its data and logic and exposes a small public API; other modules may use only that API. It keeps the simplicity of one deployment (one build, one process, in-process calls, local transactions) while getting much of the independence people seek from microservices. Many teams start here, and some never need to leave.

Boundaries that are enforced, not hoped for

Each module has an api.py (its public face) and private internals (_tickets.py holds the kitchen's data). Two rules, written as import-linter contracts:

Text
Modules talk only through each other's api module     KEPT
Kitchen and billing don't depend on ordering          KEPT

Then two very ordinary shortcuts were added: ordering read the kitchen's ticket table directly ("it's just one line"), and the kitchen imported ordering to look up order details:

Text
Modules talk only through each other's api module     BROKEN
-   shop.ordering.service -> shop.kitchen._tickets (l.5)
Kitchen and billing don't depend on ordering          BROKEN
-   shop.kitchen.api -> shop.ordering.service (l.5)
Contracts: 0 kept, 2 broken.

The first shortcut couples ordering to the kitchen's storage format, so the kitchen team can no longer change its tables freely. The second creates a cycle: ordering needs kitchen and kitchen needs ordering, so neither can be understood, tested or extracted alone. In most monoliths these shortcuts accumulate silently until the "modules" are fiction (the "big ball of mud"); a fitness function in CI stops each one at the pull request.

Why not just make them services?

The same kitchen lookup, called two ways:

Text
in-process call to kitchen.api.ticket_status:            68 ns
same call over HTTP + JSON on localhost:                 273 µs   (≈4,000× slower)
plus a typical same-zone network round trip (~0.5 ms):   ≈0.77 ms (≈11,000×)

An in-process call can't time out, fail halfway or arrive twice; a network call can do all three, so every one needs timeouts, retries, idempotency and monitoring (Volume 12, chapter 130). A well-bounded module can still be extracted into a service later, when a real reason appears (different scaling, a separate team's release cadence, a different technology). Because it already talks only through its API, extraction means replacing in-process calls with network calls behind that same API.

How deep to go in modular monoliths

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain modular monoliths and how they differ from layered monoliths and microservices
L2 Structure an application into modules with public APIs and owned data
L3 Explain module communication (calls, in-process events), data ownership and transaction boundaries
L4 Enforce and repair boundaries with dependency rules, cycle detection and data-access checks
L5 Plan a monolith's modularisation and selective extraction to services
L6 Guide large codebases' evolution across many teams with modular boundaries

Why a modular monolith

Teams often face a false choice between a big ball of mud (a monolith with no internal structure, where everything depends on everything) and microservices (independently deployable services with high operational cost). The modular monolith is the middle path:

  • One deployable unit (one process, one CI pipeline, one runtime to operate), usually one database server.
  • Internally divided into modules aligned with business domains (bounded contexts, chapter 138), each with a public API and hidden internals.
  • Enforced boundaries: modules communicate only through their APIs or events; dependency rules are checked automatically in the build.
big ball of mud no boundaries modular monolith orders catalogue payments shipping one DB · schema per module enforced modules microservices orders+ DB catalogue+ DB payments+ DB shipping+ DB many deployables
Three architectures compared. A big ball of mud is one deployable with tangled internal dependencies. Microservices split the system into separately deployed services that communicate over the network, each with its own database. A modular monolith keeps one deployable and one database server but divides code and data into domain modules that talk through explicit APIs and events, enforced by build-time checks.

Benefits over microservices

Concern Modular monolith Microservices
Deployment and operations One artifact, one pipeline, one runtime Many pipelines, service discovery, mesh, versioned APIs
Calls between modules In-process: nanoseconds, no partial failure, no serialisation Network: latency, timeouts, retries, partial failure
Transactions Local ACID transactions are available when truly needed Sagas, outbox, eventual consistency everywhere
Refactoring boundaries Move code between modules with IDE support Change APIs across services and teams; data migration
Debugging One process, one stack trace, one log stream Distributed tracing required
Testing Straightforward end-to-end tests Contract tests, environments, flaky E2E
Infrastructure cost Low Higher (per-service overhead, platform team)

Benefits over an unstructured monolith

  • Changeability: features change one module; teams own modules.
  • Understandability: each module is a smaller system with a clear purpose.
  • Testability: modules tested in isolation with their dependencies stubbed.
  • Evolution path: well-bounded modules can later be extracted into services with far less effort, because their APIs and data are already separated.

The modular monolith is now a mainstream recommendation (Shopify's large Rails monolith with "componentization" via Packwerk, many teams adopting Spring Modulith, and several high-profile moves from microservices back to monoliths for cost and simplicity). The key insight: modularity is a design property; distribution is a deployment decision. You can get most of the benefits of microservices' boundaries without paying for the network.

Finding module boundaries

Modules should follow business capabilities / bounded contexts (chapter 138), not technical layers:

  • Good: ordering, catalogue, pricing, inventory, payments, shipping, customers, notifications.
  • Poor: controllers, services, repositories, utils, common; or entity-based modules (customer, order, product) that every feature must touch.

Heuristics:

  • High cohesion inside, low coupling between (chapter 135): a typical feature should change one module.
  • Data ownership: each piece of data has exactly one owning module (writes happen only there).
  • Language: module = bounded context with its own ubiquitous language.
  • Team alignment: a module (or a few) per team; modules shouldn't need constant cross-team coordination.
  • Rates of change and risk: volatile or high-risk areas (pricing rules) separated from stable ones.
  • Start coarse: a few larger modules are easier to get right than many tiny ones; split when a module grows multiple reasons to change.

A shared kernel of truly generic building blocks (value objects like Money, IDs, error types, time utilities) is acceptable but should stay small and stable; beware it turning into a dumping ground (common/shared modules full of business logic).

Module APIs

Each module exposes a public API and hides everything else. API forms:

  • Facade/service interfaces: OrderingApi.placeOrder(...), CatalogueQueries.productSummary(id).
  • Commands and queries as typed messages handled by the module (in-process mediator).
  • Events published by the module (OrderPlaced) for others to react to (below).
  • DTOs/read models designed for consumers, not the module's internal entities: other modules must not receive (and then depend on) internal aggregates or ORM entities.

Design module APIs like external APIs: stable, minimal, documented, versioned in spirit (changing them affects other teams), returning values rather than mutable internal objects.

// Java: module API in the module's base package; everything else in internal subpackages
package com.shop.ordering;                         // public API package (Spring Modulith: module root)

public interface Ordering {
    OrderId placeOrder(PlaceOrder command);
    Optional<OrderSummary> summary(OrderId id);    // DTO, not the internal Order aggregate
}

public record PlaceOrder(CustomerId customer, List<Item> items) {}
public record OrderSummary(OrderId id, String status, Money total) {}
public record OrderPlaced(OrderId orderId, CustomerId customer, Money total) {}    // published event

// com.shop.ordering.internal.* — Order aggregate, repository, JPA entities, service implementation:
// not accessible to other modules (verified by Spring Modulith / ArchUnit)

Dependency rules and enforcement

Boundaries that aren't enforced erode within months. Enforce them mechanically, in the build:

Ecosystem Enforcement tools
Spring (Java/Kotlin) Spring Modulith: treats top-level packages under the application package as modules, internal subpackages as hidden; ApplicationModules.of(App.class).verify() fails tests on violations or cycles; generates C4/PlantUML documentation
Java generally ArchUnit rules in tests; JPMS modules (exports only API packages); Gradle/Maven multi-module builds (a module can't use what isn't on its dependency list); jMolecules annotations
.NET Separate projects with explicit references; internal access; NetArchTest/ArchUnitNET
Go internal/ directories (compiler-enforced), separate packages per module, go-arch-lint/depguard rules in golangci-lint
Rust Crates in a Cargo workspace (dependencies explicit, cycles impossible); pub(crate)
TypeScript/JavaScript Nx enforce-module-boundaries with tags, dependency-cruiser, eslint-plugin-boundaries, package exports maps
Python import-linter contracts (layers, forbidden, independence), Tach, Packwerk-style tooling
Ruby Shopify Packwerk (packages with public folders and dependency declarations)
C/C++ Build-system targets with explicit dependencies (CMake/Bazel visibility rules), C++20 modules

Typical rules:

  1. No access to another module's internals (only its API package/types).
  2. No cyclic dependencies between modules (cycles mean they're really one module, or need events to decouple).
  3. Allowed dependency directions are explicit (e.g. ordering → catalogue (API), never catalogue → ordering).
  4. No direct access to another module's tables.
  5. Within a module, the domain doesn't depend on adapters (hexagonal rules, chapter 139).
// Spring Modulith: one test verifies all module boundaries and documents them
class ModularityTests {
    ApplicationModules modules = ApplicationModules.of(ShopApplication.class);

    @Test
    void verifiesModularStructure() {
        modules.verify();                         // fails on access to internals or cycles
    }

    @Test
    void writesDocumentation() {
        new Documenter(modules).writeModulesAsPlantUml().writeIndividualModulesAsPlantUml();
    }
}

// Optional explicit allowed dependencies per module (package-info.java)
@org.springframework.modulith.ApplicationModule(allowedDependencies = { "catalogue", "customers" })
package com.shop.ordering;

Domain ownership

Each module owns its domain concepts, rules and data:

  • Only the owning module writes its data and enforces its invariants; other modules ask (queries) or tell (commands) via its API, or react to its events.
  • Duplicated read data is fine: the shipping module may keep its own copy of the delivery address it needs (populated from events), rather than querying ordering on every operation. This reduces runtime coupling.
  • Teams own modules: CODEOWNERS files per module directory; module-level documentation (README, ADRs, API docs); module health metrics.
  • Avoid shared "god" modules: a common module accumulating domain logic re-creates the big ball of mud.

Separate persistence

Code boundaries are only half the story; data coupling is the most common way modular monoliths degrade into tangled ones (a report joins five modules' tables; a module updates another's rows directly).

Options, from weakest to strongest separation:

  1. Shared schema, owned tables: each table belongs to one module (naming prefix, documented ownership); cross-module joins forbidden by convention and review.
  2. Schema per module in the same database (ordering.orders, catalogue.products): enforce with database permissions (each module's data source uses a role with access only to its schema). Cross-schema joins impossible for the application role.
  3. Separate databases per module (same server or different): strongest; distributed-transaction concerns appear as in microservices.

Most teams use schema per module with separate migration folders per module (Flyway/Liquibase locations, Alembic branches, per-crate sqlx migrations), and no foreign keys across modules (reference by ID only, chapter 138's aggregate rule at module scale).

Cross-module queries (reports, dashboards) use:

  • Module APIs composed in an application/query layer.
  • Read models fed by events (a reporting module builds its own denormalised tables from other modules' events).
  • A separate analytics store (CDC to a warehouse) for heavy reporting.
SQL
-- Schema per module with roles that can only touch their own schema
CREATE SCHEMA ordering;  CREATE SCHEMA catalogue;  CREATE SCHEMA payments;

CREATE ROLE ordering_app LOGIN PASSWORD '…';
GRANT USAGE ON SCHEMA ordering TO ordering_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA ordering TO ordering_app;
-- no grants on catalogue or payments: cross-module SQL fails at runtime and in tests

Internal events

Modules often need to react to each other without direct calls: when an order is placed, payments should authorise, inventory should reserve, loyalty should award points. In-process domain events decouple the publisher from consumers:

  • The publishing module defines and publishes events in its API (OrderPlaced).
  • Consumer modules subscribe; the publisher doesn't know them (dependency points from consumer to publisher's API, not the reverse).
  • Events can be handled synchronously (same transaction: strong coupling of failure, use sparingly) or asynchronously after commit (eventual consistency, isolation of failures).

The reliability problem: if the application crashes after committing the order but before the listener runs, the event is lost. Transactional event publication solves it in-process the same way the outbox does across services (Vol. 12 ch. 131): persist the event publication in the same transaction, mark it complete when the listener succeeds, and retry incomplete publications on restart.

// Spring Modulith: events published within the transaction, handled asynchronously after commit,
// with the Event Publication Registry persisting publications so none are lost on crashes
@Service
@RequiredArgsConstructor
class OrderingService implements Ordering {
    private final OrderRepository orders;
    private final ApplicationEventPublisher events;

    @Transactional
    public OrderId placeOrder(PlaceOrder cmd) {
        Order order = Order.place(cmd);
        orders.save(order);
        events.publishEvent(new OrderPlaced(order.id(), cmd.customer(), order.total()));
        return order.id();
    }
}

// In the payments module: @ApplicationModuleListener = @Async + @Transactional(REQUIRES_NEW)
// + @TransactionalEventListener(AFTER_COMMIT); completion recorded in the publication registry
@Component
class PaymentsOnOrderPlaced {
    @ApplicationModuleListener
    void on(OrderPlaced event) { payments.authorize(event.orderId(), event.total()); }
}
// Incomplete publications can be resubmitted on restart; spring-modulith-events-kafka/amqp can
// also externalise selected events to a broker when modules become services.

Guidelines: events carry what consumers commonly need (event-carried state, chapter 131 of Vol. 12), named in the publisher's language; handlers are idempotent; avoid long chains of synchronous event handlers that recreate tight coupling; document which modules publish and consume which events (Spring Modulith can generate this).

Testing modules

  • Module tests: bootstrap one module (plus stubs for its dependencies' APIs) and test its use cases end to end within the module, including its persistence (Spring Modulith @ApplicationModuleTest bootstraps only one module; Scenario API to assert published events).
  • Unit tests for domain logic inside modules (chapter 135, Vol. 11 ch. 115).
  • Architecture tests verify boundaries on every build (above).
  • Integration tests of the whole application for critical flows (fewer than with microservices, and far less flaky: one process).
Java
@ApplicationModuleTest                      // bootstraps only the ordering module (and its declared deps, mocked)
class OrderingModuleTests {
    @Autowired Ordering ordering;
    @MockitoBean CatalogueQueries catalogue;   // other module's API stubbed

    @Test
    void publishesOrderPlaced(Scenario scenario) {
        when(catalogue.price(any())).thenReturn(Money.inr(49900));
        scenario.stimulate(() -> ordering.placeOrder(new PlaceOrder(customerId, List.of(item))))
                .andWaitForEventOfType(OrderPlaced.class)
                .toArriveAndVerify(e -> assertThat(e.total()).isEqualTo(Money.inr(49900)));
    }
}

Operating a modular monolith

  • Scaling: scale the whole application horizontally (stateless instances behind a load balancer, Vol. 12 ch. 124). If one module needs very different scaling (e.g. CPU-heavy image processing), run the same artifact in different roles (web vs worker processes consuming queues), or extract that module.
  • Deployments: one pipeline; keep it fast with modular builds and test selection (build caches, affected-module testing).
  • Observability: tag logs, metrics and traces with the module name; per-module dashboards and error budgets; Spring Modulith adds module-level tracing spans.
  • Team scaling: CODEOWNERS per module, module-level reviews, clear API change process, trunk-based development with feature flags to avoid merge pain.
  • Failure isolation is weaker than microservices (a memory leak in one module affects all): use bulkheads (separate thread pools/executors per module), timeouts, and resource limits; consider extracting modules with risky resource profiles.

Extracting a module into a service

When forces justify it (independent scaling, independent release cadence, a different technology need, fault isolation, team autonomy at scale), a well-bounded module can be extracted:

  1. Ensure the module is clean: no access to internals from outside, no foreign tables, communication only via API and events.
  2. Make module API calls network-ready: coarse-grained operations, DTOs serialisable, idempotent commands, no chatty call patterns, timeouts in callers.
  3. Move its data to its own database (schema per module makes this a copy + switch; use CDC for zero-downtime migration).
  4. Externalise its events to a broker via the outbox (Spring Modulith can publish selected events to Kafka/AMQP/SQS).
  5. Deploy the module as a separate service; replace the in-process API implementation in the monolith with an HTTP/gRPC client implementing the same interface (an adapter), behind a feature flag for gradual traffic shifting.
  6. Add the operational pieces: monitoring, SLOs, on-call, contract tests (Vol. 11 ch. 117).
before monolith ordering paymentsAPI + internal payments schema · in-process events after monolith ordering PaymentsClient paymentsservice+ own DB gRPC events: outbox → broker (externalised) same API interface on both sides
Extracting a module into a service. The module first communicates only through its API and events and keeps its data in its own schema. It is then deployed separately with its own database; inside the monolith, a client adapter implements the same API over the network, and in-process events are externalised to a broker through an outbox, so callers barely change.

The strangler fig approach applies (chapter 141): extract incrementally, one module at a time, keeping the system working throughout. Many teams find they only ever need to extract a few modules; the rest stay happily in the monolith.

Anti-patterns

  • Modules in name only: packages called modules but freely importing each other's internals, without automated checks.
  • Shared database free-for-all: modules joining and updating each other's tables.
  • Entity-centric modules (customer, order, product) that every feature crosses.
  • Chatty synchronous calls between modules mirroring a distributed system's coupling (fine in-process, painful later if extracted).
  • Synchronous event chains that make one request run five modules' side effects in one transaction.
  • A giant shared/common module holding business logic.
  • Premature extraction: splitting into services before boundaries have stabilised; it's much cheaper to move a boundary inside a monolith.

Lab: enforcing module boundaries and pricing the network

Python 3.13 on the lab machine: a shop package with ordering, kitchen and billing modules, each exposing api.py with private _*.py internals; import-linter 2.15; and a call-cost benchmark using http.server with TCP_NODELAY and a keep-alive http.client connection.

Experiment 1: boundary contracts

Config
[importlinter:contract:public-apis-only]
name = Modules talk only through each other's api module
type = forbidden
source_modules = shop.ordering, shop.billing
forbidden_modules = shop.kitchen._tickets
allow_indirect_imports = True

[importlinter:contract:no-cycles]
name = Kitchen and billing don't depend on ordering
type = forbidden
source_modules = shop.kitchen, shop.billing
forbidden_modules = shop.ordering
Code state Result
as designed 2 kept, 0 broken
+ ordering imports kitchen._tickets; + kitchen.api imports ordering.service 0 kept, 2 broken; shop.ordering.service -> shop.kitchen._tickets (l.5), shop.kitchen.api -> shop.ordering.service (l.5)

Two configuration lessons from building it. root_packages = shop on one line was parsed as a list of characters (Could not find package 's'); it needs one package per indented line. And without allow_indirect_imports = True, the first contract also flagged the legitimate chain ordering → kitchen.api → kitchen._tickets, since a forbidden contract checks the whole import graph by default. Real modular-monolith tooling: Spring Modulith (verifies module structure and documents it), ArchUnit, .NET's NetArchTest, Packwerk for Ruby (Shopify), and Nx module boundaries in TypeScript monorepos.

Experiment 2: data ownership

Import rules don't stop SQL from crossing boundaries. Enforce data ownership too: one schema per module (ordering.*, kitchen.*), a database role per module granted only its own schema, and a check that fails if any module's queries mention another's schema. Cross-module reads go through the owner's API, or through a read model the owner publishes (an in-process event updating a projection), the same patterns microservices use, without the network.

Experiment 3: in-process versus network

Call Time Relative
kitchen.api.ticket_status() in-process 68 ns 1×
HTTP + JSON, localhost, keep-alive 273 µs ≈4,000×
plus a 0.5 ms same-zone round trip ≈0.77 ms ≈11,000×

Latency is the smaller cost. The larger ones: a module call that's now remote can fail independently, needs a timeout, retries with idempotency, a versioned contract (Volume 11, chapter 117), its own deployment and monitoring, and can no longer share a database transaction with the caller. A screen that made 20 module calls in a monolith (≈1.4 µs) would spend over 15 ms on them as services, unless redesigned to make fewer calls.

Try it yourself

  1. Add an independence contract (type = independence) for kitchen and billing, and an in-process event bus so billing reacts to OrderPlaced without importing ordering.
  2. Give each module its own PostgreSQL schema and role, and show the kitchen role is denied a query on ordering.orders.
  3. Extract billing behind its existing api.py as an HTTP service: replace the function bodies with HTTP calls and run the same tests.
  4. Run Spring Modulith's ApplicationModules.of(App.class).verify() on a small Spring Boot app with two packages that reference each other's internals.

Revision sheet: modular monolith

Key ideas

  • One deployable, many modules: simple operations, in-process calls, local transactions.
  • Module boundaries from bounded contexts and business capabilities, not technical layers.
  • Public API per module (facade, commands, queries, DTOs); internals private; no cycles.
  • Data ownership: schema per module, no cross-module joins or writes; read models for cross-module queries.
  • Communication: direct API calls for queries/commands; in-process domain events for reactions; outbox if events leave the process.
  • Enforcement: import rules, cycle checks, schema permissions, architecture tests in CI (Spring Modulith, ArchUnit, Packwerk, import-linter, Nx).
  • Evolution: extract a module into a service only for a concrete driver; strangler-fig style, behind its existing API.

Numbers to remember

  • Lab: in-process module call 68 ns vs HTTP+JSON on localhost 273 µs (≈4,000×).
  • Lab: two everyday shortcuts broke both boundary contracts, each reported with file and line.

Pitfalls

  • Modules by technical layer (controllers/, services/, repositories/) instead of by capability.
  • Shared tables and cross-module joins.
  • "Utility" or "common" modules that everything depends on and that grow without bound.
  • Boundaries without enforcement; cycles tolerated "temporarily".
  • Extracting services before modules are clean (a distributed ball of mud).

Glossary

  • Big ball of mud: a system with no discernible structure.
  • Module facade: the public entry point of a module.
  • Read model / projection: data maintained from another module's events for querying.
  • Strangler fig: incrementally replacing parts of a system behind stable interfaces.
  • Package by feature: organising code by business capability.