Full-Stack Web & Next.js Architecture

Microservices vs. Monolithic Architecture: How to Choose the Right Tech Stack for Enterprise Scaling

Decision framework for microservices versus modular monoliths: coupling costs, data ownership, operational overhead and a staged decomposition workflow.

Thushara SanjeewaLead Systems Architect & Media Buying Director8 min read

Most microservices programmes fail for an unglamorous reason: the organisation distributed its code before it understood its data. Teams split a codebase into twenty deployables, then discover that a single user-facing action still touches eleven of them synchronously. The result is a distributed monolith — the deployment complexity of microservices with the coupling of a monolith and none of the independence that justified the migration.

The decision is not ideological. It is an economic tradeoff between two costs: the coordination cost of many teams sharing one deployable, and the operational cost of running a distributed system with partial failure, eventual consistency, and cross-service observability. Below a certain team size and change volume, the first cost is trivial and the second is severe. Above it, the reverse.

This analysis gives CTOs and lead engineers a decision framework grounded in measurable signals rather than architecture fashion: the coupling taxonomy that predicts failure, data ownership rules, the modular monolith as a first-class destination, a comparison of operational tradeoffs, an extraction pattern with code, and a 90-day sequencing plan. The core takeaway: decompose along data ownership and change frequency, and only when you can prove the constraint you are relieving.

Diagnose the Actual Constraint

Before any architectural change, identify which constraint is binding. Each has a different remedy.

  • Deployment contention — teams blocked waiting on a shared release train. Remedy: trunk-based development, feature flags, faster pipelines. Rarely requires service extraction.
  • Scaling asymmetry — one workload (image processing, search, PDF generation) consumes resources disproportionately. Remedy: extract that workload only.
  • Fault isolation — one subsystem's failure degrades everything. Remedy: bulkheads, timeouts and circuit breakers, which are available inside a monolith too.
  • Technology divergence — a component genuinely needs a different runtime, such as a Python inference service. Remedy: extract that boundary.
  • Cognitive load — nobody can reason about the codebase. Remedy: enforce module boundaries first; extraction without modularity just relocates confusion.

If none of these bind, distribution adds cost with no return.

Coupling Taxonomy

Rank coupling from cheapest to most damaging:

  1. Contract coupling — services agree on a versioned schema. Acceptable and manageable.
  2. Temporal coupling — service A cannot answer unless B responds now. Each synchronous hop multiplies failure probability and adds latency.
  3. Data coupling — two services read or write the same tables. This is the fatal one; it eliminates independent deployability entirely.

The single most important rule in enterprise decomposition: one writer per dataset. If two services must write the same rows, they are one service.

The Modular Monolith as a Destination

A modular monolith is not a compromise; for many enterprises it is the correct end state. Enforce internal boundaries with tooling, not etiquette:

  • Package-per-domain with explicit public interfaces, enforced by dependency lint rules or module boundaries in the build system.
  • Schema-per-module in a single database, with cross-module access only through published interfaces — no direct foreign keys across boundaries.
  • Domain events published on an internal bus so future extraction does not require rewriting call sites.
  • One deployable, one transaction manager, one trace context. Strong consistency remains available where the business genuinely requires it.

This preserves the option to extract later at low cost, because the seams already exist.

Extraction Mechanics

When extraction is justified, sequence it to keep the system releasable at every step.

  1. Define the boundary by data. List the tables the candidate service exclusively writes. If the list is empty, the boundary is wrong.
  2. Introduce an internal interface. Route all callers through it while the implementation still runs in-process.
  3. Break read dependencies. Replace cross-boundary joins with API calls, or with a read model populated by events.
  4. Deploy alongside. Run the extracted service and keep the in-process path behind a flag; compare outputs in production.
  5. Cut over and enforce. Move writes, revoke database credentials for other services, and add contract tests to the pipeline.

Asynchronous integration should default to event-carried state transfer with the outbox pattern, idempotent consumers keyed by event ID, and explicit dead-letter handling. Saga-style compensation replaces distributed transactions; two-phase commit across services is not a viable enterprise pattern.

