Modular Monolith
Intent
Keep a single deployable for operational simplicity while enforcing strict internal module boundaries so the system can evolve or split later.
When It Helps
- The team is growing (roughly 8–30 developers) and stepping on each other’s code.
- You suspect services will be needed eventually but the boundaries are not proven yet.
- You want independent development streams without paying for distributed operations today.
Structure
flowchart TB Clients --> Gateway[Single Entry Point] Gateway --> A[Module: Orders] Gateway --> B[Module: Catalog] Gateway --> C[Module: Billing] A -.->|public API only| SharedKernel[Shared Kernel] B -.->|public API only| SharedKernel C -.->|public API only| SharedKernel A --> DB[(Shared DB, Schema per Module)] B --> DB C --> DB
Deployment unit: one artifact containing all modules, deployed together. Communication: synchronous calls through each module’s public API only — no reaching into another module’s internals. Data ownership: each module owns its tables or schema; other modules read them only via the owning module’s API.
Rules
- Modules may depend only on another module’s declared public API, never on its internals.
- No shared mutable state between modules except through explicit APIs or events.
- Each module owns its data — cross-module queries go through the owner, not direct table joins.
- All modules version and deploy together; extraction to a service must not require rewriting callers.
Illustrative Snippet
Illustrative pseudocode — not runnable.
# sketch: enforced module boundary
module orders:
public: place_order(cart) -> order
private: tables orders, order_lines
module billing:
public: charge(order) -> receipt
private: tables invoices, payments
# allowed:
billing.charge(orders.place_order(cart))
# forbidden:
billing.read_table(orders.order_lines) # must call orders API
Basic Recap
A modular monolith keeps one process and deployment while assigning business capabilities to modules with explicit public APIs. Each module owns its data and hides internal implementation from other modules. The approach supports parallel development without introducing network failures between every capability. Its benefits depend on automated boundary enforcement, not folder names alone.
Complex Scenario
An education platform contains enrollment, billing, course delivery, and identity modules in a single deployable. Enrollment must confirm that a learner has an active entitlement before unlocking a course. To meet a deadline, enrollment imports billing’s repository and reads its tables directly. Billing then calls enrollment internals to revoke access after a refund, producing a cycle that only appears in full integration builds.
flowchart TB
Learners["Learner web app"] --> Entry["Single application entry point"]
Staff["Staff admin"] --> Entry
Entry --> Enrollment["Module: Enrollment"]
Entry --> Billing["Module: Billing"]
Entry --> Courses["Module: Course delivery"]
Entry --> Identity["Module: Identity"]
Enrollment --> EnrollAPI[["Enrollment public API"]]
Billing --> BillingAPI[["Billing public API"]]
Enrollment --> ESchema[("Enrollment schema")]
Billing --> BSchema[("Billing schema")]
Enrollment <-. "repository and internal-call cycle" .-> Billing
Events["In-process domain events"] --> Courses
BillingAPI --> Events
Failure walkthrough. A billing schema rename breaks enrollment at startup, while the dependency cycle prevents either module from being tested alone. During a refund burst, nested in-process calls also hold enrollment and billing transactions longer, causing lock contention across both schemas. Mitigate by exposing EntitlementQuery and RefundCompleted contracts, deleting cross-schema access, and enforcing an acyclic module graph in the build; keep cross-module transaction expectations explicit.
Edge cases — concurrent refunds need per-learner ordering or versioning, retries need idempotent entitlement revocation, and partial failure inside one transaction needs a documented commit boundary. In-process events dispatched after commit must not be lost when the process stops.
Sketch (illustrative pseudocode, not runnable):
module billing:
public:
EntitlementQuery.active?(learner_id, course_id)
events: RefundCompleted{refund_id, learner_id, version}
owns: billing_schema.*
transaction: commit_before_event_dispatch
module enrollment:
depends_on: [billing.public, identity.public]
owns: enrollment_schema.*
on RefundCompleted:
revoke_once(refund_id, learner_id)
architecture_test:
require: acyclic_public_dependencies
forbid: cross_module_table_access
Trade-offs
- Benefit: scales development — teams work in parallel inside clear boundaries without distributed-system overhead.
- Benefit: extraction is cheap later: a module with a clean API and owned data can become a service with minimal rewiring.
- Cost: boundary discipline needs tooling and reviews; without enforcement it decays back into a tangled monolith.
- Cost: runtime scaling is still all-or-nothing since every module ships in one process, and a faulty module can crash its neighbors.
When to Use / When Not to Use
Use when:
- One team needing boundaries first without service ops overhead.
- Extraction-ready structure before splitting.
Avoid when:
- Capabilities needing independent scaling/deploys now — go Microservices.
Anti-pattern / Failure Mode
- Misuse: Module boundaries only on paper, bypassed by direct DB access.
- Review signal: Cross-module imports with no fitness-function enforcement.
Failure Modes / Trade-offs
- Namespace-only modules: packages look separate but freely share entities, tables, and mutable singletons. Boundary tests should fail before integration tests expose the leak.
- Distributed-monolith rehearsal: synchronous APIs connect every module in deep chains, reproducing service coupling without network isolation. Prefer domain events for secondary reactions.
- Premature extraction: teams split modules into services to escape poor discipline, only to add latency and deployment coupling. Fix ownership before changing the deployment unit.
- Scaling trade-off: development can be separated cleanly, but all modules still share runtime capacity, release timing, and potentially the failure domain.
Boundary review. Generate the module dependency graph on every build and test public APIs without importing implementation packages or opening another module’s schema.
Transaction review. A call crossing modules may appear to be a local function while still coordinating two policies and lock sets; document atomicity and event dispatch at the API.
Extraction review. Candidate modules need their own migrations, configuration, metrics, and data export before becoming services, otherwise extraction simply publishes internal coupling over HTTP.
- Test trade-off: module tests become focused, but full-process tests remain necessary for shared middleware, transaction managers, and composition-root mistakes.
- Security trade-off: database users per module can enforce ownership more reliably than package visibility, though credential management becomes more involved.
- Release trade-off: clear module ownership reduces merge friction but cannot provide independent rollback or deployment timing.
Constraint-based use / avoid
| Constraint | Recommendation |
|---|---|
| Team of 8–30 with increasingly clear domain ownership | Use explicit module APIs, owned schemas, and dependency tests. |
| Small infrastructure budget with future service extraction likely | Use one deployment now; extract only modules with proven scaling or release needs. |
| Hard requirement that billing deploy without enrolling changes | Avoid a monolith for that capability because deployment independence is the constraint. |
| Compliance requires separation of duties but not separate runtimes | Use module-owned credentials and reviewed APIs, backed by database permissions and audit tests. |
Related Patterns
- Monolithic — the simpler starting point this pattern adds discipline to.
- Microservices — the natural next step once a module’s boundary and load justify independent deployment.
- CQRS + Event Sourcing — can be applied inside one module to separate its reads from its writes.
- Modular Monolith Orders — extraction-ready exercise.
- Common Closure — co-locate what changes together.