Manoj Yadav

Modular Monoliths: Single-Image Runtime Composition

There is a common architectural dilemma when building a system with multiple domain services:

Do you split the project into a microservices monorepo with separate Dockerfiles for each service, or do you build a single monolithic container?

In building my self-hosted ERP and household management platform (Prabandh), I ran into this exact problem. The backend spans multiple domains: authentication (pehchan), finance and expenses (paisa), household inventory (ghar), and automations.

Splitting them into separate microservice repositories or separate Docker images created massive operational pain:

  1. Shared code duplication: Every service needed identical database connection pools, JWT verification, logging formatters, and middleware.
  2. Slow builds: Publishing changes required building, tagging, and pushing six separate Docker images on every release.
  3. Inflexible deployments: A user running on a Raspberry Pi couldn’t easily choose to run everything in a single lightweight process without maintaining separate configuration trees.

Instead of fighting microservices overhead, I adopted an architectural pattern: Modular Monolith with Single-Image Runtime Composition.


How It Works

This pattern is inspired by tools like Grafana Loki (with its -target CLI flag) and Thanos:

Instead of building 6 different container images, we build one single container image (prabandh-backend:latest). What actually runs inside the container is controlled entirely by an environment variable at startup: PRABANDH_MODULES.

                    ┌─────────────────────────────────┐
                    │  prabandh-backend:latest Image  │
                    └────────────────┬────────────────┘
                                     │
           ┌─────────────────────────┼─────────────────────────┐
           ▼                         ▼                         ▼
   [ Container 1 ]           [ Container 2 ]           [ Container 3 ]
  PRABANDH_MODULES=paisa    PRABANDH_MODULES=ghar     PRABANDH_MODULES=*
  (Only loads finance)      (Only loads inventory)    (All-in-one for small SBCs)

The Directory Structure

The code is organized with strict isolation:

app/
├── core/             # Global settings, config schemas, middleware
├── platform/         # Shared infra (db engine, auth checks, outbox)
└── modules/          # Isolated business domains
    ├── pehchan/      # Identity & user accounts
    ├── paisa/        # Transactions, bills, ledger
    ├── ghar/         # Household inventory
    └── yantra/       # IoT & device controls

Dynamic Module Loading

When a container spins up, a lightweight loader inspects PRABANDH_MODULES. If the environment specifies paisa, the loader dynamically imports only the routes, background tasks, and models for paisa.

Modules that are not active are never imported into memory.

# app/platform/loader.py (Simplified)
import os
import importlib

active_modules = os.getenv("PRABANDH_MODULES", "*").split(",")

for module_name in discovered_modules:
    if "*" in active_modules or module_name in active_modules:
        mod = importlib.import_module(f"app.modules.{module_name}.router")
        app.include_router(mod.router, prefix=f"/api/v1/{module_name}")

Preventing Code Spaghetti: Enforcing Boundaries

The common risk with monoliths is that developers start importing models and helpers from neighboring modules until the architecture becomes a tangled ball of yarn.

To strictly enforce boundaries without splitting the code into separate repos, we use import linter in our CI pipeline:

# .importlinter
[importlinter]
root_package = app

[importlinter:contract:module-isolation]
name = Domain modules cannot import each other
type = forbidden
source_modules =
    app.modules.paisa
forbidden_modules =
    app.modules.ghar

If an endpoint in the finance module tries to directly import code from the inventory module, the CI test suite fails immediately. Any communication between domains must happen over explicit API contracts or an internal event bus.


The Benefits

  1. One image to build and cache: CI builds a single Docker image once. It takes seconds instead of minutes.
  2. Zero code duplication: Core utilities (database connections, JWT middleware, telemetry) live in one place without needing a private PyPI package.
  3. Deployment flexibility:
    • A single-board computer (Raspberry Pi) runs one container with PRABANDH_MODULES=*.
    • A multi-node cluster runs split containers with dedicated CPU and memory limits per domain via docker-compose.split.yml.

You get all the deployment flexibility of microservices with the developer ergonomics and build speeds of a clean monolith.