DEV Community

Cover image for Monolith Modular vs Microservices
Naur
Naur

Posted on Edited on

Monolith Modular vs Microservices

Software architecture is often mistaken for drawing clean boxes on a whiteboard. As Mark Richards and Neal Ford point out in Fundamentals of Software Architecture, architecture is actually the art of making structural decisions that are expensive to reverse later: where data lives, how modules communicate, and which boundaries protect your business domains over years of change.

There is no architectural style without downsides. Every choice carries a price tag. Let's walk through a concrete e-commerce workflow (Orders, Payments, and Inventory) across three stages — Traditional Monolith, Modular Monolith, and Microservices — to examine what changes in code, data ownership, and operational complexity.


Technical Partitioning vs. Domain Partitioning

Before splitting servers or containers, the most consequential boundary decision happens inside the codebase itself:

  • Technical Partitioning groups code by technical layer (controllers/, services/, repositories/). While common in small apps, adding or changing an inventory rule forces you to touch files across every horizontal layer.
  • Domain Partitioning slices the codebase vertically by business capability (orders/, payments/, inventory/). Containing changes inside vertical slices lowers efferent coupling (fan-out) and stabilizes afferent coupling (fan-in), laying the foundation for both a Modular Monolith and future service extraction.

1. The Traditional Coupled Monolith

In an unstructured monolith without domain boundaries, classes freely query and mutate tables belonging to other domains:

// app.js - everything mixed together without domain boundaries
class ECommerceApp {
  createOrder(userId, items) {
    const product = db.query(`SELECT * FROM products WHERE id = ${items[0].id}`);
    if (product.stock < items[0].qty) throw new Error("Out of stock");

    db.query(`UPDATE products SET stock = stock - ${items[0].qty}`);

    const paymentOk = this.chargeCard(userId, product.price);
    if (!paymentOk) {
      // Fragile manual rollback leaked into order logic
      db.query(`UPDATE products SET stock = stock + ${items[0].qty}`);
      throw new Error("Payment failed");
    }

    db.query(`INSERT INTO orders (user_id, product_id, status) VALUES (...)`);
    this.sendEmail(userId, "Order confirmed!");
  }
}
Enter fullscreen mode Exit fullscreen mode

The real problem isn't the single deployment unit — it's the lack of boundaries. A seemingly harmless column change in products can silently break checkout or billing.


2. The Modular Monolith ("Modular Monolith First")

A Modular Monolith keeps a single deployment artifact and a single process, while enforcing strict domain ownership in code. Each module owns its tables exclusively and communicates strictly through explicit module interfaces — never through raw cross-domain SQL:

src/
├── orders/
│   ├── order.service.js
│   └── order.repository.js
├── payments/
│   ├── payment.service.js
│   └── payment.repository.js
└── inventory/
    ├── inventory.service.js
    └── inventory.repository.js
Enter fullscreen mode Exit fullscreen mode
// orders/order.service.js
const InventoryService = require('../inventory/inventory.service');
const PaymentService = require('../payments/payment.service');

class OrderService {
  async createOrder(userId, items) {
    // Direct in-memory call via explicit module interface
    await InventoryService.reserve(items);

    try {
      await PaymentService.charge(userId, this.calculateTotal(items));
    } catch (err) {
      await InventoryService.release(items); // Clean in-process compensation
      throw err;
    }

    return this.repository.save({ userId, items, status: 'confirmed' });
  }
}

// inventory/inventory.service.js
class InventoryService {
  async reserve(items) {
    // Only this module mutates the inventory table
    return this.repository.decrement(items);
  }
}
Enter fullscreen mode Exit fullscreen mode

Why this shines: You get clean domain isolation, local ACID transactions, zero network serialization latency, and simple CI/CD.


3. Microservices & Conway's Law

In Microservices, each domain becomes an independently deployable application with its own codebase, its own CI/CD pipeline, and its own dedicated database:

┌────────────────────┐     ┌────────────────────┐     ┌─────────────────────┐
│   Order Service    │────▶│  Payment Service   │     │  Inventory Service  │
│    (port 3001)     │     │    (port 3002)     │     │     (port 3003)     │
│   DB: orders_db    │     │  DB: payments_db   │     │   DB: inventory_db  │
└────────────────────┘     └────────────────────┘     └─────────────────────┘
Enter fullscreen mode Exit fullscreen mode
// order-service/index.js
app.post('/orders', async (req, res) => {
  const { userId, items } = req.body;

  const stockOk = await fetch('http://inventory-service:3003/reserve', {
    method: 'POST',
    body: JSON.stringify({ items })
  });
  if (!stockOk.ok) return res.status(400).send("Out of stock");

  const payment = await fetch('http://payment-service:3002/charge', {
    method: 'POST',
    body: JSON.stringify({ userId, amount: 199.90 })
  });
  if (!payment.ok) {
    // Over a network, even this compensating call can time out!
    await fetch('http://inventory-service:3003/release', {
      method: 'POST',
      body: JSON.stringify({ items })
    });
    return res.status(400).send("Payment failed");
  }

  await ordersDb.save({ userId, items, status: 'confirmed' });
  res.json({ success: true });
});
Enter fullscreen mode Exit fullscreen mode

When two services share the same database tables, independent deployability disappears — leaving you with all the pain of distributed systems and none of the autonomy. True microservices reflect Conway's Law (like Amazon's 2002 API Mandate enabling autonomous two-pizza teams) and demand mature DevOps, automated CI/CD, and distributed tracing.


Side-by-Side Comparison

Dimension Traditional Monolith Modular Monolith Microservices
Deployments 1 1 N (one per service)
Database Shared, no boundaries Shared DB, strict module owners Dedicated DB per service
Communication Direct, coupled In-memory via module contracts Network (HTTP / gRPC / Events)
Operational Overhead Low Low High
Scaling Teams Hard Medium / Good High (autonomous squads)
Scaling Infra Whole app Whole app Per-service elasticity
CAP Trade-offs? No No Yes

Paying the Network Tax: CAP Theorem & Resilience Patterns

Replacing an in-memory method call with a network call introduces partial failures: packets drop, latency spikes, or a target service commits work while the response is lost on the way back.

Under network partitions, the CAP Theorem forces a choice between Consistency (C) — rejecting operations until nodes agree — and Availability (A) — accepting writes and reconciling via eventual consistency.

Inside a Modular Monolith, calling PaymentService from OrderService runs in the same OS process: it only fails if the entire process crashes. There is no gray zone where a customer's card was charged on another machine while the network dropped before Orders found out.

Patterns born from this distributed trade-off:

  1. Saga Pattern: Decomposes distributed workflows into local transactions paired with explicit compensating actions when a step fails.
  2. Choreography vs. Orchestration: Event-driven choreography (Kafka/RabbitMQ) keeps services decoupled via domain events, whereas orchestration centralizes conditional workflow state, retries, and rollbacks.
  3. Circuit Breaker: Fails fast when a downstream dependency degrades, preventing thread-pool exhaustion and cascading outages.
  4. Idempotency: Since message brokers usually deliver at-least-once, consumers must handle duplicate messages safely (via idempotency keys) without charging a customer twice.

When to Use Each Style

  • Traditional Monolith: Quick throwaway prototypes, hackathons, or tiny short-lived scripts.
  • Modular Monolith (Recommended Default): Best starting point for greenfield products, startups, and small-to-mid-sized teams. Fixing a wrong domain boundary in a modular monolith is an afternoon refactor; fixing wrong service boundaries in microservices means cross-database migrations and multi-repo API coordination.
  • Microservices: Earned when concrete scaling or organizational forces emerge — asymmetric load profiles (e.g., search receiving 1,000x more traffic than billing), multiple autonomous squads deploying on independent schedules, and solid observability foundations.

Top comments (0)