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

📚 Interview question

Your team runs a modular monolith and some people want to move to microservices. How do you decide whether and when to split, which module to extract first, and how do you extract it safely without a big-bang rewrite?

Modular monolith first: the criteria for splitting a module out, choosing the first candidate, and the step-by-step extraction (contract, data, traffic switch) with rollback.

Senior Architecture Advanced architecture data-ownership microservices modular-monolith service-extraction strangler-fig

🎯 Key points

  • Start modular: strong logical boundaries, one deployable, schema per module
  • Split only for a measured driver: independent scaling, release cadence, team autonomy, fault or security isolation, or a genuinely different stack (GPU, Python ML model, a different data store)
  • Pick the first candidate with few inbound dependencies, a clear contract and a real driver (e.g. a CPU-heavy or spiky module)
  • Prerequisites: module talks only through its contract, owns its schema, no cross-module joins or transactions
  • Extract in steps: contract stable in-process, move data, deploy service, route traffic behind a flag, remove old code
  • Network calls bring latency, partial failure and eventual consistency: timeouts, retries, circuit breakers, idempotency and an outbox
  • Observability first: distributed tracing (OpenTelemetry, Application Insights) and before/after metrics for latency, errors, cost and deployment frequency, with a rollback path

⏱ 30-second answer

I keep a modular monolith until a module has a measured reason to become its own deployable: it needs to scale independently, it has a different release cadence or owning team, it needs fault or security isolation, or it needs a different runtime. "Microservices are modern" isn't a reason.

The first candidate should have few inbound dependencies, a clean contract and its own schema already. Extraction is incremental: make the module talk only through its contract, stop cross-module joins and transactions, move its data, deploy it as a service, and switch traffic behind a feature flag with a rollback path.

The trade-off: every extracted module turns method calls into network calls, so you gain autonomy and isolation but pay with latency, partial failures and eventual consistency.

🗣 Full answer (senior)

How I would answer this in an interview

"My default is a modular monolith: one deployable, but modules with their own schema and a public contract, enforced by architecture tests. It gives us most of the modifiability of microservices without the distributed systems tax. I'd only split a module out when there's a measured driver. The common ones are independent scaling, for example a document-rendering module that pegs the CPU and forces us to scale the whole app; a different release cadence because another team owns it; fault isolation, so a memory leak in one area can't take down checkout; or a security boundary, such as a module that handles card data and should sit in a smaller PCI scope.

For example, at [company] our [quote PDF generation] module caused [70%] of our CPU at month-end and forced us to run [8] App Service instances for everything. I wrote an ADR proposing to extract just that module. Because it already had its own schema and a contract interface, the work was mostly mechanical: we replaced the in-process implementation with an HTTP client behind the same interface, moved its tables with a one-off migration, published 'quote requested' messages through an outbox instead of calling it synchronously, and routed traffic with a feature flag so we could flip back in seconds. Month-end instance count for the main app dropped from [8] to [3], and the PDF service scaled on queue length on its own.

The mistake I see is splitting along technical layers or extracting a module that's tangled with everything else, which produces a distributed monolith where every deploy is coordinated. My senior line is: extract modules for a reason you can measure, one at a time, and make the boundary right inside the monolith before you make it a network boundary."


Reasons to split, and reasons that aren't

Good driver Evidence to look for
Independent scaling One module dominates CPU/memory; scaling the whole app is wasteful
Release cadence / team autonomy A separate team blocked by shared release trains
Fault isolation Incidents in one area take down unrelated features
Security / compliance scope PCI, health data, a smaller audited surface
Different technology GPU workload, Python ML model, different data store
Weak reason Why
"Microservices are best practice" No driver, all cost
"The codebase is messy" A network boundary doesn't fix poor modularity
"So teams can choose any language" Usually raises ops and hiring cost

Choosing the first module

Criterion Prefer
Inbound dependencies Few callers; ideally it is called asynchronously
Data coupling Own schema, no cross-module joins
Driver Clear, measurable (scaling, isolation)
Risk Not on the critical revenue path for the first attempt, or well covered by tests

