Polski

Article · Modular Monolith · Monolith

The Modular Monolith: hard boundaries without the cost of the network

One process and one deployment, but modules with a public API, their own data and communication through events. How to build it in .NET, Java (Spring Modulith), Node.js, Go and Python, and how to guard the boundaries with tests.

By · · 13 min read

After two years, the system of Halina's pierogi place serves a chain of three restaurants, catering and a loyalty programme. Three teams work on it, and an ordinary change in orders can break the points calculation. Instead of immediately cutting the system into microservices, the team chooses a modular monolith: still one deployment, but with boundaries that the compiler and the tests guard as strictly as the network guards service boundaries.

1
process and one deployment – just like a plain monolith
3–10
typical number of modules – one per business area
0
network calls between modules – a network error is not a scenario

Context and forces

The pierogi place's classic monolith began to resemble a big ball of mud: the Customer class has fields for sales, delivery and loyalty, and the kitchen report does a JOIN over seven tables owned by different areas. The forces to reconcile:

  • Team independence – the loyalty team wants to change its model without asking the orders team for permission.
  • Operational cost – nobody wants to maintain ten pipelines, a message broker and distributed tracing for a system that fits on two servers.
  • Data consistency – some operations still need a transaction, but not all of them.
  • An option for the future – if catering grows tenfold, it should be possible to extract it without a rewrite.

If you can't build a well-structured monolith, what makes you think microservices are the answer?

— Simon Brown, creator of the C4 model

Structure

A module is a vertical slice of the system around one business capability, not a technical layer. It has three parts: a public contract (facade, commands, queries, integration events), an interior (domain, use cases, data access) and its own data.

Diagram: Modules in one process: contracts outside, interior hidden
RuleWhat it means in practice
Public module APIOther modules see only contracts: the facade interface, DTOs, events. Everything else is internal, in an internal package or in an internal/ directory
Data ownershipA module has its own schema or table prefix; nobody else runs a SELECT or JOIN on them
CommunicationSynchronously through the facade (when an answer is needed) or asynchronously through events (when a reaction is enough)
No cyclesThe dependency graph between modules is acyclic – otherwise it's one module in disguise
Little shared codeThe shared part is infrastructure (event bus, Result), never business logic

What it looks like in code

Each stack has its own mechanism for hiding the interior: in .NET separate projects and internal, in Java the Spring Modulith package convention, in Node.js a public index.ts and linter rules, in Go the internal/ directory enforced by the compiler, in Python the underscore convention checked by a test.

Module structure in five stacks

dotnet/solution-tree.txt
src/
├── Pierogarnia.Host/                    ← the only deployable: Program.cs wires all modules
├── Modules/
│   ├── Orders/
│   │   ├── Pierogarnia.Orders.Contracts/  ← PUBLIC: IOrdersModule, OrderPlaced (integration event)
│   │   └── Pierogarnia.Orders.Core/       ← INTERNAL: domain, handlers, OrdersDbContext (schema "orders")
│   ├── Kitchen/
│   │   ├── Pierogarnia.Kitchen.Contracts/
│   │   └── Pierogarnia.Kitchen.Core/
│   └── Loyalty/
│       ├── Pierogarnia.Loyalty.Contracts/
│       └── Pierogarnia.Loyalty.Core/      ← may reference Orders.Contracts, never Orders.Core
└── Pierogarnia.Shared/                  ← tiny: event bus abstraction, Result type. No business logic.
java/spring-modulith-tree.txt
src/main/java/pl/pierogarnia/
├── PierogarniaApplication.java          ← @SpringBootApplication, the only deployable
├── orders/                              ← application module (top-level package)
│   ├── OrdersApi.java                   ← public: classes in the module's base package
│   ├── OrderPlaced.java                 ← public event record
│   └── internal/                        ← hidden from other modules (Spring Modulith rule)
│       ├── Order.java
│       └── OrderRepository.java
├── kitchen/
│   └── ...
└── loyalty/
    ├── LoyaltyApi.java
    └── internal/OrderPlacedListener.java
node/nx-workspace-tree.txt
apps/
└── pierogarnia/                         ← the only deployable (NestJS)
    └── src/app.module.ts                ← imports OrdersModule, KitchenModule, LoyaltyModule
libs/
├── orders/
│   ├── src/index.ts                     ← PUBLIC barrel: OrdersService, OrderPlacedEvent
│   └── src/lib/internal/                ← everything else, never imported directly
├── kitchen/
└── loyalty/                             ← lint rule: may import "@pierogarnia/orders", not its internals
go/module-tree.txt
pierogarnia/
├── cmd/pierogarnia/main.go              ← the only binary
└── internal/
    ├── orders/
    │   ├── orders.go                    ← PUBLIC API of the module: type Module, func (m *Module) Place(...)
    │   └── internal/                    ← compiler-enforced: only internal/orders/... may import it
    │       ├── domain/
    │       └── store/                   ← tables in schema "orders"
    ├── kitchen/
    └── loyalty/
