Skip to content
Katabench
Try free
8 min read The Katabench team

Modular monolith: what makes a module boundary real

A modular monolith holds only when crossing a boundary fails a build or a query. Three checks separate real modules from folders with good names.

Here is a review comment you may have written: "Why does renaming a column in Reservations also change Housekeeping, Loyalty and the invoice PDF?" Take a hypothetical hotel system to see how it happens. Housekeeping joins the stays table to decide when to clean a room. Loyalty reads the same table to award points. The invoice template formats the persistence row directly. The solution has four folders named after four modules, and a one-column rename still has to land in all of them in a single commit.

That codebase calls itself a modular monolith. A modular monolith is one deployable application divided into modules that can change independently. Independence comes from three properties: each module owns its data, other modules reach it only through a published contract, and a broken dependency rule fails something automatically.

Same folders, different boundaries

Data ownership

Folder only

Housekeeping joins reservations.stays to plan cleaning.

Boundary holds

Housekeeping's role gets: permission denied for schema reservations.

Public contract

Folder only

The invoice template formats a StayRow, so a column rename breaks it.

Boundary holds

Callers see DepartureInfo. StayRow is internal to the module.

Enforced dependencies

Folder only

Reservations → Loyalty → Housekeeping → Reservations compiles in one project.

Boundary holds

The same loop across project references fails with MSB4006.

Each right-hand box is a failure a tool raises on its own: the database, the compiler or the build. Nobody has to catch the violation in review.

Give every module its own data

Shared tables are the strongest coupling in a monolith because they bypass every abstraction in the code. If Housekeeping can read reservations.stays, then the shape of that table is public API, whatever the architecture diagram says.

In PostgreSQL, a schema per module plus a role per module turns the rule into an error. By default, users cannot access objects in schemas they do not own until the owner grants USAGE, so the useful move is to grant nothing:

SQL
CREATE ROLE reservations_app;
CREATE ROLE housekeeping_app;

CREATE SCHEMA reservations AUTHORIZATION reservations_app;
CREATE SCHEMA housekeeping AUTHORIZATION housekeeping_app;

CREATE TABLE reservations.stays (
    room_no      text PRIMARY KEY,
    check_out_on date NOT NULL
);
ALTER TABLE reservations.stays OWNER TO reservations_app;

SET ROLE housekeeping_app;
SELECT room_no, check_out_on FROM reservations.stays;
-- ERROR:  permission denied for schema reservations

Separate roles usually mean separate connection pools, so some teams start with one role and put the rule in a test that scans for cross-schema queries. That is weaker, because a test only covers the SQL it can find, but it still catches the casual join in a pull request.

Owning data has consequences you should accept before you start. Other modules store a room number as a plain value, with no foreign key into reservations. A report that needs data from three modules cannot use a three-way join, so it reads a projection built for reporting or asks each module through its contract. The same database also makes a transaction across modules possible, and each one you write ties those modules' commits together. Keep transactions inside a module and let the others react to a domain or integration event. If two modules truly must commit together every time, consider whether they are one module.

Publish answers instead of rows

A contract should answer the question the caller has. Housekeeping wants to know when a room empties, and it has no use for how Reservations stores that fact:

C#
// Project: Reservations.Contracts. Other modules compile against this and nothing else.
public interface IStayLookup
{
    Task<DepartureInfo?> FindDepartureAsync(string roomNumber, CancellationToken ct);
}

public sealed record DepartureInfo(string RoomNumber, DateOnly Date, bool LateCheckout);

// Project: Reservations. The storage shape can change with the next migration.
internal sealed class StayRow
{
    public required string RoomNo { get; init; }
    public required DateOnly CheckOutOn { get; init; }
    public required string ExtrasCsv { get; init; }
}

internal sealed class StayLookup(Func<string, StayRow?> findRow) : IStayLookup
{
    public Task<DepartureInfo?> FindDepartureAsync(string roomNumber, CancellationToken ct)
    {
        var row = findRow(roomNumber);
        return Task.FromResult(row is null
            ? null
            : new DepartureInfo(row.RoomNo, row.CheckOutOn, row.ExtrasCsv.Contains("LATE")));
    }
}

ExtrasCsv is a bad column, and that is fine, because no caller ever sees it and Reservations can normalize it next month without telling anyone.

In C#, the compiler can hold this line. internal types are only accessible within their assembly, so a project per module gives the keyword something to enforce. Reaching for the row from another project gets this:

