📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is a modular monolith? Explain modules that own their data or schema, how modules talk to each other through internal APIs or events, and how you enforce boundaries in a single .NET deployable.

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.

Intermediate Theory Intermediate architecture bounded-context ef-core microservices modular-monolith module-boundaries

🎯 Key points

  • One deployable, many modules aligned to business capabilities (bounded contexts), not technical layers
  • Each module owns its data: its own schema and DbContext; no cross-module joins or foreign keys — share data through contracts, events or read models
  • Modules expose a small public contract (interface, DTOs) and/or integration events; everything else is internal
  • One transaction per module (ACID inside); cross-module changes are eventually consistent via integration events, with an outbox where loss is unacceptable
  • Enforce with separate projects, internal types, architecture tests and per-module database permissions
  • Benefits: simple deployment, in-process speed, easier refactoring than microservices
  • Observe per module: tag logs, traces and metrics with the module name to spot hot or noisy modules
  • Designed so a module can be extracted later; costs: discipline, one shared runtime, release train and scaling unit

⏱ 30-second answer

A modular monolith is one deployable split into modules aligned to business capabilities — Orders, Billing, Catalogue — each with hard boundaries.

  • Each module owns its data: its own schema and DbContext, no cross-module joins or foreign keys.
  • Modules talk only through a public contract (an interface and DTOs) or integration events; everything else is internal.
  • Boundaries are enforced: separate projects, 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 DbContext per 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.GetOrderTotalAsync returning a DTO — and everything else in the module is internal. For reactions, they publish integration events, like OrderPlaced, 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 DbContext and 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."


Monolith vs modular monolith vs microservices

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

Ways modules communicate

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

Decision table

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

Production example

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.

🔍 What the interviewer is checking

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

  • Mentions schema or DbContext per module and no cross-module joins
  • Describes a small public contract plus events, with internal implementation
  • Names concrete enforcement (architecture tests, project references, DB permissions)
  • Explains how a module could be extracted later

Red flags

  • Modules are just folders sharing one DbContext
  • Splits modules by technical layer
  • Sees it only as a stepping stone with no value of its own

📚 Learn in depth

1. The structure

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

2. Project layout

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.

3. Data ownership

  • OrdersDbContext calls modelBuilder.HasDefaultSchema("orders") and has its own migrations history table (MigrationsHistoryTable("__EFMigrationsHistory", "orders")).
  • No foreign keys across schemas. Billing stores OrderId as a plain value.
  • Optional hardening: a database user per module with GRANT only on its schema, used through a module-specific connection string.
  • Reporting that needs data from many modules reads from a reporting projection or a read replica, not by joining live module tables.

4. Transactions

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.

5. How it decays

  1. Someone adds Include(o => o.Invoice) across modules "just once".
  2. A shared Common project grows business logic.
  3. Modules call each other's internals via 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.

6. Extraction path

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.

Try it yourself

  1. Create two module projects with their own DbContext and schema, and generate migrations for each with --context.
  2. Write an ArchUnitNET or NetArchTest rule: types in Billing may not depend on Orders except Orders.Contracts.
  3. Create a SQL user granted only on the billing schema and confirm a cross-schema SELECT fails.
  4. Publish an OrderPlaced event after SaveChanges and handle it in Billing; then make Billing throw and confirm the order still saves.
  5. Replace IBillingApi's in-process implementation with an HTTP client and run the same tests.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Sharing one 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.
  • Mistake: Cross-module foreign keys and joins. Why it is wrong: they couple schemas so modules can't evolve or be extracted independently. Instead: store ids as plain values and compose data through contracts or read models.
  • Mistake: Making everything 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.
  • Mistake: Splitting modules by technical layer (a "Data" module, a "Services" module). Why it is wrong: changes still cut across every module. Instead: split by business capability or bounded context.
  • Mistake: Updating several modules in one transaction by default. Why it is wrong: it couples them at run time and blocks extraction. Instead: one module per transaction; react to events, with an outbox where loss is unacceptable.
  • Mistake: A 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.
  • Mistake: No enforcement. Why it is wrong: boundaries erode one shortcut at a time. Instead: architecture tests in CI, CODEOWNERS per module, per-schema database permissions.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says modules can be extracted into services later. Why: Checks whether they can design for evolution with fitness functions and reversible decisions.
    How to answer

    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.

  2. When: Candidate mentions publishing events between modules. Why: Checks whether they know how to make those events reliable with an outbox.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Cross-module joins block extraction of a hot module
Situation
A [grants-management] modular monolith, [6] modules on one Azure SQL database in Australia East, [3] teams. The document-processing module needed separate scaling because OCR jobs pegged CPU during application rounds.
Signals
CPU at [95%] on the App Service during rounds, slowing every module; extraction estimate ballooned because [14] queries joined `docs.*` with `applications.*`; two modules shared a `DbContext`.
Investigation
Ran an architecture test listing cross-module dependencies; queried `sys.sql_expression_dependencies` and Query Store for statements touching more than one schema; reviewed the Application Insights application map to see call patterns.
Resolution
Short term: moved OCR to a queue-triggered background worker with a concurrency limit so the web tier recovered. Long term: replaced the cross-schema joins with a `DocumentSummary` read model updated by events, split the shared `DbContext`, then extracted the module into Azure Container Apps.
Prevention
Per-module database logins with schema-only grants; architecture tests failing on cross-module references; a quarterly review of modules' load and change coupling; ADR recording the extraction criteria.

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.

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me