Extraction steps

Step Done when
1. Harden boundary in-process Only the contract is referenced; architecture tests pass
2. Remove shared transactions and joins Module data accessed only through its contract or events
3. Move data Tables moved to a new database; sync or cut-over plan rehearsed
4. Deploy the service Same contract over HTTP/gRPC or messages, with health checks, telemetry
5. Switch traffic behind a flag Canary, compare error rates and latency
6. Remove the old code path Flag removed after a stable period

Production example

Extracting the [PDF generation] module cut month-end App Service instances for the main app from [8] to [3], saved about [$3k] a month, and removed the CPU spikes that had pushed checkout p95 above [1.5 s].

🔍 What the interviewer is checking

Checks whether the candidate can make a driver-based decision to split and execute an incremental, reversible extraction that handles data and failure modes.

Green flags

  • Lists measurable drivers and rejects fashionable ones
  • Fixes boundaries in-process before extracting
  • Has a concrete plan for data, call style and rollback
  • Measures before and after

Red flags

  • Proposes splitting everything at once
  • Keeps a shared database or distributed transactions
  • Ignores resilience and eventual consistency

📚 Learn in depth

1. Logical vs physical boundaries

A logical boundary (module, namespace, assembly, schema) controls what code can depend on. A physical boundary (process, deployable, database server) controls how it runs and fails. Microservices add physical boundaries; you can get most of the design benefit from logical ones alone.

Modular monolith (one process)            After extracting Documents
┌───────────────────────────────────┐          ┌────────────────────────┐   msg   ┌──────────────────┐
│ Quotes ──► IDocuments contract    │          │ Monolith               │ ─────► │ Documents service │
│ Policies     │                   │          │  Quotes, Policies,     │         │  own DB, scales  │
│ Billing      ▼                   │          │  Billing               │ ◄───── │  on queue length │
│          Documents module         │          │  DB: quotes., billing. │  event  │                  │
│ DB schemas: quotes. documents. …  │          └────────────────────────┘         └──────────────────┘
└───────────────────────────────────┘

2. Why "monolith first"

Martin Fowler's "MonolithFirst" argument: you rarely know the right boundaries at the start, and moving a boundary inside one codebase is a refactor, while moving it between services is a migration. A modular monolith lets the domain teach you where the seams are.

3. Readiness checklist for a module

  1. Contract-only access: other modules reference X.Contracts, never X.Domain or X.Infrastructure (verify with ArchUnitNET or NetArchTest).
  2. Owned data: its tables live in its own schema; no other module reads them directly.
  3. No shared transactions: cross-module work already uses events or explicit calls, not one DbContext spanning both.
  4. Asynchronous where possible: callers can tolerate eventual consistency.
  5. Telemetry: its operations are traceable with OpenTelemetry so you can compare before/after.

4. Moving the data

The hardest part is data, not code.

  • Same server, new database: simplest; copy tables during a short maintenance window or with a dual-write period.
  • Change data capture / replication: keep old and new in sync while traffic moves, then cut over.
  • Read models for others: modules that used to join to the extracted data subscribe to its events and keep their own projection.

5. Changing the call style

An in-process call can't fail halfway; a network call can. When converting:

In-process Over the network
Exceptions Timeouts, transient errors, 5xx
Same transaction Outbox + idempotent consumer, or saga
Microseconds 1-5 ms in-region plus serialisation
Refactor freely Versioned contract

Use Microsoft.Extensions.Http.Resilience (standard resilience handler: timeout, retry, circuit breaker) for HTTP, and the outbox pattern for messages.

6. Traffic switch and rollback

Route through a feature flag (Azure App Configuration or Microsoft.FeatureManagement) at the contract implementation: in-process vs remote. Start with a small percentage, compare error rate and p95 in Application Insights, then increase. Keep the in-process path until the service has been stable for a release or two.

Try it yourself

  1. Draw your modules and the calls between them; count inbound dependencies for each.
  2. Write an architecture test that fails if any module references another module's internals.
  3. Find every query that joins tables from two modules; plan how to remove each.
  4. Implement a feature-flagged switch between an in-process and an HTTP implementation of one contract.
  5. Measure p95 latency of the operation before and after with Application Insights.