Text
error CS0122: 'StayRow' is inaccessible due to its protection level

Splitting contracts into their own project is stronger still. Housekeeping references only Reservations.Contracts, so the implementation is not on its compile path at all and the same line fails with CS0234, because that namespace does not exist as far as the project can see. Only the composition root references every implementation, and it is the one place allowed to wire them together.

Languages without assembly-level visibility need an equivalent mechanism, such as a module system, package-private types or an import linter in CI.

Make the dependency graph fail loudly

Modules should form a directed acyclic graph, so that any module can be understood and tested with only the things beneath it. Suppose Reservations calls Loyalty to award points, Loyalty asks Housekeeping whether a room was upgraded, and Housekeeping asks Reservations for the departure time. Now none of the three can change alone.

With one project per module, the build rejects that loop. Two projects that reference each other stop at restore:

Text
error MSB4006: There is a circular dependency in the target dependency graph

Put the same modules in namespaces inside one project and the code compiles without a warning. Two classes in two namespaces, each naming the other, build cleanly. That is why a single-project modular monolith needs architecture fitness functions to carry the rule.

Two projects in a reference cycle fail restore with MSB4006. The same cycle across two namespaces in one project builds with zero warnings.

Breaking a cycle takes more thought than deleting the arrow that looks wrong, because the reason for each dependency decides the fix:

  1. Invert a call. Reservations publishes that a guest checked out, and Loyalty subscribes. Reservations no longer knows Loyalty exists.
  2. Pass the fact in. If Loyalty needs one value from Housekeeping and its caller already has it, take it as a parameter and delete the reference.
  3. Merge the modules. Two modules that change together in nearly every pull request were probably one module, and finding that out now costs one refactor.

Choosing it over a layered monolith or microservices

A layered monolith organizes code by technical role: controllers, services, repositories. Any feature cuts across all of them, and nothing stops one feature's service from using another feature's repository. It works while one small team keeps the whole model in their heads. Once unrelated changes keep colliding, reorganizing around business capabilities is the cheaper fix.

Microservices buy things a module cannot provide: independent deployment, independent scaling, a separate failure domain and freedom to use a different stack. A modular monolith has one process, so a memory leak in Housekeeping takes Reservations down with it, and one module's bad migration blocks everyone's release. If those are your actual problems, modules will not solve them.

The price is what Martin Fowler calls the microservice premium: automated deployment, monitoring, failure handling and eventual consistency, all of which slow a team down before they pay anything back. His Monolith First note adds the argument that matters most here: boundaries are hard to get right early, and moving functionality between services is much harder than moving it inside a monolith, where correcting a bad boundary takes a pull request.

Shopify has published its own account of this choice. With more than a thousand developers on a Rails codebase over a decade old, it reorganized around business domains instead of moving to services, aiming for a dedicated interface and exclusive data ownership per component. The same article says enforcement was still being worked out at the time of writing.

Do not treat extraction as free just because the boundary exists. As an in-process call, IStayLookup adds no network failure mode of its own. Move Reservations behind a network and the same interface needs timeouts, retries and idempotent operations. A good contract keeps its shape through that move, and its failure model changes completely.

Three breaks to try on your own modules

You can measure your boundaries this afternoon. Rename a private column in one module and count how many other modules the change touches; the target is zero. Connect as one module's database identity and select from another module's table, which should fail. Add a forbidden project reference or import in a throwaway branch and see whether CI turns red, because if it stays green the rule exists only in your wiki.

Most bad fixes to a tangle like this keep every behavior test green, which is the trap in Break the Checkout Cycle: the output has to stay byte-for-byte identical while design rules judge the import graph.

Practice what you just read

  • Architecture Hard Free, no account needed

    Break the Checkout Cycle

    Orders, Pricing and Promotions import each other in a three-hop cycle while Pricing also reaches into Inventory's internals. Moving the obvious call only rotates the cycle; hoist the shared vocabulary into a kernel leaf and reach Inventory through its published port to turn every rule green.

    Open in the editor: Break the Checkout Cycle
  • Architecture Hard Katabench Pro

    Own Your Data Boundary

    Billing bypasses Orders' published surface and reads its internal database rows directly. Route the question through an Orders-owned query API, but do not mistake a port that returns the private row for a real boundary.

    Open the Pro kata: Own Your Data Boundary

More like this: C# architecture exercises →

Get new katas and .NET tips in your inbox

A short note when fresh kata land, plus the C# and performance tricks behind the grading. No spam, unsubscribe anytime.