14. Monolith vs Microservices

Big picture: A monolith is one kitchen cooking everything; microservices are separate stalls in a food court. Both can serve great food β€” the question is whether you need independent kitchens, menus, and staffing yet.


Learning goals

After this chapter you should be able to:

  • Define monolith, modular monolith, and microservices in plain language
  • List pros/cons of each approach without treating microservices as "always better"
  • Explain when not to split services (most early products)
  • Draw either architecture cleanly in an HLD diagram
  • Choose sync vs async communication between components
  • Spot the shared database anti-pattern
  • Describe a realistic evolution path from MVP to extracted services

Prerequisites: 04-clients-servers-apis.md, 08-databases.md, 12-queues-async.md


Everyday analogy: food truck vs food court

The food truck (monolith)

One food truck has one chef, one menu, one cash register. They make tacos, burgers, and fries in the same small kitchen.

AdvantageWhy
Simple operationsOne vehicle to maintain, one health inspection
Easy coordinationChef sees entire order; fries and burger ready together
Fast to startOpen tomorrow with one setup
DisadvantageWhy
Can't scale one itemBurger demand spikes β†’ you scale the whole truck
One grease fireKitchen problem shuts down everything
Crowded kitchenMore menu items β†’ chefs bump into each other

The food court (microservices)

A food court has separate stalls: Taco Stand, Burger Bar, Smoothie Shop. Each has its own staff, ingredients, and line. A central seating area (API gateway / frontend) connects them for the customer.

AdvantageWhy
Scale independently10x burger demand β†’ hire at Burger Bar only
Team ownershipTaco team deploys new salsa recipe without touching burgers
Technology choiceSmoothie shop buys industrial blender; taco stand doesn't need one
DisadvantageWhy
Coordination overhead"Combo meal" needs two stalls + payment split
Partial failureBurger Bar open, Smoothie Shop closed β€” awkward experience
More infrastructureSeparate inventory, staffing, health permits per stall

Beginner takeaway: Most successful apps start as a food truck (monolith). They become a food court (microservices) when clear boundaries, team size, and scaling needs justify the overhead.


Monolith

A monolith is one deployable application that implements many features β€” often one codebase compiled into one binary or one Docker image.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Monolith API App               β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚  Auth   β”‚ β”‚  Feed   β”‚ β”‚   Payments   β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ Notificationsβ”‚ β”‚      Search         β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                    β”‚
         β–Ό                    β–Ό
    [(Postgres)]         [(Redis)]

Real examples of successful monoliths (often for years):

  • Shopify (modular monolith)
  • Stack Overflow
  • Many early-stage startups running a single Rails/Django/Spring app

Pros

BenefitExplanation
Simple developmentOne repo, one build, one debug session
Easy transactionsBEGIN … UPDATE inventory … INSERT order … COMMIT in one DB
Single deploymentNo version skew between "auth service v2" and "feed service v1"
Lower ops burdenOne process to monitor, one log stream (initially)
Refactoring is localRename a function; IDE finds all callers

Cons

DrawbackExplanation
Scaling is coarseTraffic spike on media uploads scales entire app
Blast radiusMemory leak in search indexer crashes payments
Team friction at scale50 engineers stepping on same codebase
Technology lock-inHard to use Python for ML and Go for gateway in one binary
Long build/test cyclesFull test suite runs for every small change

Microservices

Microservices split the system into independently deployable services, each owning a business capability, communicating over the network (HTTP, gRPC, message queues).

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   User   β”‚  β”‚   Feed   β”‚  β”‚  Media   β”‚  β”‚  Notification    β”‚
β”‚ Service  β”‚  β”‚ Service  β”‚  β”‚ Service  β”‚  β”‚  Service         β”‚
β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     β”‚             β”‚             β”‚                  β”‚
     β–Ό             β–Ό             β–Ό                  β–Ό
 [(User DB)]  [(Feed DB)]  [(S3 + Queue)]    [(Queue + Email)]

Each service ideally:

  • Has its own data store (or clearly owned tables)
  • Can be deployed independently
  • Is maintained by a team with clear ownership

Real examples:

  • Netflix (hundreds of services)
  • Uber (domain-oriented services)
  • Amazon ( famously "two-pizza teams")

Pros

BenefitExplanation
Independent scalingScale chat gateway for 1M WebSockets without scaling billing
Independent deploymentShip notification fix Friday without redeploying feed
Team autonomyFeed team owns feed SLA end-to-end
Polyglot techML ranking in Python, payments in Java
Fault isolationRecommendation service down; core feed still loads

Cons

DrawbackExplanation
Distributed complexityNetwork latency, partial failures, eventual consistency
Harder debuggingOne user request spans 8 services β€” need tracing
No free transactionsCross-service "all or nothing" requires sagas/compensation
Operational overheadCI/CD per service, service discovery, more dashboards
Integration testingContract tests, staging environments, version compatibility

