How to Tell If Two Modules Should Be One

modular-monolithpostgresqlsoftware-architecturetesting
How to Tell If Two Modules Should Be One

Two modules should be one when a use case must write to both in one transaction, one keeps reading the other's current data, or most changes touch both. In .NET, an ArchUnitNET test and a Postgres role per module catch code that crosses the boundary. The architecture test misses raw SQL, and the database role misses code that uses the other module's DbContext. That is why you need both.

DigitalOcean's Managed Agents offer security-hardened code execution and fast startup, with governed access to 36,000+ tools and dozens of cloud services. Focus on running the agent, not managing the infrastructure. Learn more.

AI writes code fast. Someone still has to read it, verify it, and maintain it. Morph from Modelcode.AI modernizes legacy codebases, and the codebase analysis and modernization plan are free. You pay only if you approve the work, and code NETWEEKLY gets you 60,000 credits per month for six months. Analyze your codebase for free.

I once split order collaboration and the product catalog into two modules. On paper, it was an obvious split between two distinct domains.

Then ordinary feature work started coming in. Collaboration needed product options, then live prices, and eventually orders had to reflect catalog changes right away. A year later, the boundary only existed in the folder structure.

When I'm unsure about a boundary now, I run three checks and let two tools show where one module reaches into another.

Check 1: What Has to Be Saved Together?

Look at any use case that needs a single transaction across both modules. Shared transactions couple modules at the database level, so your module boundary should also be your transaction boundary.

Say an Ordering module places an order that also reduces product stock in Catalog. If stock must be accurate the instant an order is saved, orders and stock belong in the same module.

You can still keep them separate and update stock through an event. That requires an outbox so the event survives a crash, plus a way for Ordering to cancel if stock runs out first.

One module saves the order and stock update in one transaction. With two modules, Ordering writes to an outbox and Catalog reduces stock later.

Check 2: Snapshot Reads or Live Reads?

Not every cross-module read is a problem. It comes down to whether you need a snapshot in time or the live value.

An order needs the product's name and price at checkout. In PlaceOrder.cs, Ordering calls Catalog's public API (ICatalogModule) once and copies both onto the order:

ProductForOrder product =
    await catalog.GetProductForOrderAsync(productId, cancellationToken)
    ?? throw new InvalidOperationException($"Product {productId} was not found.");

var order = new Order
{
    Id = Guid.NewGuid(),
    ProductId = product.Id,
    ProductName = product.Name,
    UnitPrice = product.Price,
    Quantity = quantity
};

If you place an order at 129.00 and Catalog later changes the price to 149.00, the saved order still reads back 129.00. Once copied, Ordering doesn't need Catalog again.

Ordering copies the price 129.00 once through the public API. Catalog later changes it to 149.00, and the order still keeps 129.00.

An occasional live call to another module's public API is fine. But if nearly every Ordering feature needs current Catalog data to work, those two modules probably belong together.

Check 3: What Changes Together?

A bad boundary usually shows up in git history. Count recent commits on main touching both modules against total commits in one (with squash-merge, one commit is one PR):

comm -12 \
  <(git log main --since="6 months ago" --format=%H -- src/Ordering | sort) \
  <(git log main --since="6 months ago" --format=%H -- src/Catalog | sort) | wc -l

git log main --since="6 months ago" --format=%H -- src/Ordering | wc -l

If most Ordering PRs also touch Catalog, the split isn't buying you independence.

On a new codebase with no history yet, run the change test: would a typical feature touch both modules?

Catching Boundary Violations in Code

Those checks need real data on where one module reaches into another. I put together a small .NET and Postgres app with Shop.Catalog and Shop.Ordering as namespaces in one project, and Catalog's public API in Shop.Catalog.Contracts. Because they're namespaces in one project, not separate projects, the compiler lets Ordering use any Catalog type, even the internal ones. So I added three shortcuts to Ordering to see what catches them:

