Course contents

10. Software Architecture Lesson 5 of 10

Modular Monolith

One deployable, strong boundaries: modules with private schemas and public contracts, in-process events, shared runtime fate, and extracting a module into a service.

16 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A modular monolith is one deployment unit split into modules along business capabilities.
  • Each module owns its schema and exposes a narrow public contract; everything else is internal.
  • Modules interact through in-process calls on contracts and through integration events.
  • Boundaries need enforcement: internal types, per-module database logins, architecture tests.
  • Modules share one process and its fate; good boundaries make extracting a module later a contained change.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A modular monolith is a single deployable application whose code is divided into modules along business capabilities (Ordering, Catalog, Payments), each with:

  • its own data, usually a separate schema in a shared database, touched by no other module;
  • a narrow public contract (interfaces, commands, DTOs, integration events) through which other modules interact with it;
  • internal everything else: entities, handlers, EF Core configuration.

It runs as one process and ships as one artifact, like any monolith. The difference from a "big ball of mud" is that the boundaries are designed and enforced.

Why it exists

Microservices give teams independent deployment and scaling, but they bring network calls, partial failures, distributed data and a lot of operational machinery. Many systems do not need those properties on day one, and many teams split too early along the wrong lines. A modular monolith delivers most of the design benefit, clear boundaries, private data, explicit contracts, while keeping in-process calls, one deployment and simple local development. If a module later needs independence, the boundary already exists.

How it works

Project layout. Each module is a few projects, for example Ordering.Core, Ordering.Infrastructure and Ordering.Contracts; only *.Contracts is referenced by other modules. The host (Shop.Api) references all modules and wires them up.

// Catalog.Contracts
public interface ICatalogApi { Task<Price?> GetPrice(ProductId id, CancellationToken ct); }

// Catalog.Core
internal sealed class CatalogApi(CatalogDbContext db) : ICatalogApi
{
    public async Task<Price?> GetPrice(ProductId id, CancellationToken ct) =>
        await db.Products.Where(p => p.Id == id).Select(p => p.Price).SingleOrDefaultAsync(ct);
}

Data per module. Each module has its own DbContext mapped to its own schema (HasDefaultSchema("catalog")) and its own migrations. No joins across schemas; a module that needs another's data asks through the contract or keeps a local copy fed by events.

Synchronous calls go through contracts: fast in-process method calls. Asynchronous integration events (OrderPlaced) go through an in-process bus or mediator, so the publisher does not know its subscribers. An in-memory bus loses events if the process dies between commit and dispatch; the transactional outbox pattern stores them in the same transaction as the business data.

Enforcement. Mark module internals internal; give each module a database login restricted to its schema; run architecture tests (NetArchTest, ArchUnitNET) in CI that fail when a module references another module's non-contract types.

When to use it

  • New products and teams whose domain boundaries are still being discovered: boundaries are cheaper to move inside one codebase.
  • Small to medium organisations without a strong need for independent deployment per team.
  • As a step away from a tangled monolith, before (or instead of) moving to microservices.
  • As the target of a "monolith first" strategy, extracting services only where a module needs independence.

When not to

  • Many teams that must deploy independently many times a day without coordinating releases.
  • Modules with very different runtime needs: a GPU-heavy or memory-hungry component that should not share a process.
  • Hard isolation requirements (regulatory, security, fault isolation) for a specific capability; extract that module.

Trade-offs

Choice You gain You pay
One deployable Simple operations, one pipeline, easy local runs One release train; everything scales together
In-process contracts Fast calls, no network failures Discipline needed to keep contracts narrow
Schema per module in one database Data ownership, easier extraction No cross-module joins; some data duplication
In-process events Decoupled modules, no broker to run Lost on crash unless stored (outbox)
Extracting a module Independent deploy, scale and isolation Network latency, partial failure, distributed data

Alternatives

  • Traditional (layered) monolith: simpler at first, but boundaries erode without modules.
  • Microservices: independent deployment and scaling per service, at the cost of distribution.
  • Vertical slices or clean architecture inside each module: these complement the modular monolith rather than replace it.

