StackPractices
intermediate By Mathias Paulenko

Modular Monolith: Single Deployable with Module Boundaries

How to build a modular monolith with strict internal module boundaries. Covers module isolation, shared kernel, inter-module communication, and migration to microservices.

Overview

A modular monolith is a single deployable application with strict internal module boundaries. Each module owns its data, exposes a public API, and talks to other modules only through that API or through domain events — never through another module’s internals. One build, one process, usually one database; inside, the code is partitioned as if it were already several services.

The pattern exists because most teams don’t actually need microservices — they need the boundaries microservices force on you. A classic layered monolith lets any controller import any repository, so over time every change touches everything. The modular monolith keeps the cheap operations (no network, no distributed transactions, one deploy pipeline) while making “who may call what” an architectural rule instead of a convention people forget under deadline pressure.

The real payoff shows up later. If a module’s boundaries held — its own tables, its own schema, all cross-talk through events or a thin facade — extracting it into a separate service is a deployment change, not a rewrite. The modular monolith guide walks through how to find those boundaries in a real domain; this page is the structural recipe for keeping them intact.

When to Use

  • Small to medium teams that want clean architecture without operating a distributed system.
  • Startups that need to ship fast but expect to extract services later — the boundaries are the insurance policy.
  • Domains that partition naturally into bounded contexts (orders, catalog, billing, shipping).
  • Teams migrating off a big ball of mud: re-modularize inside the existing monolith before paying for distribution.
  • Systems where deployment simplicity matters more than scaling modules independently.

When NOT to Use

  • Parts of the system genuinely need independent scaling — a hot read path next to a batch writer argues for separate deployables.
  • Teams large enough that a single repo creates merge contention; at some point the boundary enforcement cost exceeds the coordination cost of separate repos.
  • Modules with wildly different availability or compliance requirements — a module that needs five-nines shouldn’t share a fate with a reporting module.
  • Hard real-time paths where even in-process indirection is a problem. Rare, but it exists.

How It Works

The pattern is three rules, enforced mechanically:

  1. Public API per module. Each module exposes a small surface — a facade, an interface, a package __all__. Everything else is internal. In Python that’s package exports; in Java it’s package-private classes plus module-info; in C# it’s internal. Other modules may only touch the public surface.
  2. Data ownership. Each module owns its tables (or its schema). No cross-module foreign keys — references travel as IDs. This is what makes extraction possible later.
  3. Mediated communication. Cross-module calls go through the public API, or better, through domain events on an in-process bus. If module A imports module B’s internal package, the build should fail — enforced in CI, not in code review.