Side-by-side comparison

DimensionMonolithMicroservices
Deploy units1Many
Cross-feature transactionEasy (single DB)Hard (saga, outbox)
Scale granularityWhole appPer service
Team structureOne team earlyTeam per service later
Failure blast radiusWhole appIsolated (if done well)
Best forMVP, small teams, unclear boundariesClear domains, large org, different scale profiles
Interview default"Modular monolith, extract later"Draw logical services; note MVP may be one deployable

Modular monolith: the smart middle ground

A modular monolith is one deployable application with clear internal module boundaries β€” like a food truck with separate prep stations that don't share cutting boards.

monolith/
  auth/          ← module: no imports from feed/
  feed/
  payments/
  shared/        ← minimal shared kernel only

Rules that keep it modular

RuleWhy
Modules communicate via public interfaces, not direct DB access across modulesExtraction to service later is easy
Each module owns its tablesAvoid shared-database trap inside monolith
No "god module" importing everythingBoundaries stay honest
Feature flags / package boundaries enforced in CIPrevents spaghetti

Interview phrase:

"I'll draw this as separate logical components β€” User, Feed, Media β€” but for MVP they'd live in one deployable modular monolith. We'd extract Media Service first when transcoding CPU justifies independent scaling."

This shows maturity: you understand microservices and know when not to pay their cost.


When to split (and when NOT to)

Do NOT split when:

  • Team is < ~10 engineers
  • Product boundaries are still shifting weekly
  • You haven't felt pain (deploy conflicts, scaling bottleneck, ownership confusion)
  • You're splitting because "Netflix does it"

Consider splitting when:

SignalExampleService to extract
Different scaling needsVideo transcoding is CPU-heavyMedia Processing Service
Different traffic patternsNotifications are spiky, asyncNotification Service
Different storageFull-text search needs ElasticsearchSearch Service
Different SLA / release cadencePayments needs slow, audited releasesPayment Service
Team ownership8 engineers only work on chatChat Gateway Service
Regulatory isolationPCI scope reductionPayment Service with own DB

How to split: domain boundaries, not technical layers

Good splits (business capabilities):

  • UserService β€” accounts, profiles, auth
  • OrderService β€” cart, checkout, order history
  • InventoryService β€” stock levels, reservations

Bad splits (technical layers):

  • DatabaseService β€” all SQL for everyone ❌
  • ValidationService β€” all input validation ❌
  • UtilsService β€” shared helpers as a network call ❌

Analogy: You wouldn't split a restaurant into "Knife Service" and "Plate Service." You split by cuisine or by front-of-house vs kitchen.


Communication styles: sync vs async

When services (or modules) talk to each other:

Comparison table

StyleProtocolUser waits?Use whenRisk
SyncHTTP REST, gRPCYes (usually)Need immediate answer: "Is seat available?"Cascading latency & failures
AsyncSQS, Kafka, RabbitMQNoSide effects: send email, update analyticsEventual consistency, duplicate handling

Sync example: checkout asks inventory

POST /inventory/reserve { sku, qty }
β†’ 200 { reserved: true, reservation_id }
β†’ 409 { reserved: false, reason: "out of stock" }

User's checkout flow depends on the answer β€” sync makes sense.

Async example: order placed β†’ side effects

Event: order.placed { order_id, user_id, items }
Consumers:
  - NotificationService β†’ send confirmation email
  - AnalyticsService β†’ increment revenue metrics
  - WarehouseService β†’ print pick list

User doesn't wait for email to send β€” async decouples.

Choosing in interviews

QuestionSyncAsync
Does the user need the result to continue?βœ“
Can this fail without failing the main action?βœ“
Is fan-out to many subscribers needed?βœ“
Is strong consistency required across steps?βœ“ (or single monolith TX)

The shared database anti-pattern

The worst microservices mistake: three services, one database, shared tables.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Order   β”‚     β”‚  User    β”‚     β”‚ Inventoryβ”‚
β”‚ Service  β”‚     β”‚ Service  β”‚     β”‚ Service  β”‚
β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
     β”‚                β”‚                β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                      β–Ό
              [(One Postgres)]
              orders, users, inventory
              ← all services read/write all tables

This is a distributed monolith:

  • Can't deploy Order Service without coordinating schema changes with User Service
  • No true isolation β€” one bad query locks tables for everyone
  • You pay microservices complexity without microservices benefits

The fix: database per service (logical or physical)

ApproachDescription
Physical separationEach service has its own Postgres instance
Logical separationOne Postgres cluster, but Order Service only accesses orders schema; enforced by credentials/code review
Integration via API/eventsUser Service exposes GET /users/{id}; Order Service stores user_id, not a copy of user profile (or caches denormalized snapshot via events)