Failure modes

  • Boundary erosion: cross-schema queries and references to internals accumulate until modules are modules in name only.
  • Shared fate: a memory leak, a thread-pool starvation or a CPU-heavy job in one module degrades or crashes every module.
  • Chatty contracts: fine-grained calls that are harmless in process become slow and fragile after extraction.
  • Shared "common" module: a dumping ground that every module depends on, coupling them all.
  • Lost events: in-memory integration events disappear if the process stops between commit and dispatch.

In production

Deploy as one unit, but monitor per module: tag logs, metrics and traces with the module name so a noisy neighbour is visible. Protect shared resources: separate connection pools per module, bounded background work, timeouts. Use an outbox for integration events that must not be lost. When extracting a module, keep its contract, replace the in-process implementation with a client (HTTP or gRPC), move its schema to its own database, and add the resilience patterns a network call needs (timeouts, retries with backoff, circuit breakers).

Common misconceptions

  • "A modular monolith is a stepping stone you must leave." Many systems stay one for good; extraction is an option, not a goal.
  • "Modules isolate failures." They isolate code and data. Runtime faults in one module still affect the process.
  • "Schema per module means a database per module." Separate schemas with restricted logins in one server are usually enough.
  • "Extraction is free if boundaries are good." The code change is contained; the latency, failure modes and data consistency work are new.

Interview angle

Propose a modular monolith when the scale and team size do not yet justify microservices, and show you know how to keep it modular: capability-aligned modules, private schemas, narrow contracts, events, enforcement in CI. Then discuss limits (shared runtime, one scaling unit, one release train) and the extraction path: which module you would extract first, why, and what changes when an in-process call becomes a network call.

Model assumptions

Contracts, schema ownership, the cross-schema shortcut and boundary enforcement are scripted illustrations with hand-placed packets, slowed to 30–40 ms per hop. The other steps are simulated: each module is a server with 16 workers and a 1–2 ms mean service time; module-to-module calls use 0 ms links (in process). Each schema is a database node with its own pool of 8 connections, 1 ms away, with about 4 ms per query (lognormal, cv 0.3). The shopper is 20 ms away; arrivals are random (Poisson). The in-process event bus is modelled as a queue consumed by a Notifications worker (4 workers, 20 ms each). The process crash fails every module at once for 3 s. The extracted Payments service is 3 ms away each way, an illustrative figure for a data-centre call including serialisation. In the challenge each charge takes 40 ms of work. Numbers show behaviour and orders of magnitude, not benchmarks.

