Modular Monolith in .NET: Refactoring Project
On this page
Learning Objective
Restructure the Task Board into modules with explicit public contracts, private data and separate schemas, communicate between modules through interfaces and integration events, and enforce the boundaries with architecture tests so the system can be extracted into services later, if ever needed, along the seams you drew.
Concept Explanation
A modular monolith is a single deployable application whose insides are divided into modules with strong boundaries, each owning a business capability, its code, and its data. It aims to capture the main benefits people seek from microservices, independent reasoning, clear ownership, and the freedom to change one area without breaking others, without paying their operational costs: network calls, distributed transactions, many deployment pipelines, and cross-service debugging. It is also a sensible starting point, because boundaries can be moved cheaply while the code is in one process, and extracting a module into a service later is far easier when the seams already exist.
The Task Board suggests four modules. Identity handles users and sessions. Projects owns projects, members, roles, and invitations. Tasks owns the board: tasks, statuses, and comments. Notifications owns emails and real-time messages. Each module has a public surface, a small set of interfaces and integration events other modules may use, and an internal part that nobody else may touch. The rules that make this real are few and mechanical. A module's database tables live in its own schema and are accessed only through its own DbContext. No module references another module's internals or writes to its tables, and no query joins across module schemas. When the Tasks module needs to know whether a user may edit a project, it calls the Projects module's public membership interface. When something happens that others care about, the module publishes an integration event, through the outbox from Day 66.
The refactor is a sequence of small, safe steps. First, draw the module map and decide, for every table, which module owns it. Second, move code into module projects and split the single DbContext into one per module with its own default schema, so cross-module joins stop compiling or start failing. Third, replace direct cross-module data access with contracts, for example an IProjectMembership interface exposing exactly the questions other modules need, such as whether a user is an editor of a project. Fourth, convert reactions into events: when a member is removed from a project, Projects publishes MemberRemoved, and Tasks reacts by unassigning that person's tasks. Finally, write the architecture tests that lock the boundaries in, since without them the modules erode within months.
Security fits naturally. Each module's public contract is a place to apply authorization, and the membership contract becomes the single source of truth for project access, so the rules from Day 47 are implemented once instead of in every module's queries. Sensitive data stays inside the module that owns it, such as personal details in Identity, and other modules hold only user identifiers, which reduces exposure and simplifies privacy handling. Tenant handling, the outbox, and audit stamping from earlier lessons are shared infrastructure that every module uses through the same building blocks. The result is a system where you can point at the boundary and say what crosses it, which is exactly what a security review wants to see.
| Aspect | Rule | Enforced by |
|---|---|---|
| Ownership | Each table belongs to exactly one module and schema | Separate DbContext and default schema per module |
| Public surface | Contracts and integration events only | Internal types, architecture tests |
| Synchronous queries across modules | Through a public interface | No cross-module project references to internals |
| Reactions to changes | Integration events via the outbox | Idempotent handlers in the receiving module |
| Data sharing | Identifiers, never other modules' entities | Contract types are DTOs |
| Boundaries over time | Automated dependency tests | Failing build on violation |
Worked Example: Module Structure, a Contract, an Event and Boundary Tests
The listings show the layout, the Projects module's public contract and its implementation, an event handled by Tasks, and tests that fail the build on a boundary violation.
src/
Modules/
Identity/ Identity.Contracts, Identity.Internal, schema: identity
Projects/ Projects.Contracts, Projects.Internal, schema: projects
Tasks/ Tasks.Contracts, Tasks.Internal, schema: tasks
Notifications/ Notifications.Contracts, Notifications.Internal, schema: notifications
BuildingBlocks/ Outbox, tenant, audit, result types, shared kernel (small!)
Host/ Program.cs composes modules; endpoints call module contracts// Projects.Contracts: the ONLY thing other modules may reference.
public interface IProjectMembership
{
Task<ProjectRole?> GetRoleAsync(Guid projectId, Guid userId, CancellationToken ct);
Task<bool> IsAtLeastAsync(Guid projectId, Guid userId, ProjectRole minimum, CancellationToken ct);
}
public sealed record MemberRemoved(Guid ProjectId, Guid UserId) : IIntegrationEvent;
// Projects (internal): implementation and data stay private.
internal sealed class ProjectMembership(ProjectsDb db) : IProjectMembership
{
public async Task<ProjectRole?> GetRoleAsync(Guid projectId, Guid userId, CancellationToken ct) =>
await db.Members.Where(m => m.ProjectId == projectId && m.UserId == userId)
.Select(m => (ProjectRole?)m.Role).FirstOrDefaultAsync(ct);
public async Task<bool> IsAtLeastAsync(Guid projectId, Guid userId, ProjectRole minimum, CancellationToken ct) =>
(await GetRoleAsync(projectId, userId, ct)) is { } role && role >= minimum;
}
// Module registration: each module wires its own services, DbContext and schema.
public static class ProjectsModule
{
public static IServiceCollection AddProjectsModule(this IServiceCollection s, IConfiguration c)
{
s.AddDbContext<ProjectsDb>(o => o.UseSqlServer(c.GetConnectionString("Default"),
sql => sql.MigrationsHistoryTable("__EFMigrationsHistory", "projects")));
s.AddScoped<IProjectMembership, ProjectMembership>();
return s;
}
}
// In ProjectsDb.OnModelCreating: modelBuilder.HasDefaultSchema("projects");// Tasks module: uses the contract, reacts to the event. It never touches projects.* tables.
internal sealed class MoveTaskHandler(TasksDb db, IProjectMembership membership, ICurrentUser user)
{
public async Task<IResult> HandleAsync(Guid taskId, TaskState next, CancellationToken ct)
{
var task = await db.Tasks.FirstOrDefaultAsync(t => t.Id == taskId, ct);
if (task is null || !await membership.IsAtLeastAsync(task.ProjectId, user.Id, ProjectRole.Editor, ct))
return Results.NotFound(); // same answer for missing and forbidden
/* ... domain rule, save, publish TaskMoved via the outbox ... */
return Results.NoContent();
}
}
internal sealed class UnassignRemovedMember(TasksDb db) : IIntegrationEventHandler<MemberRemoved>
{
public Task HandleAsync(MemberRemoved e, CancellationToken ct) =>
db.Tasks.Where(t => t.ProjectId == e.ProjectId && t.AssigneeId == e.UserId)
.ExecuteUpdateAsync(s => s.SetProperty(t => t.AssigneeId, (Guid?)null), ct); // idempotent by nature
}// Boundary tests: the build fails when a module reaches into another's internals.
public class ModuleBoundaryTests
{
static readonly string[] Modules = ["Identity", "Projects", "Tasks", "Notifications"];
[Theory, MemberData(nameof(Pairs))]
public void Modules_only_reference_each_others_contracts(string from, string to)
{
var result = Types.InAssembly(Assembly.Load($"{from}"))
.That().ResideInNamespace($"{from}")
.ShouldNot().HaveDependencyOn($"{to}.Internal") // another module's internals; its .Contracts namespace is allowed
.GetResult();
Assert.True(result.IsSuccessful, $"{from} must not depend on {to} internals: {string.Join(", ", result.FailingTypeNames ?? [])}");
}
[Fact]
public void No_module_queries_another_modules_schema()
{
// Search migrations and SQL strings for foreign schema prefixes.
var offenders = FindSqlReferences(module: "Tasks", forbiddenSchemas: ["projects.", "identity."]);
Assert.Empty(offenders);
}
public static IEnumerable<object[]> Pairs() =>
from a in Modules from b in Modules where a != b select new object[] { a, b };
}The acceptance test for the refactor is behavioral: the whole existing suite, including the authorization matrix and the tenant isolation tests, must pass unchanged. If any test needs editing, the refactor changed behavior, and that is worth investigating before proceeding. Finish by writing a one-page module map for the repository that lists each module's contracts, events, and owner, since that document is what makes the boundaries understandable to a new team member.
Real-World Examples
- Shopify, running one of the largest Ruby on Rails applications, chose to modularize its monolith rather than split it into microservices, describing the approach in engineering posts from 2019 onward. They built a tool called Packwerk to enforce boundaries between packages of code, following the same principle as the architecture tests here, that boundaries only survive if violations fail the build.
- In March 2023, the Amazon Prime Video engineering team described moving the video quality monitoring service from a distributed microservices design back to a single process, reporting an infrastructure cost reduction of over 90 percent for that workload. The post drew wide discussion and is often cited as a reminder that service boundaries should be chosen for real reasons, not by default.
Review Questions & Answers
In a modular monolith the primary division is by business capability, and each module owns its data and exposes only a deliberate public contract, with enforced rules forbidding access to other modules' internals or tables. A layered application divides by technical role, and any part can usually call any other, so boundaries between features are informal and tend to erode.
It makes data ownership physical: a module can only see its own tables through its context, and cross-module joins stop compiling or fail, forcing communication through contracts and events. It also lets each module evolve its schema and migrations independently and makes later extraction into a separate database or service straightforward.
Tasks owns its data, so no other module should modify its tables. Publishing MemberRemoved lets Projects finish its own work without knowing who cares, and Tasks handles the event in its own transaction, idempotently. The coupling is to a stable event contract instead of to Tasks' internal schema.
Modules erode through small convenient shortcuts, such as referencing another module's internal type or querying its table. A test that fails the build on any forbidden dependency or foreign schema reference makes each shortcut immediately visible, so the boundary either holds or is deliberately and reviewably changed.