Explains the modular monolith: business-aligned modules with their own schema, communication through public contracts or in-process events, boundary enforcement in .NET, and when it beats both a classic monolith and microservices.
A modular monolith is one deployable split into modules aligned to business capabilities — Orders, Billing, Catalogue — each with hard boundaries.
DbContext, no cross-module joins or foreign keys.internal.internal types, architecture tests, even per-schema database permissions.You get microservice-style boundaries with monolith-style operations: one pipeline, in-process calls, easy refactoring. The trade-off: one runtime, one release and one scaling unit, and it only works if the boundaries are enforced — otherwise it decays into a big ball of mud.
"A modular monolith is a single deployable application that's internally split into modules along business lines — Orders, Billing, Catalogue — rather than technical layers. Each module is a mini-application: its own domain, its own use cases, and crucially its own data. In .NET that usually means a project per module, a
DbContextper module mapped to its own SQL Server schema —orders.*,billing.*— and no foreign keys or joins across schemas.Modules talk in two ways. For queries or commands that need an answer, they call another module's small public contract — say
IOrdersModule.GetOrderTotalAsyncreturning a DTO — and everything else in the module isinternal. For reactions, they publish integration events, likeOrderPlaced, which Billing handles. Those can be dispatched in-memory, or through an outbox table so a failure in Billing doesn't roll back the order. I enforce the boundaries with architecture tests in CI, and ideally with separate database users per module so a sneaky cross-schema query fails at run time too.The mistake I see is a 'modular' monolith whose modules share one
DbContextand join each other's tables; that's a layered monolith with extra folders. Done properly, it gives you most of the benefits people want from microservices — clear ownership, independent reasoning, parallel teams — without the distributed systems tax. And because the seams are real, extracting a module into a service later is a project, not a rewrite."
| Classic monolith | Modular monolith | Microservices | |
|---|---|---|---|
| Deployables | 1 | 1 | Many |
| Boundaries | Weak or none | Enforced in code and data | Enforced by network |
| Data | Shared schema | Schema per module | Database per service |
| Communication | Any method call | Public contract or events, in-process | HTTP/gRPC/messaging |
| Consistency | Transactions anywhere | Prefer per module; cross-module via events | Eventual, sagas |
| Operational cost | Low | Low | High |
| Style | Mechanism | Coupling | Use for |
|---|---|---|---|
| Synchronous contract | IOrdersModule interface + DTOs |
Medium (runtime) | Queries needing an immediate answer |
| In-memory events | Domain/integration event dispatcher after commit | Low | Reactions that can fail independently |
| Outbox events | Outbox table + background dispatcher | Lowest, durable | Reactions that must not be lost |
| Factor | Modular monolith fits | Consider microservices |
|---|---|---|
| Team size | 1–5 teams | Many teams needing independent releases |
| Scale | Fits one scalable app (scale out instances) | Parts with very different scaling needs |
| Domain clarity | Boundaries still being discovered | Boundaries stable and well understood |
| Ops maturity | Limited platform team | Strong DevOps, observability, on-call |
A grants-management platform for a state agency started as a modular monolith with six modules and schemas on one Azure SQL database in Australia East. Over two years, only the document-processing module needed separate scaling (OCR CPU spikes); it was extracted into an Azure Container Apps service in four weeks because it already communicated only through events and owned its docs schema. The other five modules stayed in one App Service at a fraction of the hosting and on-call cost.
Checks that the candidate understands what makes a monolith genuinely modular — data ownership, contracts and enforcement — and why it is often the right first architecture.
Green flags
DbContext per module and no cross-module joinsinternal implementationRed flags
DbContext+---------------------------------------------------------------+
| Host (ASP.NET Core) |
| Program.cs: AddOrdersModule(), AddBillingModule(), ... |
+----------------+----------------+-----------------------------+
| Orders module | Billing module | Catalogue module |
| public: | public: | public: |
| IOrdersApi | IBillingApi | ICatalogueApi |
| events | events | events |
| internal: | internal: | internal: |
| domain, | domain, | domain, |
| handlers, | handlers, | handlers, |
| DbContext | DbContext | DbContext |
+-------+--------+-------+--------+-------------+---------------+
| | |
[orders schema] [billing schema] [catalogue schema] (one SQL database)
src/
Host/ // composition root, endpoints mapping
Modules/
Orders/
Orders.Contracts/ // public: IOrdersApi, DTOs, integration events
Orders/ // internal: domain, handlers, OrdersDbContext
Billing/
Billing.Contracts/
Billing/
Shared/
BuildingBlocks/ // tiny: event bus abstraction, Result type
Rule: a module may reference only other modules' .Contracts projects. An architecture test checks it.
OrdersDbContext calls modelBuilder.HasDefaultSchema("orders") and has its own migrations history table (MigrationsHistoryTable("__EFMigrationsHistory", "orders")).OrderId as a plain value.GRANT only on its schema, used through a module-specific connection string.Within a module: one SaveChanges is one transaction. Across modules you could share a transaction (same database), but doing so couples them and blocks future extraction. The usual rule: one module per transaction; cross-module effects via events, using an outbox if they must not be lost.
Include(o => o.Invoice) across modules "just once".Common project grows business logic.InternalsVisibleTo.Each step is small; together they rebuild a big ball of mud. Architecture tests and code ownership (CODEOWNERS per module folder) stop the drift.
Because a module has a contract, its own data and event-based reactions, extracting it means: host it separately, replace the in-process IBillingApi with an HTTP/gRPC client implementing the same interface, move events to Azure Service Bus, and move its schema to its own database.
DbContext and schema, and generate migrations for each with --context.Billing may not depend on Orders except Orders.Contracts.billing schema and confirm a cross-schema SELECT fails.OrderPlaced event after SaveChanges and handle it in Billing; then make Billing throw and confirm the order still saves.IBillingApi's in-process implementation with an HTTP client and run the same tests.Key pieces of a module: a public contract, internal implementation with its own schema, and a registration extension.
// Modules/Orders/Orders.Contracts/IOrdersApi.cs — the only thing other modules may reference
namespace Orders.Contracts;
public sealed record OrderTotalDto(Guid OrderId, decimal Total, string Currency);
public sealed record OrderPlaced(Guid OrderId, Guid CustomerId, decimal Total, DateTimeOffset PlacedAt); // integration event
public interface IOrdersApi
{
Task<OrderTotalDto?> GetOrderTotalAsync(Guid orderId, CancellationToken ct);
}
// Modules/Orders/Orders/OrdersModule.cs — internal implementation and its own schema
namespace Orders;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Orders.Contracts;
internal sealed class Order
{
public Guid Id { get; init; }
public Guid CustomerId { get; init; }
public decimal Total { get; private set; }
}
internal sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder b)
{
b.HasDefaultSchema("orders"); // the module owns this schema; no other module maps it
b.Entity<Order>().Property(o => o.Total).HasPrecision(18, 2);
}
}
internal sealed class OrdersApi(OrdersDbContext db) : IOrdersApi
{
public Task<OrderTotalDto?> GetOrderTotalAsync(Guid orderId, CancellationToken ct) =>
db.Orders.AsNoTracking()
.Where(o => o.Id == orderId)
.Select(o => new OrderTotalDto(o.Id, o.Total, "AUD"))
.SingleOrDefaultAsync(ct);
}
public static class OrdersModule
{
public static IServiceCollection AddOrdersModule(this IServiceCollection services, IConfiguration config)
{
services.AddDbContext<OrdersDbContext>(o => o.UseSqlServer(
config.GetConnectionString("Orders"), // can be a login granted only on the orders schema
sql => sql.MigrationsHistoryTable("__EFMigrationsHistory", "orders")));
services.AddScoped<IOrdersApi, OrdersApi>();
return services;
}
}
// tests/Architecture.Tests/ModuleBoundaryTests.cs — NetArchTest-style rule (works with the maintained eNhancedEdition fork)
namespace Architecture.Tests;
using NetArchTest.Rules;
using Xunit;
public sealed class ModuleBoundaryTests
{
[Fact]
public void Billing_does_not_depend_on_Orders_internals()
{
var result = Types.InAssembly(typeof(Billing.BillingModule).Assembly)
.ShouldNot()
.HaveDependencyOn("Orders") // the Orders implementation namespace
.GetResult();
Assert.True(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? []));
}
}
Note: HaveDependencyOn("Orders") matches by namespace prefix, so in a real solution name the implementation namespace distinctly (for example Modules.Orders.Core) to avoid also matching Orders.Contracts.
DbContext across all modules. Why it is wrong: any module can query or update any table, so boundaries exist only in folder names. Instead: a DbContext and schema per module.public. Why it is wrong: other modules will use your internals, and the compiler won't stop them. Instead: only the contracts project is public; implementation types are internal.Shared project that slowly gains business logic. Why it is wrong: it becomes a hidden module everyone depends on. Instead: keep shared building blocks tiny and technical.A modular monolith is my default for a new product with fewer than about five teams: it gives clear ownership and the option to split later, without paying for distributed systems on day one. The hard part isn't the code layout; it's data ownership and discipline. I make the boundaries mechanical — schema per module, internal by default, architecture tests, per-module DB logins — so they survive deadline pressure.
Two things candidates often skip. Consistency: each module's SaveChanges is an ACID transaction over its own schema; when placing an order must also reserve credit in Billing, Orders commits and publishes OrderPlaced (via an outbox if it must not be lost), and Billing reacts — the UI shows "pending" briefly rather than holding one transaction across modules. Observability: one process hides which module is hurting, so I tag logs, OpenTelemetry spans and metrics with a module dimension and give each module its own ActivitySource and Meter; that's also the evidence I need when deciding whether a module deserves extraction. Shared resources are the performance risk — one module's heavy query can exhaust the connection pool or CPU for all, so I watch per-module query time in Query Store and put background-heavy work behind queues with concurrency limits.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Classic monolith | Small app, one team, simple domain | Low now, high later if it grows | Several teams, complex domain |
| Modular monolith | Most new business systems, 1–5 teams | Boundary discipline, shared release and runtime | Parts with radically different scale or tech needs |
| Microservices | Many teams needing independent deploys, proven boundaries | Networking, observability, eventual consistency, platform team | Unknown boundaries, small org |
I measure the health of the boundaries with architecture-test violations over time, and the case for extraction with per-module load, deploy frequency conflicts and on-call incidents.
Evolutionary architecture (Ford, Parsons and Kua) is architecture designed to support guided, incremental change, rather than a fixed upfront design. The key tool is fitness functions: automated checks that protect the characteristics you care about, such as dependency rules (architecture tests), latency budgets, or startup time, run in CI or production. Around that, I keep boundaries modular (often a modular monolith first), make decisions reversible where possible and defer irreversible ones to the last responsible moment, record decisions in ADRs, and rely on continuous delivery, feature flags and observability so each change is small and safe.
The dual-write problem: an order is saved in SQL Server and an OrderPlaced event is sent to Service Bus. Those are two systems with no shared transaction. If the publish fails after the commit, the event is lost. If you publish first and the commit fails, consumers act on an order that doesn't exist.
The outbox fixes this by writing the event as a row in an OutboxMessages table in the same EF Core transaction as the order. A relay (a BackgroundService polling with UPDLOCK, READPAST) publishes unprocessed rows and marks them ProcessedAt.
A crash between publish and mark means the row is sent again, so delivery is at-least-once. Consumers must be idempotent (an inbox), helped by setting MessageId to the outbox id for Service Bus duplicate detection. The trade-off is guaranteed publication against extra writes, latency, cleanup and a relay to monitor.
How to tell it (STAR)
**S:** Our [grants] platform slowed for everyone during application rounds because OCR in one module maxed out the CPU. **T:** I was asked to scale that module separately, but the estimate was huge. **A:** I found [14] cross-schema joins and a shared `DbContext` had quietly broken the module boundary. I moved OCR to a throttled background worker as an immediate fix, wrote an ADR proposing an event-fed read model and per-module DB logins, then led the extraction. **R:** The extraction took [4 weeks], CPU during rounds dropped from [95%] to [40%], and boundary violations have stayed at [zero] since the tests went in.
Last updated 23 Nov 2026.