The lesson as textEvery step of the simulation, written out.
  1. 1. Modules inside one deployable

    The shop is one application, built and deployed as a unit, but inside it the code is split into modules along business capabilities: Ordering, Catalog and Payments. Each module is its own set of projects with its own data.

    Shoppers place 20 orders per second (simulated). Ordering asks Catalog for prices, asks Payments to charge, and saves the order: three modules, one process, about 60 ms per order.

    Scene: Inside one dashed process boundary, Ordering calls Catalog and Payments; each module talks to its own schema below. Shoppers send 20 orders per second and every order succeeds in about 60 ms.

    Key idea: A modular monolith is one deployment unit with strong internal boundaries along business capabilities.

  2. 2. Modules talk through public contracts

    Ordering does not reach into Catalog’s classes. Catalog exposes a small public contract, ICatalogApi in a Catalog.Contracts project, and keeps everything else internal. Payments does the same with IPaymentsApi.

    The calls are ordinary in-process method calls, so they are fast and share one transaction scope if needed, but they go through a door that each module controls. (Scripted illustration, slowed down.)

    Scene: One order walks through the modules: Ordering calls Catalog, which reads its schema, then Payments, which writes its schema, then saves the order in its own schema and answers the shopper.

    Key idea: Each module exposes a narrow public contract and hides everything else.

  3. 3. Each module owns its schema

    All three schemas live in one SQL Server, but each belongs to exactly one module: only Catalog reads and writes catalog.*, only Ordering touches ordering.*. A module that needs another module’s data asks through its contract.

    That ownership is what keeps modules replaceable. Each module can change its tables freely, and the schema boundary is already the line along which a database could be split later.

    Scene: Each module queries only the schema directly below it, all three at the same time; no line crosses from one module to another module’s schema.

    Key idea: Data ownership is a boundary too: one schema, one owner, no cross-module joins.

  4. 4. A shortcut across the boundary

    Under deadline pressure, someone lets Ordering read product prices straight from catalog.Products: one SQL join instead of a call. It works, until the Catalog team renames a column, which is their right: they own the schema.

    Ordering’s query now fails at runtime, and Catalog had no way to know Ordering depended on its table. A cross-module query is a hidden contract, and enough of them turn the modular monolith into a big ball of mud.

    Scene: A new line runs from Ordering straight into the catalog schema. Ordering reads prices directly and succeeds; then Catalog changes its table, and Ordering’s next direct query comes back as an error.

    Key idea: Reaching into another module’s tables creates hidden contracts that break silently.

  5. 5. Make the boundaries hard to cross

    Remove the shortcut, and make the next one impossible rather than merely discouraged. Mark module internals internal so other modules cannot compile against them. Give each module its own database login that can only see its own schema. Add an architecture test (NetArchTest, ArchUnitNET) that fails the build when Ordering references a Catalog type outside Catalog.Contracts.

    Now Ordering’s attempt to query catalog.* is refused, and prices come through ICatalogApi again.

    Scene: The direct line is gone. A direct query from Ordering to the catalog schema is refused with an error; then Ordering asks Catalog through its contract, and Catalog reads its own schema.

    Key idea: Enforce boundaries with the compiler, database permissions and architecture tests, not with goodwill.

  6. 6. Integration events inside the process

    A new Notifications module must email the customer after each order. Ordering should not call it: Ordering would then depend on Notifications and wait for it. Instead Ordering publishes an OrderPlaced event to an in-process bus, and Notifications consumes it asynchronously.

    With 20 orders per second again, orders are no slower than before, and Notifications works through the events on its own schedule. Ordering does not even know who listens.

    Scene: Ordering now also publishes an OrderPlaced message to an in-process event queue, and the Notifications module consumes the messages. Orders still take about 60 ms and all succeed; the queue stays nearly empty.

    Key idea: Events decouple modules: the publisher does not know or wait for its subscribers.

  7. 7. One process, one fate

    A memory leak in the Notifications module eventually crashes the process. Because every module runs in the same process, they all go down together: for three seconds, until the host restarts, every order fails, although Ordering, Catalog and Payments had no bug.

    The schemas survive; the code does not. That is the price of a single deployable: modules isolate code and data, but not runtime faults, memory or CPU.

    Scene: At 1.5 s every module in the process goes offline at once and all orders fail; at 4.5 s the process restarts and orders succeed again. The three schemas stay healthy throughout.

    Key idea: Modules isolate code and data, not runtime: one module’s crash takes the whole process down.

  8. 8. Extract a module along its seam

    Payments now needs its own release cycle and stricter isolation, so it becomes a separate service. Because it already had its own contract and its own schema, the cut is clean: Ordering keeps calling IPaymentsApi, now implemented by an HTTP client; the payments schema moves with the service.

    The price shows up at once: every order makes a network call, about 3 ms each way here, so orders get about 6 ms slower, and Payments can now fail on its own. Extract a module when its independence is worth that, not before.

    Scene: Payments and its database now sit outside the process boundary, joined to Ordering by a 3 ms network link. Orders still all succeed but take about 6 ms longer.

    Key idea: Good module boundaries make extraction cheap in code, but every extracted call pays network latency and partial failure.

  9. 9. Boundaries first, distribution later

    A modular monolith gives you most of the structure of microservices, modules aligned with business capabilities, private data, explicit contracts and events, while keeping one deployment, in-process calls and simple operations.

    Its limits are runtime ones: one process, one scaling unit, one fate. When a module truly needs independence, its boundaries make extraction a contained change. Many teams start here and extract only the few modules that earn it.

    Scene: Ordering, Catalog and Notifications run in one process with their schemas; Payments runs as its own service. Shoppers send 20 orders per second and all succeed.

    Key idea: Get the boundaries right in one process; distribute only the modules that need it.