# How to Tell If Two Modules Should Be One

> When two modules need shared transactions, constant live reads, or changes that keep touching both sides, they're probably one module. Here are three checks for evaluating a boundary, plus how to catch boundary violations with ArchUnitNET and Postgres roles in .NET.

Published: 2026-12-05. Author: Milan Jovanović. Topic: The .NET Weekly. Tags: modular-monolith, postgresql, software-architecture, testing.

Canonical: https://milanjovanovic.tech/blog/where-to-draw-module-boundaries

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.

I once split [**order collaboration and the product catalog**](https://milanjovanovic.tech/blog/the-modular-monolith-boundary-i-couldnt-take-back) into two [**modules**](https://milanjovanovic.tech/blog/what-is-a-modular-monolith).
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**](https://milanjovanovic.tech/blog/implementing-the-outbox-pattern) 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.](https://milanjovanovic.tech/blogs/mnw_223/save_together.png)

## 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**](https://milanjovanovic.tech/blog/internal-vs-public-apis-in-modular-monoliths) (`ICatalogModule`) once and copies both onto the order:

```csharp
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.](https://milanjovanovic.tech/blogs/mnw_223/price_copy.png)

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):

```bash
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**](https://milanjovanovic.tech/blog/module-boundaries-bounded-contexts): 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.](https://milanjovanovic.tech/blogs/mnw_223/boundary_shortcuts.png)

First is an [**architecture test**](https://milanjovanovic.tech/blog/5-architecture-tests-you-should-add-to-your-dotnet-projects) with [**ArchUnitNET**](https://github.com/TNG/ArchUnitNET):

```bash
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`:

```csharp
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:

```text
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**](https://milanjovanovic.tech/blog/how-to-keep-your-data-boundaries-intact-in-a-modular-monolith).
Each module connects with its own login role, owns its schema, and has no permissions on the other:

```sql
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`):

```text
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:

| Violation | What It Does | Verdict |
| --- | --- | --- |
| PlaceOrderDirect | Reads a product through CatalogDbContext | Shortcut. Call ICatalogModule instead. |
| TopProductsReport | Joins catalog.products for the product name | Shortcut. ordering.orders.product_name already has it. |
| ReduceStock | Updates stock in catalog.products | Boundary 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**](https://milanjovanovic.tech/templates/modular-monolith-architecture) 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**](https://milanjovanovic.tech/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.