Tradeoff Comparison

DimensionModular monolithMicroservices
Deployment unitOne artifact, fast rollbackMany artifacts, independent release
TransactionsACID within one databaseSagas, compensation, eventual consistency
Latency profileIn-process callsNetwork hops per boundary crossing
Failure surfaceProcess-levelPartial failure is the normal state
Observability needLogs plus metricsDistributed tracing mandatory
Team fit1–4 teams sharing a domain5+ teams with distinct roadmaps
Infra costLowHigher: mesh, registry, per-service pipelines
OnboardingSingle repo, single runbookService catalogue and ownership discipline
Refactoring costCheap, compiler-assistedExpensive, cross-repo and versioned

Implementation Blueprint: Outbox and Idempotent Consumer

The pattern below removes dual-write inconsistency, the most common data-integrity defect in decomposed systems.

ts
// Producer: write business state and event in one transaction
export async function placeOrder(input: { userId: string; total: number }) {
  return db.transaction(async (tx) => {
    const order = await tx.order.create({
      data: { userId: input.userId, total: input.total, status: "PLACED" },
    });

    await tx.outbox.create({
      data: {
        id: crypto.randomUUID(),
        aggregate: "order",
        aggregateId: order.id,
        type: "order.placed.v1",
        payload: { orderId: order.id, userId: input.userId, total: input.total },
      },
    });

    return order;
  });
}

// Consumer: idempotent by event id, safe to retry
export async function handleOrderPlaced(event: { id: string; payload: { orderId: string } }) {
  const claimed = await db.processedEvent
    .create({ data: { id: event.id } })
    .catch(() => null);

  if (!claimed) return; // already processed
  await fulfilment.reserveStock(event.payload.orderId);
}

A relay process publishes unsent outbox rows to the broker with at-least-once delivery; consumer idempotency turns that into effectively-once processing.

Strategic Action Plan: 90 Days

  1. Days 1–15 — Measure, do not assume. Record deploy frequency, lead time, change-failure rate, per-endpoint latency and the top ten cross-module database dependencies. Name the binding constraint explicitly.
  2. Days 16–35 — Modularise in place. Introduce domain packages with enforced boundaries, schema-per-module, and an internal event bus. Ban cross-module table access in CI.
  3. Days 36–55 — Extract one service. Choose the boundary with the clearest exclusive data ownership and the strongest scaling or runtime justification. Implement outbox and idempotent consumers.
  4. Days 56–75 — Build the operational floor. Distributed tracing with propagated context, per-dependency timeouts and circuit breakers, contract tests in the pipeline, and a service ownership catalogue.
  5. Days 76–90 — Review the economics. Compare pre- and post-extraction lead time, failure rate and infrastructure spend. Extract the next boundary only if the numbers justify it; otherwise consolidate.

Frequently Asked Questions

How do we know whether to start with microservices on a new product?

Default to a modular monolith unless you already have multiple teams with independent roadmaps, a workload with radically different scaling characteristics, or a hard runtime requirement such as a separate inference stack. Early products change domain boundaries frequently, and moving a boundary inside one codebase costs hours while moving it across services and repositories costs weeks.

What is a distributed monolith and how do we detect one?

A distributed monolith is a set of separately deployed services that still must be released together. Detect it with three checks: do multiple services write the same tables, does a single user action require more than three synchronous internal hops, and do releases require coordinated version bumps across repositories. Any of these means boundaries were drawn on code structure rather than data ownership.

Should each microservice have its own database?

Yes for writes. Exclusive write ownership is what makes independent deployment possible; shared write access reintroduces coupling at the schema level. Other services obtain data through APIs or events, optionally maintaining their own read models. A shared database instance with strictly separated schemas and revoked cross-credentials is an acceptable transitional step.

How do we maintain consistency without distributed transactions?

Model multi-step business processes as sagas with explicit compensating actions, publish state changes through a transactional outbox so persistence and events cannot diverge, and make consumers idempotent using event identifiers. Where an operation genuinely requires atomicity — payment authorisation with ledger entry, for example — keep it inside a single service and a single database transaction.