💻 Code

Switching one module's contract from in-process to remote behind a feature flag, so extraction is gradual and reversible.

namespace Documents.Contracts;

public sealed record RenderQuotePdf(Guid QuoteId, string TemplateCode);
public sealed record RenderedDocument(Guid DocumentId, Uri Location);

public interface IDocumentsModule
{
    Task<RenderedDocument> RenderQuotePdfAsync(RenderQuotePdf request, CancellationToken ct);
}
namespace Host.Composition;

using Documents.Contracts;
using Microsoft.FeatureManagement;

// Routes to the old in-process module or the new service; flipping the flag is the rollback.
public sealed class RoutingDocumentsModule(
    IFeatureManager features,
    Documents.InProcess.DocumentsModule local,
    Documents.Client.DocumentsHttpClient remote) : IDocumentsModule
{
    public async Task<RenderedDocument> RenderQuotePdfAsync(RenderQuotePdf request, CancellationToken ct) =>
        await features.IsEnabledAsync("Documents.UseRemoteService", ct)
            ? await remote.RenderQuotePdfAsync(request, ct)
            : await local.RenderQuotePdfAsync(request, ct);
}
// Program.cs
builder.Services.AddFeatureManagement();
builder.Services.AddScoped<Documents.InProcess.DocumentsModule>();
builder.Services
    .AddHttpClient<Documents.Client.DocumentsHttpClient>(c => c.BaseAddress = new Uri("https://documents.internal"))
    .AddStandardResilienceHandler(); // timeout, retry with jitter, circuit breaker
builder.Services.AddScoped<IDocumentsModule, Host.Composition.RoutingDocumentsModule>();

⚠ Common mistakes

  • Mistake: Splitting because microservices feel modern. Why it is wrong: You add network, data and ops costs without a benefit. Instead: Require a measured driver per extraction and record it in an ADR.
  • Mistake: Extracting a module that is tangled with everything. Why it is wrong: Every change then needs coordinated deploys, giving you a distributed monolith. Instead: Fix the boundary in-process first; extract modules with few inbound dependencies.
  • Mistake: Keeping a shared database after extraction. Why it is wrong: Schema changes still couple deploys and both sides can break each other's invariants. Instead: Give the service its own database and expose data through its API or events.
  • Mistake: Assuming data stays consistent the way it did in one transaction. Why it is wrong: After extraction, the monolith and the service commit separately; a crash between them leaves data inconsistent, and copies lag. Instead: Use an outbox and idempotent consumers, design screens for eventual consistency, and add reconciliation checks.
  • Mistake: Converting calls to HTTP without resilience. Why it is wrong: Latency adds up and timeouts or transient failures now cascade into the monolith. Instead: Add timeouts, retries with jitter and circuit breakers (AddStandardResilienceHandler), and prefer asynchronous messages where possible.
  • Mistake: Keeping a cross-module transaction by using a distributed transaction. Why it is wrong: Two-phase commit is fragile and not supported across most cloud services. Instead: Use an outbox and idempotent consumers, or a saga.
  • Mistake: Extracting before you can trace a request across the boundary. Why it is wrong: Failures now span two processes and logs alone won't show where time or errors go. Instead: Add OpenTelemetry tracing with W3C trace context and Application Insights before the cut-over.
  • Mistake: Big-bang cut-over with no rollback. Why it is wrong: Any defect becomes an outage. Instead: Switch traffic gradually behind a feature flag and keep the old path for a while.
  • Mistake: Not measuring before and after. Why it is wrong: You can't prove the extraction paid off or spot regressions. Instead: Capture latency, error rate, cost and deployment frequency before you start.

🏛 Senior insight: trade-offs

The question isn't monolith vs microservices; it's where you need physical boundaries. Most systems need very few. I treat each extraction as its own business case with a driver, a cost estimate and a success metric, and I'd rather extract two services that clearly pay off than ten that don't.