Data duplication is OK when intentional: Order Service might store user_display_name denormalized, updated by user.updated events β€” trading consistency for autonomy.


Example evolution: social app

Phase 1 β€” MVP monolith

Single Rails/Node app
  β†’ Postgres (all tables)
  β†’ Redis (sessions, cache)
  β†’ S3 (photos)
One team, one deploy per day

Good enough for: 10K DAU, 5 engineers.

Phase 2 β€” modular monolith

Same deployable, but modules:
  auth/, feed/, media/, notifications/
CI enforces: media/ cannot import from notifications/ internals

Good enough for: 500K DAU, 15 engineers, occasional deploy conflicts.

Phase 3 β€” extract first service

Extract Media Service because:

  • CPU-heavy image processing saturates API servers
  • Needs GPU workers, different autoscaling rules
  • Team of 4 owns media pipeline
Monolith (auth, feed, social graph)
Media Service (upload, transcode, CDN URLs)
  ↔ communicate via HTTP + SQS events

Phase 4 β€” extract Notification Service

Because:

  • Spiky traffic (viral post β†’ millions of push notifications)
  • Async by nature
  • Third-party integrations (FCM, SendGrid) isolated
Monolith β†’ publishes post.created
Notification Service β†’ consumes, fans out push/email

API Gateway in microservices

Clients shouldn't call 12 internal services directly.

Gateway handles: auth token validation, rate limiting, routing, SSL termination.

Analogy: Food court has one ordering kiosk facing customers; individual stalls work in the back.


Common mistakes

MistakeReality
"Microservices from day 1"Most startups fail from complexity, not from monolith limits
Splitting by layerCreates chatty, fragile systems
Shared databaseDistributed monolith β€” worst of both worlds
Sync chains A→B→C→D400ms+ latency, fragile; use async or consolidate
No distributed tracingImpossible to debug cross-service requests
Ignoring eventual consistency"But the UI shows stale data!" β€” design for it
Extracting before measuringSplit when data shows bottleneck, not because diagram looks cool

How to draw this in HLD interviews

Option A: Monolith (say it explicitly)

"Single deployable with internal modules for auth, feed, and media metadata."

Option B: Logical microservices (MVP still one box)

"Logical separation for clarity; MVP could merge User+Feed into one service."

Both are valid if you explain your reasoning.


Check your understanding (Q&A)

1. Name one advantage of a monolith for early products.

Answer

Faster development with one codebase and one deployment pipeline. Cross-feature operations (e.g., creating a user and their first post) can use a single database transaction without distributed coordination.

2. Why are distributed transactions hard?

Answer

Multiple services may each commit to their own database. If step 3 fails after steps 1–2 succeed, there's no single "ROLLBACK" across services. You need patterns like sagas (compensating actions), outbox, or accept eventual consistency β€” all more complex than a monolith transaction. See 18. Transactions & Isolation.

3. What is a modular monolith?

Answer

One deployable application structured into well-bounded internal modules (auth, feed, payments) with explicit interfaces and owned data. It deploys as one unit but is organized so modules can later become separate microservices with minimal rewrite.

4. What is the shared database anti-pattern?

Answer

Multiple "microservices" reading and writing the same database tables directly. Coupling remains as tight as a monolith, but you also suffer network latency and operational overhead between services β€” a distributed monolith.

5. When would you choose async over sync between services?

Answer

When the caller doesn't need an immediate result for the user-facing flow: sending emails, updating analytics, fan-out notifications, or any side effect that can happen eventually. Async also absorbs traffic spikes and allows retries without blocking the user.

6. Give a good reason to extract a service from a monolith.

Answer

Different scaling profile: e.g., media transcoding is CPU-bound and needs worker pools autoscaling separately from stateless API servers. Or organizational: a dedicated team owns payments and needs independent release cadence for compliance.

7. Why shouldn't you split into a "DatabaseService"?

Answer

That's splitting by technical layer, not business domain. Every feature still depends on it, creating a bottleneck and tight coupling. The network hop adds latency without independent business ownership or scaling benefit.


Quick reference card

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  START: modular monolith (one deploy, clear modules)         β”‚
β”‚  SPLIT WHEN: scale, team, or domain boundary justifies cost  β”‚
β”‚  SPLIT BY: business capability (User, Order, Media)          β”‚
β”‚  AVOID: shared DB across services (distributed monolith)     β”‚
β”‚  SYNC: need immediate answer                                 β”‚
β”‚  ASYNC: side effects, fan-out, spike absorption              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Next: 15. Reliability, Security & Observability β€” how to design systems that fail gracefully, stay secure, and tell you when something breaks.