
Hamsayeh, my building-management SaaS, has a feature list that grows on several fronts at once: accounting, tickets, reservations, voting and a marketplace. Without firm boundaries, features like these collapse into one data model that nobody can change safely. The usual escape is to split the system into services. I went the other way: Hamsayeh is a modular monolith, one codebase with internal boundaries, deployed as two ASP.NET Core API hosts.
This note covers what makes the "modular" part real: where the boundaries go, how modules talk, how tests keep the boundaries from eroding, and when a module should move out into its own service. The code is simplified, with neutral names.
One deployable, many boundaries
Microservices give each part its own deployment, database and failure domain, and charge for it in network calls, eventual consistency, message plumbing and operations. A monolith is cheap on all of those: one deployment, one transaction, and refactorings across module lines that the compiler checks. Its risk is the big ball of mud, where any class can reach any table. A modular monolith keeps the cheap deployment and makes the boundaries explicit.
The multi-tenant microservice platform I am building, whose tenant isolation was the subject of an earlier note, takes the other route: separate services, each with its own PostgreSQL database. Hamsayeh is one product whose code I have almost entirely written myself, and paying for distribution before it buys anything would be hard to justify there.
One distinction is worth making early: a host is a deployment unit, a module is a code boundary, and the two do not have to line up. Hamsayeh's hosts are split by who calls them, one for building users and one for administration, and both sit on one shared application layer of MediatR commands and queries, validated with FluentValidation.
Drawing the boundaries
Hamsayeh's PostgreSQL database is divided into seven main schemas: identity, building, accounting, governance, growth, service and marketplace. Each schema is mapped by its own EF Core DbContext, so a module's model contains only its own tables, and reaching into another module's tables through EF Core is an error instead of a shortcut.
Three signals help me decide where a line goes. A business capability with its own vocabulary: to the building module a unit is an apartment with residents; to accounting it is a party that owes money. A single writer: every table has one module that inserts and updates it, and everyone else asks. And invariants that must hold inside one transaction, such as a journal entry and its lines, belong to one module.
Accounting goes further than the rest. It has its own domain, application and infrastructure projects, so project references enforce the boundary of its domain and persistence, not only convention. Most of its commands and handlers still sit in the shared application layer, where convention does that work. Money is where an unexplained figure costs the most trust, so it gets the strictest isolation. Here is a sketch of such a module's data access:
public sealed class AccountingDbContext(DbContextOptions<AccountingDbContext> options) : DbContext(options)
{
public const string Schema = "accounting";
public DbSet<Charge> Charges => Set<Charge>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(Schema); // every table lands in "accounting"
modelBuilder.ApplyConfigurationsFromAssembly(typeof(AccountingDbContext).Assembly);
}
}
public static class AccountingModule
{
// the one public entry point the hosts call; the rest of the module can stay internal
public static IServiceCollection AddAccountingModule(this IServiceCollection services,
NpgsqlDataSource dataSource)
{
services.AddDbContext<AccountingDbContext>(options => options.UseNpgsql(dataSource,
npgsql => npgsql.MigrationsHistoryTable("__EFMigrationsHistory", AccountingDbContext.Schema)));
services.AddScoped<IChargeStore, EfChargeStore>();
return services;
}
}
HasDefaultSchema puts every table of the context in its schema, and MigrationsHistoryTable puts the context's migration history there too, so each module's migrations are listed and applied on their own. When several contexts share one assembly, give ApplyConfigurationsFromAssembly a predicate, or each context will map every module's entities. And the module offers the hosts one public entry point, while the store, the entity configurations and the handlers stay internal, so no other module can depend on them by accident.
References by id, plus a snapshot
The rule that does the most work is small: accounting refers to buildings and units by id plus a stored snapshot of the name or unit number, never through an EF navigation property.
public sealed class Charge
{
private Charge() { } // for EF Core
public Guid Id { get; private set; }
public Guid CycleId { get; private set; }
public Guid BuildingId { get; private set; } // an id, never a Building navigation
public Guid UnitId { get; private set; }
public string UnitNumber { get; private set; } = ""; // snapshot taken when the charge was issued
public decimal Amount { get; private set; }
public DateTimeOffset IssuedAt { get; private set; }
public static Charge Issue(Guid cycleId, Guid buildingId, Guid unitId, string unitNumber,
decimal amount, DateTimeOffset issuedAt)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
ArgumentException.ThrowIfNullOrWhiteSpace(unitNumber);
return new Charge
{
Id = Guid.CreateVersion7(issuedAt),
CycleId = cycleId, BuildingId = buildingId, UnitId = unitId,
UnitNumber = unitNumber, Amount = amount, IssuedAt = issuedAt,
};
}
}
A navigation property couples more than it seems. It lets accounting load building entities with Include, join across schemas, and touch another module's tables from a report. Each of these works while both modules share a database, and each becomes a distributed query on the day they do not. An id and a snapshot cost a little duplication. In return, a statement can be rendered from accounting data alone, showing the unit number as it was when the charge was issued, which is what a financial record should show anyway. When accounting needs current data, the clean route is to ask the building module through a contract.
Contracts between modules
A module's contract is the only part of it that other modules may reference: a few interfaces and records in a separate project, owned by the module that implements them. Hamsayeh has no such projects today: an Accounting.Contracts project existed for five days in May and was removed as unused, and building handlers write accounting's snapshots directly through a small writer interface. What follows is the shape I would use.
// Building.Contracts: the only part of the building module that other modules reference
public sealed record UnitRef(Guid UnitId, string UnitNumber);
public interface IUnitDirectory
{
Task<IReadOnlyList<UnitRef>> ListUnitsAsync(Guid buildingId, CancellationToken ct);
}
// the building module implements it with an internal class over its own DbContext
// and registers it in AddBuildingModule: services.AddScoped<IUnitDirectory, UnitDirectory>();
In the sketch, accounting calls it when it issues a cycle of charges, and that is where the snapshot is taken. IChargeStore is a small interface that accounting's infrastructure project implements:
public sealed record IssueCharges(Guid BuildingId, Guid CycleId, decimal AmountPerUnit) : IRequest<int>;
internal sealed class IssueChargesHandler(IUnitDirectory units, IChargeStore charges, TimeProvider clock)
: IRequestHandler<IssueCharges, int>
{
public async Task<int> Handle(IssueCharges command, CancellationToken ct)
{
var issuedAt = clock.GetUtcNow(); // never DateTime.UtcNow
var unitList = await units.ListUnitsAsync(command.BuildingId, ct); // a contract call, not a join
foreach (var unit in unitList)
charges.Add(Charge.Issue(command.CycleId, command.BuildingId, unit.UnitId, unit.UnitNumber,
command.AmountPerUnit, issuedAt));
await charges.SaveChangesAsync(ct);
return unitList.Count;
}
}
A few rules keep contracts useful. They carry small records, never entities and never IQueryable, which would leak the provider's model and database into the caller. They are asynchronous and take a CancellationToken, even though they run in process today, so that an HTTP implementation could replace them later without touching the callers. And the provider owns them, changing them as carefully as any public API.
Events travel the other way: a payment was approved, and other modules may want to react. In process, a notification such as MediatR's INotification is the simple tool, with one catch: timing. Published before the commit, a handler can act on a change that then rolls back; published after it, a crash in between loses the event. The outbox closes that gap by storing the event in the same transaction as the change, and Hamsayeh's own list of work before production includes an outbox for payment and notification side effects. The mechanics are in the RabbitMQ guide.
One more habit keeps a later split cheap: a command changes one module's data in one transaction. A shared database makes it tempting to update building and accounting tables atomically, and that is exactly the transaction that would become distributed after a split. Hamsayeh does not fully keep this habit yet: its unit of work can span contexts in one transaction, and five handlers write building and accounting data in one save.
Keeping the boundaries honest
The first guard is the project graph: Accounting.Domain references no other project, so the compiler refuses a stray using. But a project reference is one line in a csproj, easy to add in a hurry and easy to miss in a large diff. Architecture tests turn the rules into failing tests with readable messages. Hamsayeh has six. Three of them matter most here: the accounting domain references no outer layer, accounting entities do not navigate into other areas, and application code reads time through a clock abstraction. Here are the first two, simplified, written with nothing but reflection:
public sealed class AccountingArchitectureTests
{
private static readonly Assembly AccountingDomain = typeof(Charge).Assembly;
private static readonly Assembly AccountingApplication = typeof(IssueCharges).Assembly;
private static readonly string[] OtherModules =
["Identity", "Building", "Governance", "Growth", "Service", "Marketplace"];
[Fact]
public void Accounting_domain_references_no_outer_layer()
{
string[] forbidden = ["Accounting.Application", "Accounting.Infrastructure",
"Microsoft.EntityFrameworkCore", "Microsoft.AspNetCore", "Npgsql", .. OtherModules];
var offenders = AccountingDomain.GetReferencedAssemblies()
.Select(reference => reference.Name ?? "")
.Where(name => forbidden.Any(prefix => name.StartsWith(prefix, StringComparison.Ordinal)))
.ToList();
Assert.Empty(offenders);
}
[Fact]
public void Accounting_entities_do_not_navigate_into_other_modules()
{
const BindingFlags all = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var offenders =
from type in AccountingDomain.GetTypes()
from property in type.GetProperties(all)
from target in Unwrap(property.PropertyType)
where OtherModules.Contains(target.Namespace?.Split('.')[0])
select $"{type.Name}.{property.Name} -> {target.FullName}";
Assert.Empty(offenders);
}
// Unit, Unit[], List<Unit> and Dictionary<Guid, Unit> all count as a reference to Unit
private static IEnumerable<Type> Unwrap(Type type) =>
type.IsArray ? Unwrap(type.GetElementType()!)
: type.IsGenericType ? type.GetGenericArguments().SelectMany(Unwrap)
: [type];
}
The compiler records only the assembly references the code actually uses, so the first test fails when the domain starts using EF Core or another module, not when someone merely adds a package. The second walks every property of every domain type, unwraps arrays and generic arguments, and fails on any type whose root namespace belongs to another module; a stricter version also checks fields.
The clock rule has to look inside method bodies. Hamsayeh's own test is simpler than this one: it scans the source files of the application project with a regular expression. Reading the IL with Mono.Cecil, as below, is the stricter version:
[Fact]
public void Application_code_reads_time_through_the_clock()
{
string[] banned =
[
"System.DateTime System.DateTime::get_Now()",
"System.DateTime System.DateTime::get_UtcNow()",
"System.DateTime System.DateTime::get_Today()",
"System.DateTimeOffset System.DateTimeOffset::get_Now()",
"System.DateTimeOffset System.DateTimeOffset::get_UtcNow()",
];
using var module = ModuleDefinition.ReadModule(AccountingApplication.Location);
var offenders =
from type in module.GetTypes() // includes nested types: lambdas, async state machines
from method in type.Methods
where method.HasBody
from instruction in method.Body.Instructions
where instruction.Operand is MethodReference called && banned.Contains(called.FullName)
select $"{type.FullName}::{method.Name}";
Assert.Empty(offenders);
}
Lambdas and async methods compile into nested types, and GetTypes() includes them, so a DateTime.UtcNow inside an async handler is still found. A compile-time alternative is Microsoft's BannedApiAnalyzers package with a list of banned symbols, which fails any build that treats warnings as errors. NetArchTest and ArchUnitNET offer similar rules as fluent APIs. In Hamsayeh, the architecture tests run with the rest of the roughly 390 xUnit test methods in a back-end CI that also builds with warnings as errors.
The clock rule earns its place because time drives much of the product: ticket SLAs, scheduled announcements, penalty rules and debtor aging all depend on "now", and background services run several of them (the previous note covered running such jobs reliably). Code that reads the system clock can only be tested by waiting. With TimeProvider, built into .NET since version 8, production registers TimeProvider.System and a test calls Advance on a FakeTimeProvider to step past a due date. The same idea works on the front end, where Hamsayeh's React app has custom checks that stop imports from crossing portal boundaries.
The database can check one more rule. If you decide that modules keep no foreign keys into each other's schemas, this catalog query lists every key that crosses a schema, and a test can require it to return nothing:
SELECT c.conname, c.conrelid::regclass AS from_table, c.confrelid::regclass AS to_table FROM pg_constraint c JOIN pg_class src ON src.oid = c.conrelid JOIN pg_class tgt ON tgt.oid = c.confrelid WHERE c.contype = 'f' AND src.relnamespace <> tgt.relnamespace;
When to split out a service
Keeping accounting ready for a split is not a plan to split it. Moving a module out pays off when a need appears that one process cannot meet, and I would want to see that need rather than predict it:
- Different scaling or availability, measured rather than guessed.
- A different security boundary, such as code that handles payment credentials.
- Independent teams, when releasing together costs more than the network calls would.
- A different runtime: heavy computation, another language, special hardware.
The reasons I distrust are size, fashion and slowness. A slow module usually needs profiling, an index or a background job, and putting it behind a network adds latency instead of removing it.
The cost side is easy to underestimate, and the other platform shows it plainly. Its services own their databases and never read each other's, so every change that others care about travels as a message: written to an outbox in the same transaction, published to RabbitMQ with confirms, recorded in an inbox by the consumer, retried through delay tiers, dead-lettered when it breaks the contract, and versioned by name and payload. Traces have to cross the broker too. That machinery is justified there; in Hamsayeh today it would be cost without return.
A monolith can also separate failure domains without separating processes. Hamsayeh's audit log lives in its own PostgreSQL database: audit data grows without weighing on the main one, and a failed audit write is logged without failing the request. Redis gets the same treatment: every cache operation is best-effort, so the API keeps working with the database alone. Separating data and failure handling first, and processes last, is often enough.
If accounting ever had to move, much of the path is already laid: its projects and schema are separate, and it holds no navigations into other modules. The remaining steps are mechanical, though not small: put contracts in front of whatever it still needs from other modules and serve them over HTTP or messages, route its events through an outbox, move the accounting schema into its own database, and find whatever still joins across schemas. The architecture tests keep the laid part intact until then.
The next note goes inside that strictest module: a double-entry ledger in PostgreSQL, with journal entries and postings, constraints that keep debits equal to credits, idempotent posting and corrections by reversal.
If you are deciding between a monolith and services, or untangling a codebase whose modules have grown into each other, that is the kind of backend work I take on.
This note is also available in Persian: read the Persian version.