The architecture test catches PlaceOrderDirect using CatalogDbContext. The Postgres role blocks the raw SQL JOIN in TopProductsReport and UPDATE in ReduceStock on catalog.products.

First is an architecture test with ArchUnitNET:

dotnet add package TngTech.ArchUnitNET.xUnit

This rule in BoundaryTests.cs limits Shop.Ordering to Catalog's contracts and blocks the rest of Shop.Catalog:

using ArchUnitNET.Domain;
using ArchUnitNET.Fluent;
using ArchUnitNET.Loader;
using ArchUnitNET.xUnit;
using Shop.Ordering;
using Xunit;
using static ArchUnitNET.Fluent.ArchRuleDefinition;

public class BoundaryTests
{
    private static readonly Architecture Architecture = new ArchLoader()
        .LoadAssemblies(typeof(OrderingDbContext).Assembly)
        .Build();

    private static readonly IObjectProvider<IType> Ordering =
        Types().That().ResideInNamespaceMatching(@"^Shop\.Ordering(\.|$)").As("Ordering");

    private static readonly IObjectProvider<IType> CatalogInternals =
        Types().That().ResideInNamespaceMatching(@"^Shop\.Catalog(\.|$)")
            .And().DoNotResideInNamespace("Shop.Catalog.Contracts")
            .As("Catalog internals");

    [Fact]
    public void Ordering_ShouldOnlyUse_CatalogContracts()
    {
        Types().That().Are(Ordering)
            .Should().NotDependOnAny(CatalogInternals)
            .Check(Architecture);
    }
}

It catches PlaceOrderDirect, which skips the contract and uses CatalogDbContext directly:

Shop.Ordering.Shortcuts.PlaceOrderDirect does depend on "Shop.Catalog.CatalogDbContext" and "Shop.Catalog.Product"

It only inspects the compiled assembly and needs no database, so it runs on every PR.

On the database side, use a Postgres role and schema per module. Each module connects with its own login role, owns its schema, and has no permissions on the other:

CREATE ROLE catalog_role LOGIN PASSWORD 'catalog_secret';
CREATE ROLE ordering_role LOGIN PASSWORD 'ordering_secret';

CREATE SCHEMA catalog AUTHORIZATION catalog_role;
CREATE SCHEMA ordering AUTHORIZATION ordering_role;

Run each module's migrations as its own role so it owns the tables, and put EF Core's migrations history table in that schema.

Postgres blocked both raw SQL shortcuts (the JOIN in TopProductsReport and the UPDATE in ReduceStock):

Npgsql.PostgresException : 42501: permission denied for schema catalog

Neither tool caught all three shortcuts on its own. ArchUnitNET missed the raw SQL because a query is just a string in IL. Postgres let PlaceOrderDirect through because it used CatalogDbContext, which connects as catalog_role.

The tradeoff: more setup. Each module needs its own schema and connection string, and integration tests must run under those roles instead of a superuser, since Postgres only catches queries that run.

Fix the Shortcut or Merge the Modules?

Once the tests fail, run each violation through Checks 1 and 2:

ViolationWhat It DoesVerdict
PlaceOrderDirectReads a product through CatalogDbContextShortcut. Call ICatalogModule instead.
TopProductsReportJoins catalog.products for the product nameShortcut. ordering.orders.product_name already has it.
ReduceStockUpdates stock in catalog.productsBoundary question. Decide with Check 1.

The first two are shortcuts, so a quick refactor fixes them and keeps the boundary intact.

ReduceStock comes down to whether stock can lag behind briefly after an order is saved. If eventual consistency is fine, publish an event and keep the two modules separate. If stock has to update in the same transaction as the order, Ordering and Catalog belong in one module.

Merging puts both sets of tables under one schema, one DbContext, and one role, and drops the public contract. Still, merging is the expensive direction once data and contracts are live. When you're unsure early on, start with one module and split it later.

Summary