Also watch the organisational side: a service without a clear owning team becomes an orphan. Extraction should follow team ownership (Conway's law), not precede it.

Option When it fits Cost When not to
Stay modular monolith One to a few teams, no strong scaling/isolation driver Low One module dominates resources or needs isolation
Extract one module Clear driver, clean boundary, owning team Medium per service Boundary still leaky; no owner
Broad decomposition Many teams, mature platform, independent cadences High Small org, unclear domain

🔗 Follow-ups the interviewer may ask

  1. When: Candidate refers to modules owning their schema Why: Checks they understand how a modular monolith enforces boundaries
    How to 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.

  2. When: Candidate mentions the distributed systems tax Why: Checks they can describe what microservices really cost
    How to answer

    Microservices are small, independently deployable services, each owning one business capability and its own data, talking over the network via APIs or messages.

    • Benefits: independent deployment and scaling, team autonomy, fault isolation, technology choice per service.
    • The distributed systems tax: network latency and partial failure, eventual consistency and sagas instead of transactions, versioned contracts, distributed tracing, and many pipelines and on-call rotations.
    • They mainly solve an organisational problem: many teams needing to release without coordinating (Conway's law).

    They fit when you have several teams, stable boundaries and mature DevOps. Otherwise a modular monolith gives most of the benefits for a fraction of the cost. The worst outcome is a distributed monolith: all the cost, none of the independence.

  3. When: Candidate mentions outbox or sagas when replacing a cross-module transaction Why: Checks they can handle failure points once a call crosses a network
    How to answer

    Each service changes its own data and writes outgoing messages in one transaction (outbox), and dedups incoming messages (inbox). A saga orchestrator persists the order's progress: on OrderPlaced it sends ReserveStock; on StockReserved it sends CapturePayment; on PaymentCaptured it completes. If payment fails it sends the compensation ReleaseStock.

    At every step a crash either committed nothing (the message is redelivered) or committed everything (the outbox resends). Duplicates hit the inbox. Missing replies trigger scheduled timeouts, and late replies after a timeout get their own handling, such as refunding a late capture. Poison messages dead-letter with alerts.

    The trade-off: reliability without distributed transactions, paid for with eventual consistency, more states and more operational tooling.

🛠 Real-world problems: how you handle them

Extracting a CPU-heavy PDF module from a modular monolith
Situation
An [insurance quoting] modular monolith on Azure App Service served [about 300] brokers. The [quote PDF generation] module was a small part of the code but drove month-end load.
Signals
CPU at [90%+] at month-end, autoscale to [8] instances for the whole app, checkout p95 over [1.5 s] during PDF runs, and a hosting bill that doubled every month-end.
Investigation
I used Application Insights performance data and dotnet-counters to attribute CPU to the PDF rendering path, checked the module's dependencies with an ArchUnitNET report, confirmed it had its own schema and only [two] callers, and estimated the cost of a separate Container App scaled on queue length.
Resolution
Immediate: rate-limited PDF generation to protect checkout. Long-term: an ADR to extract the module; callers moved to an outbox-backed `QuoteDocumentRequested` message, tables moved to a new database, the service deployed on Azure Container Apps with KEDA scaling on Service Bus queue length, traffic switched by feature flag over [two] weeks.
Prevention
Architecture tests keep remaining modules contract-only; an extraction checklist (driver, owner, data plan, rollback) in the architecture repo; an Application Insights alert on per-module CPU share.

How to tell it (STAR)

**S:** At [company] our modular monolith scaled to [8] instances every month-end because one module, PDF generation, used [70%] of the CPU. **T:** I was asked to fix the cost and the checkout slowdown without a rewrite. **A:** I proved the cause with Application Insights and dotnet-counters, wrote an ADR to extract only that module, and because it already had its own schema and a contract, we swapped the in-process implementation for messages through an outbox, moved its tables, and switched traffic gradually behind a feature flag with an instant rollback. **R:** Month-end instances for the main app dropped from [8] to [3], checkout p95 stayed under [400 ms], and we saved about [$3k] a month.

↩ Usually asked after

More in Senior-Level Architecture

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me