Modular Monolith
A modular monolith is a single deployable application divided into strongly encapsulated business modules with explicit contracts and controlled dependencies.
Overview
Unlike a traditional monolith organized mainly by technical layers, a modular monolith groups code and data ownership around business capabilities. Modules communicate through public contracts or in-process messages, hide their internal models, and can own separate schemas while still sharing one process and deployment pipeline. It preserves operational simplicity and leaves room to extract a module only when independent scaling or deployment provides proven value.
What you will learn
- Identify business-capability module boundaries and ownership.
- Design narrow public contracts while hiding internal domain and persistence types.
- Choose synchronous calls, queries, events, and read models deliberately.
- Enforce dependency and data-ownership rules automatically.
- Coordinate transactions, outbox delivery, migrations, and observability.
- Decide when service extraction has enough operational value.
Prerequisites
- ASP.NET Core composition, dependency injection, persistence, and automated testing.
- DDD bounded-context, transaction, messaging, and deployment fundamentals.
- Understanding of coupling, cohesion, consistency, and distributed-system trade-offs.
When to use Modular Monolith
Good fit
- One deployable remains operationally desirable but the domain contains distinct capabilities.
- Teams need ownership and controlled dependencies without network failure.
- Potential future extraction benefits from proven seams.
Choose another approach when
- The application is small and module ceremony obscures behavior.
- Boundaries cannot be enforced and every module shares the same tables and internals.
- Independent deployment or hard isolation is already a non-negotiable requirement.
Key concepts
Each module owns a cohesive capability, its application behavior, domain model, persistence, and public contract.
Internal types stay inaccessible and dependency rules prevent modules from reaching into one another's implementation details.
Public interfaces, commands, queries, or events make cross-module interactions explicit and replace direct table or class access.
Modules compile and run together, avoiding distributed transactions and network failure while retaining architectural separation.
Each module owns its tables or schema and other modules use contracts or read models instead of direct access.
Commands, queries, and events carry stable cross-module meaning without exposing internal entities.
In-process calls can share a transaction when necessary, while outbox delivery supports reliable asynchronous collaboration.
A well-enforced module can later move behind a network boundary when independent operations justify the cost.
Architecture
One host composes independently owned modules; modules communicate through contracts while sharing the process and, when appropriate, a database server with isolated schemas.
Conceptual architecture · Adapt to your system context
Implementation walkthrough
The storefront sample composes Catalog and Orders in one process. Orders sees only catalog query, inventory command, and event contracts; tests prove success, failure atomicity, and substitutability.
- 01Map capabilities
Use business language, workflows, ownership, and change patterns to propose modules.
- 02Define public APIs
Expose only required commands, queries, events, and registration entry points.
- 03Hide internals
Use projects, internal visibility, and architecture rules to prevent implementation access.
- 04Own data
Assign tables or schemas and prohibit cross-module writes and ad hoc joins.
- 05Choose collaboration
Use direct calls for immediate consistency and events for decoupled propagation.
- 06Test boundaries
Verify contracts, forbidden dependencies, transactions, events, and module workflows.
- 07Operate and evolve
Own migrations, telemetry, capacity, failure handling, and extraction decisions per module.
Code example
A module exposes only registration and endpoint mapping while keeping handlers, entities, and persistence types internal.
public static class OrdersModule
{
public static IServiceCollection AddOrders(
this IServiceCollection services, IConfiguration configuration)
{
services.AddDbContext<OrdersDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString("Database")));
services.AddScoped<IOrdersModule, OrdersModuleApi>();
return services;
}
public static IEndpointRouteBuilder MapOrders(
this IEndpointRouteBuilder endpoints)
{
var group = endpoints.MapGroup("/api/orders")
.RequireAuthorization();
group.MapPost("/", PlaceOrder.HandleAsync);
group.MapGet("/{id:guid}", GetOrder.HandleAsync);
return endpoints;
}
}
internal sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options)
: DbContext(options);Testing strategy
Test both module behavior and the boundaries that preserve modularity.
- Unit-test module domain and application rules.
- Contract-test every public command, query, and event.
- Integration-test each module against its owned schema.
- Fail builds on forbidden project, namespace, and data dependencies.
- Test transaction rollback and outbox publication ordering.
- Run multi-module workflow tests through the composed host.
Security considerations
A process boundary is not a security boundary; modules must preserve trusted identity and authorize their own resources.
- Pass a minimal verified actor and tenant context through contracts.
- Authorize inside the owning module.
- Do not expose internal entities or unrestricted query surfaces.
- Protect module data with least-privilege database identities where practical.
- Audit cross-module commands and sensitive outcomes without leaking payloads.
Performance and scalability
In-process collaboration is fast, but hidden chatty calls and cross-module queries can still dominate latency.
- Measure calls, queries, payloads, and transaction duration per module.
- Use deliberate read models for cross-module reporting.
- Avoid serializing in-process messages unnecessarily.
- Keep integration events bounded and versioned.
- Profile the composed workflow before extracting a service.
Deployment and operations
One artifact simplifies rollout, but module schemas and contracts still need safe evolution.
- Run module migrations in a controlled order.
- Use expand-contract schema changes.
- Keep integration events backward compatible.
- Expose module-tagged health, traces, metrics, and logs.
- Smoke-test critical cross-module workflows and rollback.
Common problems and fixes
Modules query one another's tables.
Likely cause: Data ownership is unenforced.
Fix: Introduce a contract or owned read model and block direct access.
A change rebuilds every module.
Likely cause: Public contracts expose internal types.
Fix: Shrink and stabilize contract assemblies.
Events are lost after commit.
Likely cause: Publication is not transactional.
Fix: Use an outbox and idempotent consumer.
Circular module references appear.
Likely cause: Capabilities or shared semantics are misplaced.
Fix: Revisit boundaries or extract a small neutral contract.
One module dominates startup.
Likely cause: Eager initialization scans or loads excessive state.
Fix: Measure registration and defer bounded work.
Extraction becomes a rewrite.
Likely cause: Contracts and data ownership were only conceptual.
Fix: Enforce seams before introducing the network.
Best practices
- Define modules from business capabilities and bounded contexts, not arbitrary folders or deployment aspirations.
- Make module internals inaccessible and enforce dependency rules with architecture tests in continuous integration.
- Give each module ownership of its tables or schema; cross-module reads should use contracts or deliberately maintained read models.
- Extract a module into a service only when independent deployment, scaling, ownership, or isolation justifies the distributed-system cost.
- Keep public module APIs small, business-oriented, versionable, and free of internal entities.
- Choose synchronous calls or asynchronous events from consistency and coupling needs.
- Use an outbox and idempotent consumers when integration events must survive failure.
- Assign module ownership, observability, migrations, and operational runbooks explicitly.
Production checklist
- Modules map to business capabilities with named owners.
- Public contracts are narrow and versioned.
- Internals and forbidden dependencies are build-enforced.
- Each module owns data and migrations.
- Collaboration and consistency choices are documented.
- Outbox and idempotency protect durable events.
- Security and observability identify module boundaries.
- Extraction requires measured operational justification.
Common interview questions
How does a modular monolith differ from a layered monolith?
A layered monolith groups code by technical role across the system, while a modular monolith groups cohesive business capabilities and restricts dependencies across those module boundaries.
What advantages does it have over microservices?
It keeps calls and transactions in process, simplifies deployment and debugging, and avoids network and consistency complexity while still making business boundaries explicit.
How do you stop module boundaries from eroding?
Use internal visibility, small public contracts, separate schemas or contexts, architecture tests, and code ownership rules that fail builds when forbidden dependencies appear.
Should modules share one database?
They may share a server, but each module should own its schema or tables and other modules should not read or write them directly.
When should modules communicate with events?
Use events when the producer should not control downstream work and eventual consistency is acceptable; use direct contracts for an immediate result.
How are events published reliably?
Persist an outbox record with business state, then deliver asynchronously and make consumers idempotent.
When should a module become a microservice?
When independent deployment, scaling, ownership, technology, or fault isolation produces measured value worth the operational cost.
Dedicated GitHub sample
Clone, run, test, and modify the focused implementation created for this guide.
Modular Monolith Storefront
A .NET 10 storefront demonstrating business-module ownership, narrow public contracts, in-process collaboration, integration messages, and failure atomicity.
- Run
dotnet run --project src/ModularMonolithStorefront- Test
dotnet test ModularMonolithStorefront.slnx