Pick one boundary in your codebase that already feels tangled. Add an ArchUnitNET rule for its namespaces and lock down its Postgres schema with a dedicated login role.

Most failures will be shortcuts you can clean up quickly. The ones you can't refactor away without breaking consistency mean those two modules should be one.

If you want a starting point, my free modular monolith template includes two modules, separate schemas, and boundary tests. It uses one database login by default, so adding a role per module is up to you.

In Modular Monolith Architecture, I walk through defining module boundaries and enforcing them with architecture tests across a full system.

Thanks for reading.

And stay awesome!


Frequently Asked Questions

How do you decide whether two parts of a system should be one module or two?

Look at three signals: which use cases have to write to both modules in a single transaction, whether cross-module reads are one-time snapshots or constant live lookups, and how often pull requests touch both sides. Shared transactions and pull requests that keep touching both sides usually mean the two belong in one module.

Should a transaction span two modules in a modular monolith?

Avoid it. Sharing a transaction couples two modules at the database level, so treat a module boundary as a transaction boundary. If two writes must succeed or fail together, keep both tables in one module. If you keep them separate, handle the second write asynchronously through an event and an outbox table.

Can an architecture test enforce module boundaries inside one project?

Yes. ArchUnitNET lets you filter types by namespace, so a single rule can stop types in Shop.Ordering from depending on Shop.Catalog except for Shop.Catalog.Contracts. If someone uses CatalogDbContext inside an Ordering class, the test fails and names the offending types.

Do architecture tests catch raw SQL that queries another module's tables?

No. Architecture tests inspect compiled type references, and a raw SQL query is just a string in IL. A raw SQL join from Ordering into catalog.products passes the architecture test and is only caught in Postgres with error 42501 (permission denied for schema catalog) when each module connects under its own role.

What does a database role per module catch, and what does it miss?

A dedicated Postgres role blocks any SQL query or update against another module's schema at runtime. What it misses is code that uses the other module's DbContext directly, since that DbContext connects with the other module's role. Pairing database roles with architecture tests closes both gaps.

What does merging two modules mean in code?

Both sets of tables move into one database schema, one DbContext, and one database role, and the public contract between them goes away. Merge when features regularly need shared writes or live reads across the boundary. If you are unsure early on, start with one module, since splitting later is cheaper than merging two back together.

  • Build a working Modular Monolith skeleton in .NET: three modules, each with its own schema and DbContext, cross-module calls that go through Contracts projects only, and an in-process event bus. Architecture tests fail the build the moment someone crosses a boundary.

  • We built the system exactly the way a modular monolith is supposed to be built, and that's how I ended up with two modules I couldn't pull apart a year later. Here's how a reasonable boundary decision turns into one you can't undo, and the early signals I walked right past.

  • Learn how to untangle bloated services and split them into clean, modular bounded contexts in a .NET modular monolith - one practical refactor at a time.

Loading comments...

Go deeper

Whenever you're ready, there are 5 ways I can help you:

  1. Learn to deploy and run your apps on a VPS with Dokploy and Tailscale. Keep administration private, automate releases, and practice restoring backups, with source code and a runbook you can reuse.

  2. Join 5,000+ students in this comprehensive course that will teach you the system I use to ship production-ready applications using Clean Architecture. Learn how to apply the best practices of modern software architecture.

  3. Join 2,800+ engineers in this in-depth course that will transform the way you build modern systems. You will learn the best practices for applying the Modular Monolith architecture in a real-world scenario.

  4. Join 1,900+ students in this course that will teach you how to build production-ready REST APIs using the latest ASP.NET Core features and best practices. It includes a fully functional UI application that we'll integrate with the REST API.

  5. Join a community of 5,000+ engineers and software architects. You will also unlock access to the source code I use in my YouTube videos, early access to future videos, and exclusive discounts for my courses.

The .NET Weekly

One practical .NET tip, every Saturday.

Join 66,000+ engineers who read it. Free, and you can unsubscribe any time.