python/package-tree.txt
pierogarnia/
├── main.py                              ← the only deployable (FastAPI app)
├── orders/
│   ├── __init__.py                      ← PUBLIC: from .api import place_order, OrderPlaced
│   ├── api.py
│   └── _internal/                       ← underscore = private by convention, checked by a test
├── kitchen/
└── loyalty/

Boundaries that nobody checks disappear within a few months. That's why the architecture test is part of the module just like the domain tests:

Module boundary tests

ModuleBoundaryTests.cs
using System.Reflection;
using NetArchTest.Rules;

public class ModuleBoundaryTests
{
    // One marker type per module implementation assembly
    private static readonly Dictionary<string, Assembly> Modules = new()
    {
        ["Orders"] = typeof(Pierogarnia.Orders.Core.OrdersModule).Assembly,
        ["Kitchen"] = typeof(Pierogarnia.Kitchen.Core.KitchenModule).Assembly,
        ["Loyalty"] = typeof(Pierogarnia.Loyalty.Core.LoyaltyModule).Assembly,
    };

    public static IEnumerable<object[]> ModuleNames => Modules.Keys.Select(k => new object[] { k });

    [Theory]
    [MemberData(nameof(ModuleNames))]
    public void A_module_never_depends_on_the_internals_of_another(string module)
    {
        var forbidden = Modules.Keys
            .Where(m => m != module)
            .Select(m => $"Pierogarnia.{m}.Core")   // internals; "Pierogarnia.Orders.Contracts" stays allowed
            .ToArray();

        var result = Types.InAssembly(Modules[module])
            .ShouldNot()
            .HaveDependencyOnAny(forbidden)
            .GetResult();

        Assert.True(result.IsSuccessful,
            $"{module} reaches into another module: " + string.Join(", ", result.FailingTypeNames ?? []));
    }
}
ModularityTests.java
import org.junit.jupiter.api.Test;
import org.springframework.modulith.core.ApplicationModules;
import org.springframework.modulith.docs.Documenter;

class ModularityTests {

    private final ApplicationModules modules = ApplicationModules.of(PierogarniaApplication.class);

    @Test
    void modulesRespectTheirBoundaries() {
        // Fails when "loyalty" touches a type in "orders.internal" or when modules form a cycle.
        modules.verify();
    }

    @Test
    void writeDocumentation() {
        // Generates C4-style component diagrams of the modules (PlantUML) into target/spring-modulith-docs.
        new Documenter(modules).writeModulesAsPlantUml();
    }
}
.dependency-cruiser.js
/** Run in CI: npx depcruise libs --config .dependency-cruiser.js */
module.exports = {
  forbidden: [
    {
      name: "no-reaching-into-other-modules",
      comment: "A module may import another module only through its public index.ts",
      severity: "error",
      from: { path: "^libs/([^/]+)/" },
      to: {
        path: "^libs/([^/]+)/src/lib/",
        pathNot: "^libs/$1/", // its own internals are fine
      },
    },
    {
      name: "no-cycles-between-modules",
      severity: "error",
      from: { path: "^libs/" },
      to: { circular: true },
    },
  ],
  options: { tsConfig: { fileName: "tsconfig.base.json" } },
};
internal/loyalty/handler.go
package loyalty

import (
	"context"

	"pierogarnia/internal/orders" // OK: the public API of the orders module
	// "pierogarnia/internal/orders/internal/domain"
	// ^ does not compile: "use of internal package ... not allowed".
	//   Go enforces module boundaries in the compiler, no extra tooling needed.
)

type Module struct{ store pointsStore }

// OnOrderPlaced is subscribed to the in-process event bus in main.go.
func (m *Module) OnOrderPlaced(ctx context.Context, e orders.OrderPlaced) error {
	return m.store.AddPoints(ctx, e.CustomerID, int(e.Total))
}

type pointsStore interface {
	AddPoints(ctx context.Context, customerID string, points int) error
}
tests/test_module_boundaries.py
import ast
import pathlib

ROOT = pathlib.Path(__file__).parents[1] / "pierogarnia"
MODULES = {"orders", "kitchen", "loyalty"}


def imports_of(path: pathlib.Path) -> set[str]:
    tree = ast.parse(path.read_text(encoding="utf-8"))
    found = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            found |= {a.name for a in node.names}
        elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
            found.add(node.module)
    return found


def test_modules_use_only_public_apis_of_other_modules():
    leaks = []
    for module in MODULES:
        for file in (ROOT / module).rglob("*.py"):
            for name in imports_of(file):
                parts = name.split(".")
                # "pierogarnia.orders" is public, "pierogarnia.orders._internal..." is not
                if len(parts) > 2 and parts[1] in MODULES - {module} and parts[2].startswith("_"):
                    leaks.append(f"{file.relative_to(ROOT)} -> {name}")
    assert not leaks, "Module boundary violations:\n" + "\n".join(leaks)

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Trade-offs
  • Migration path
  • In practice
  • Anti-patterns
  • Related topics
  • Test yourself

Create a free account · Sign in