flowchart diagram: subgraph APP[Single deployable

A boundary that exists only in a style guide dies in the first sprint crunch. Architecture tests — ArchUnit, import-linter, a small AST script — make the rule executable. The companion repo for this site ships exactly such a boundary linter you can adapt in an afternoon.

Solution

Module structure (Python)

# order_module/__init__.py — Order module public API
from order_module.api import OrderAPI

__all__ = ["OrderAPI"]

# The module only exposes what's in __all__
# Internal classes are not importable from outside
# order_module/services.py — Order module internal implementation
from order_module.models import Order, OrderItem
from order_module.repository import OrderRepository
from shared_kernel.events import OrderCreatedEvent, OrderCancelledEvent
from shared_kernel.ids import OrderId, CustomerId
from typing import Optional, List

class OrderService:
    """Internal service — not part of the module's public API."""

    def __init__(self, repo: OrderRepository, event_bus: 'EventBus'):
        self._repo = repo
        self._event_bus = event_bus

    def create_order(self, customer_id: CustomerId, items: List[OrderItem]) -> Order:
        order = Order.create(customer_id, items)
        self._repo.save(order)

        self._event_bus.publish(OrderCreatedEvent(
            order_id=order.id,
            customer_id=customer_id,
            total=order.total
        ))
        return order

    def get_order(self, order_id: OrderId) -> Optional[Order]:
        return self._repo.find_by_id(order_id)

    def cancel_order(self, order_id: OrderId) -> None:
        order = self._repo.find_by_id(order_id)
        if order is None:
            raise ValueError(f"Order {order_id} not found")

        order.cancel()
        self._repo.save(order)
        self._event_bus.publish(OrderCancelledEvent(order_id=order_id))
# order_module/api.py — Order module public API (the contract)
from order_module.services import OrderService
from order_module.models import OrderItem
from shared_kernel.ids import OrderId, CustomerId
from typing import Optional, List, Dict, Any

class OrderAPI:
    """Public API of the Order module. Other modules use only this."""

    def __init__(self, service: OrderService):
        self._service = service

    def create_order(self, customer_id: str, items: List[Dict[str, Any]]) -> Dict[str, Any]:
        customer = CustomerId.from_string(customer_id)
        order_items = [OrderItem.from_dict(item) for item in items]
        order = self._service.create_order(customer, order_items)
        return order.to_dict()

    def get_order(self, order_id: str) -> Optional[Dict[str, Any]]:
        order = self._service.get_order(OrderId.from_string(order_id))
        return order.to_dict() if order else None

    def cancel_order(self, order_id: str) -> None:
        self._service.cancel_order(OrderId.from_string(order_id))

Notice the direction of the dependencies: the public API wraps the internal service, callers outside the module see only OrderAPI, and the service publishes events instead of calling the inventory module directly. When a module’s event handlers run in the same process, a failure in a subscriber shouldn’t kill the publisher — the event bus below logs handler errors and keeps going.

Shared kernel

The shared kernel is the only code modules are allowed to share: IDs, event definitions, maybe a few value objects. No business logic — the moment a rule lives in the kernel, every module owns it and extraction gets painful.

# shared_kernel/ids.py — Shared value objects used across modules
from dataclasses import dataclass
import uuid

@dataclass(frozen=True)
class OrderId:
    value: str

    @staticmethod
    def from_string(s: str) -> 'OrderId':
        return OrderId(s)

    @staticmethod
    def generate() -> 'OrderId':
        return OrderId(str(uuid.uuid4()))

@dataclass(frozen=True)
class CustomerId:
    value: str

    @staticmethod
    def from_string(s: str) -> 'CustomerId':
        return CustomerId(s)

@dataclass(frozen=True)
class ProductId:
    value: str

    @staticmethod
    def from_string(s: str) -> 'ProductId':
        return ProductId(s)
# shared_kernel/events.py — Event bus for inter-module communication
from typing import Callable, Dict, List, Type
from dataclasses import dataclass
from shared_kernel.ids import OrderId, CustomerId
import logging

logger = logging.getLogger(__name__)

@dataclass
class DomainEvent:
    """Base class for all domain events."""
    pass

class EventBus:
    """In-process event bus for inter-module communication.
    Modules communicate through events, not direct calls."""

    def __init__(self):
        self._handlers: Dict[Type[DomainEvent], List[Callable]] = {}

    def subscribe(self, event_type: Type[DomainEvent], handler: Callable):
        if event_type not in self._handlers:
            self._handlers[event_type] = []
        self._handlers[event_type].append(handler)

    def publish(self, event: DomainEvent):
        event_type = type(event)
        handlers = self._handlers.get(event_type, [])

        for handler in handlers:
            try:
                handler(event)
            except Exception as e:
                logger.error(f"Event handler failed for {event_type.__name__}: {e}")

# Event definitions — typed with shared kernel IDs, not raw strings
@dataclass
class OrderCreatedEvent(DomainEvent):
    order_id: OrderId
    customer_id: CustomerId
    total: float

@dataclass
class OrderCancelledEvent(DomainEvent):
    order_id: OrderId

@dataclass
class PaymentProcessedEvent(DomainEvent):
    order_id: OrderId
    amount: float

Module wiring

The composition root is the one place that sees every module’s internals — it builds repositories, services, and APIs, then wires event subscriptions across modules. Nothing else is allowed to do this; if a module instantiates another module’s service, the boundary is already broken.

# app.py — Application composition root
from order_module import OrderAPI
from order_module.services import OrderService
from order_module.repository import OrderRepository
from customer_module import CustomerAPI
from customer_module.services import CustomerService
from customer_module.repository import CustomerRepository
from inventory_module import InventoryAPI
from inventory_module.services import InventoryService
from inventory_module.repository import InventoryRepository
from shared_kernel.events import EventBus, OrderCreatedEvent
from database import Database

def create_app():
    # Shared infrastructure
    db = Database("postgresql://localhost/shop")
    event_bus = EventBus()

    # Order module
    order_repo = OrderRepository(db)
    order_service = OrderService(order_repo, event_bus)
    order_api = OrderAPI(order_service)

    # Customer module
    customer_repo = CustomerRepository(db)
    customer_service = CustomerService(customer_repo, event_bus)
    customer_api = CustomerAPI(customer_service)

    # Inventory module
    inventory_repo = InventoryRepository(db)
    inventory_service = InventoryService(inventory_repo, event_bus)
    inventory_api = InventoryAPI(inventory_service)

    # Cross-module event subscriptions
    # When an order is created, reserve inventory
    event_bus.subscribe(OrderCreatedEvent, inventory_service.reserve_items)

    return {
        "orders": order_api,
        "customers": customer_api,
        "inventory": inventory_api,
    }

Module isolation enforcement (Python)

Rules nobody checks don’t survive a deadline. This AST-based checker parses every file, maps it to its owning module, and flags any import that reaches into another module’s internals. Run it in CI next to your unit tests; it takes minutes to write and hours of arguments to skip.

# enforce_boundaries.py — static analysis to enforce module boundaries
import ast
from pathlib import Path
from typing import Set, Dict, List

class ModuleBoundaryChecker:
    """Check that modules don't import each other's internals."""

    def __init__(self, root: str, modules: Dict[str, Set[str]]):
        self.root = Path(root)
        self.modules = modules  # {module_name: {allowed_imports}}

    def check(self) -> List[str]:
        violations = []

        for py_file in self.root.rglob("*.py"):
            rel_path = py_file.relative_to(self.root)
            parts = rel_path.parts

            # Determine which module this file belongs to
            current_module = parts[0] if parts else None
            if current_module not in self.modules:
                continue

            # Parse imports
            tree = ast.parse(py_file.read_text())
            for node in ast.walk(tree):
                if isinstance(node, ast.ImportFrom):
                    module = node.module or ""
                    for import_name in [alias.name for alias in node.names]:
                        full_import = f"{module}.{import_name}" if module else import_name

                        # Check if importing from another module's internals
                        for other_module in self.modules:
                            if other_module == current_module:
                                continue
                            if full_import.startswith(other_module) and \
                               full_import not in self.modules[other_module]:
                                violations.append(
                                    f"{rel_path}: imports {full_import} from "
                                    f"{other_module} (not in public API)"
                                )

        return violations

# Usage
checker = ModuleBoundaryChecker("src/", {
    "order_module": {"order_module.OrderService", "order_module.OrderAPI"},
    "customer_module": {"customer_module.CustomerService", "customer_module.CustomerAPI"},
    "inventory_module": {"inventory_module.InventoryService", "inventory_module.InventoryAPI"},
})

violations = checker.check()
for v in violations:
    print(f"VIOLATION: {v}")

For a battle-tested version of this idea in Java, ArchUnit encodes the same rule in one line: noClasses().that().resideInAPackage("..order.internal..").should().bePublic(). The ecosystem has equivalents everywhere — import-linter for Python, Nx module boundaries for TypeScript monorepos, JPMS for JVM apps that want the compiler itself to refuse illegal access.

Java modular monolith with Spring

// OrderModule.java — Spring module with package-private internals
package com.shop.order;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

// Public API — only what's exposed to other modules
@Configuration
@Import(OrderPublicConfig.class)
public class OrderModule {

    @Bean
    public OrderFacade orderFacade(OrderService service) {
        return new OrderFacade(service);
    }
}

// OrderFacade — the public interface other modules use
package com.shop.order.api;

public interface OrderFacade {
    OrderDto createOrder(String customerId, List<OrderItemDto> items);
    OrderDto getOrder(String orderId);
    void cancelOrder(String orderId);
}

// Internal service — package-private, not accessible outside
package com.shop.order.internal;

import org.springframework.stereotype.Service;
import org.springframework.context.ApplicationEventPublisher;

@Service
class OrderServiceImpl implements OrderService {

    private final OrderRepository repository;
    private final ApplicationEventPublisher eventPublisher;

    OrderServiceImpl(OrderRepository repository,
                     ApplicationEventPublisher eventPublisher) {
        this.repository = repository;
        this.eventPublisher = eventPublisher;
    }

    @Override
    public Order createOrder(CustomerId customerId, List<OrderItem> items) {
        var order = Order.create(customerId, items);
        repository.save(order);

        eventPublisher.publishEvent(new OrderCreatedEvent(
            order.getId(), customerId, order.getTotal()
        ));

        return order;
    }
}

Spring Modulith formalizes this layout — it treats top-level packages as modules, verifies the boundaries for you, and can even document the module graph. Worth adopting before hand-rolling conventions.

Database schema isolation

-- Each module owns its tables — prefixed by module name
-- No cross-module foreign keys (use reference IDs instead)

-- Order module tables
CREATE TABLE order_orders (
    id UUID PRIMARY KEY,
    customer_id UUID NOT NULL,  -- reference, not FK
    status VARCHAR(50) NOT NULL,
    total DECIMAL(10, 2) NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

CREATE TABLE order_items (
    id UUID PRIMARY KEY,
    order_id UUID NOT NULL REFERENCES order_orders(id),
    product_id UUID NOT NULL,  -- reference, not FK
    quantity INT NOT NULL,
    price DECIMAL(10, 2) NOT NULL
);

-- Customer module tables
CREATE TABLE customer_customers (
    id UUID PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    name VARCHAR(255) NOT NULL,
    status VARCHAR(50) NOT NULL
);

-- Inventory module tables
CREATE TABLE inventory_products (
    id UUID PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    stock INT NOT NULL,
    price DECIMAL(10, 2) NOT NULL
);

-- No FK from order_orders.customer_id to customer_customers.id
-- The relationship is enforced in application code, not the database

Dropping cross-module foreign keys is the step teams resist most, and it’s the one that matters most. A foreign key between order_orders and customer_customers hard-wires two modules into the same database forever. Reference IDs plus application-level integrity checks buy you the option to move a module’s tables into their own database without rewriting a single JOIN — because there are no cross-module JOINs.

Variants

Module-as-package (lightweight isolation)

# Lightweight: modules are Python packages with __all__ controlling exports
# No separate database schemas, but code-level isolation

# catalog/__init__.py
from catalog.service import CatalogService
__all__ = ["CatalogService"]

# Other modules can only import CatalogService
# from catalog import CatalogService  ✅
# from catalog.service import _internal_helper  ❌ (convention, not enforced)

The cheapest form: packages with explicit exports and a boundary checker in CI. Isolation lives in code only; the database stays shared with table prefixes. Right choice for a young codebase — you’re paying for discipline, not infrastructure.

Module-as-subsystem (strict isolation with separate schemas)

-- Each module gets its own database schema
CREATE SCHEMA IF NOT EXISTS order_module;
CREATE SCHEMA IF NOT EXISTS customer_module;
CREATE SCHEMA IF NOT EXISTS inventory_module;

-- Tables are fully isolated
CREATE TABLE order_module.orders (...);
CREATE TABLE customer_module.customers (...);
CREATE TABLE inventory_module.products (...);

-- Modules access only their own schema
GRANT USAGE ON SCHEMA order_module TO order_app_role;
GRANT USAGE ON SCHEMA customer_module TO customer_app_role;

One database server, separate schemas, separate roles. The database itself refuses cross-module access — the strongest boundary you can get without splitting deployables. This is the variant that makes later extraction nearly mechanical: dump the schema, point the module at a new database, done.

What Works

  • Define a public API for each module — only expose what other modules need.
  • Use an event bus for cross-module communication — don’t call other modules directly.
  • No cross-module database access — each module owns its tables; use reference IDs, not foreign keys.
  • Enforce boundaries with static analysis in CI — a rule nobody checks isn’t a rule.
  • Keep the shared kernel small — only IDs, events, and value objects.
  • One team per module — shared ownership is no ownership.
  • Design contracts carefully — the module API is the contract; version it like one.
  • Design for extraction from day one — pretend the split is coming, even if it never does.

Common Mistakes

  • No boundary enforcement: modules import each other’s internals “just this once” and the monolith tangles again. Put the checker in CI from day one.
  • Shared database tables: modules query each other’s tables directly. Extraction then requires rewriting every cross-module query instead of moving a schema.
  • Direct service calls: OrderService calls CustomerService directly and now every test needs both. Use events for side effects and the public facade for queries.
  • Bloated shared kernel: business logic migrates into the kernel because “both modules need it”. Keep it to IDs, events, and value objects — if two modules need the same rule, one of them owns it and the other calls the API.
  • No module ownership: anyone can modify any module, so nobody protects the boundaries. Assign owners like you’d assign services.

See Also

Frequently Asked Questions

What is a modular monolith?

A single deployable application with strict internal module boundaries. Each module owns its data, exposes a public API, and communicates with other modules through events or facades. It's a monolith in deployment but modular in design.

How is a modular monolith different from microservices?

A modular monolith deploys as one unit with one database. Microservices deploy independently with separate databases. A modular monolith is simpler to operate but can't scale modules independently. Modules can be extracted to microservices later.

How do modules communicate in a modular monolith?

Through domain events on an in-process bus, or through the other module's public API for synchronous queries. Module A publishes an event when something happens; Module B subscribes and reacts. For queries, A calls B's facade — never its internal service or its tables.

Should modules share a database?

They can share a database server but should use separate schemas or table prefixes with no cross-module foreign keys. That keeps the option open of moving a module's tables to their own database later without rewriting JOINs that never existed.

When should I extract a module to a microservice?

When the module needs independent scaling, a different availability target, or its own deploy cadence. Extraction is nearly free when the boundaries held; if modules share tables and internal calls, you rebuild the boundary first and extract second.