Skip to content

Lesson 16 of 28Architecture

Monolith vs Microservices

Start with a modular monolith, know when microservices pay off, draw service boundaries, and migrate with the strangler fig.

18 min read0/4 questions

"Should we use microservices?" is one of the most expensive questions a team can get wrong. Split too early and five engineers spend their week on deploy pipelines and network bugs instead of features. Split too late and fifty engineers queue behind one release train. System design interviews probe this trade-off directly, and a nuanced answer is a strong senior signal.

Three shapes

  • A monolith is one codebase, deployed as one unit, usually with one database. A Django or FastAPI app on a few servers is a monolith.
  • A modular monolith is still one deployable, but its code is split into modules (orders, billing, catalog) with strict boundaries: each module exposes a small public API and owns its tables. Other modules may not reach inside.
  • Microservices split the system into many small services, each deployed independently, each owning its own data, talking over the network.
A modular monolith
One deployable appCustomersCustomersLoad balancerLoad balancerorders moduleorders modulebilling modulebilling modulecatalog modulecatalog modulePostgres: one schema per modulePostgresone schema per moduleHTTPSfunction callfunction callSQL

A request reaches the app. Everything runs in one process, so there is one thing to deploy and monitor.

1/3
The same system as microservices
Web / mobileWeb / mobileAPI gatewayAPI gatewayorders-svcorders-svccatalog-svccatalog-svcbilling-svcbilling-svcEvent bus: Kafka / SNS+SQSEvent busKafka / SNS+SQSnotify-svcnotify-svcorders DBorders DBbilling DBbilling DBHTTPSRESTRESTgRPCpublishconsume

The gateway routes /orders to its own service. Each service is deployed, scaled and owned separately.

1/4

Start with a modular monolith

For most teams under roughly 20 to 30 engineers, a modular monolith is the right default. You get clean boundaries without paying the network tax. The key is to enforce those boundaries in code so they stay real:

Python
# billing/api.py: the ONLY thing other modules may import from billingclass _Invoices: # private: other modules must not touch this directly rows: dict[int, int] = {} def create_invoice(order_id: int, cents: int) -> int: _Invoices.rows[order_id] = cents return order_id def invoice_total(order_id: int) -> int: return _Invoices.rows[order_id] # orders/service.py: talks to billing through its public APIdef place_order(order_id: int, cents: int) -> str: invoice_id = create_invoice(order_id, cents) return f"order {order_id} invoiced as #{invoice_id} for {invoice_total(order_id)}" print(place_order(42, 4999))
Output
Press Run (⌘ Enter) to see what happens.

Tools make the rule stick: import-linter in Python and ESLint's no-restricted-imports (or Nx module boundaries) in TypeScript fail the build when one module imports another's internals. If you later extract billing into a service, only billing/api.py changes from function calls to HTTP calls.

When microservices pay off, and what they cost

Microservices pay off whenBecause
Many teams (often 50+ engineers) block each other's releasesEach team deploys its service on its own schedule
One hot path needs very different scalingScale search to 40 instances while billing stays at 2
Parts need different tech or reliabilityA Python ML service next to a Go payments service
Fault isolation mattersA crash in recommendations does not take down checkout

The costs are real and arrive on day one:

  • Network. Calls are slow and can fail. You need timeouts, retries, circuit breakers and idempotency.
  • Data consistency. No transaction spans two services. You need events, sagas (covered in Event-Driven Architecture) and tolerance for "eventually consistent".
  • Operations. N pipelines, N dashboards, distributed tracing (OpenTelemetry), service discovery, versioned APIs, contract tests.
Predict the outputPython

What does this print?

# A request must pass through 5 services in a chain.
# Each one is up 99.9% of the time, independently.
chain = 0.999 ** 5
print(round(chain * 100, 2))
Need a nudge? Hints walk you through it.
Quick check
A team split their app into 8 services. Every release still needs all 8 deployed together, and they all read the same database. What do they have?
Need a nudge? A hint rules out a wrong answer.

Drawing boundaries: business capabilities

Split by what the business does, not by technical layer. "Billing", "Catalog", "Shipping" and "Identity" are good services. "Database service" and "validation service" are not, because every feature change would touch all of them.

Domain-Driven Design (DDD, from Eric Evans' 2003 book) gives this a name: a bounded context. In plain words, it is the area where a word has one meaning. "Customer" in billing means a payer with a tax ID and a card. In shipping it means a delivery address and a phone number. Forcing one giant Customer model to serve both couples the teams. Give each context its own model, linked by a shared customer_id.

How services talk

StyleExamplesGood forWatch out for
Synchronous requestREST over HTTP, gRPCQueries that need an answer now ("is this card valid?")Chains of calls, cascading failures
Asynchronous eventsKafka, RabbitMQ, SNS+SQSReacting to facts ("order placed")Eventual consistency, duplicate delivery

gRPC uses HTTP/2 and Protocol Buffers for fast, strongly typed calls between services. REST with JSON is simpler and better for public APIs. Many systems use both: sync for reads, events for side effects.

Match the pairs0/4 matched

Pick the best fit for each case.

Choose an item, then its match on the other side.

Migrating: the strangler fig

A strangler fig grows around a host tree until it can stand alone. The strangler fig pattern (named by Martin Fowler in 2004) migrates a legacy system the same way: put a proxy in front of it, rebuild one capability at a time as a new service, and switch its routes over. You never do a big-bang rewrite, and you can stop or roll back at any point.

Strangling a legacy monolith
UsersUsersRouting proxy: nginx / API gatewayRouting proxynginx / API gatewayLegacy monolithLegacy monolithinvoices-svc: newinvoices-svcnewLegacy DBLegacy DBInvoices DBInvoices DBall other/invoicessync data

Step 1: add the proxy. Every request still goes to the legacy app. Nothing visible changes, but you now control routing.

1/4
Put it in order5 steps

Put a strangler fig migration in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

Strangler fig router

You are migrating a monolith with the strangler fig pattern. Write route(path, migrated) that returns "new" if the request should go to the new services, or "legacy" otherwise.

migrated is a list of path prefixes like ["/invoices", "/payments"]. A path matches a prefix only on whole segments:

route("/invoices", ["/invoices"])        ->  "new"
route("/invoices/42", ["/invoices"])     ->  "new"
route("/invoices-old", ["/invoices"])    ->  "legacy"   (different segment)
route("/invoices?page=2", ["/invoices"]) ->  "new"      (ignore the query string)
route("/invoices/", ["/invoices"])       ->  "new"      (ignore a trailing slash)
def route(path: str, migrated: list[str]) -> str: # Strip the query string and trailing slash, then match whole segments. pass
Key terms
modular monolith
One deployable app split into modules with strict public APIs and owned data.
microservice
A small service deployed independently, owning its own data, communicating over the network.
distributed monolith
Services that must deploy together or share a database: network costs without independence.
bounded context
A part of the business where each term has one meaning and its own model.
strangler fig
Migrating a legacy system piece by piece behind a routing proxy instead of rewriting it all at once.
gRPC
A fast, typed RPC framework over HTTP/2 using Protocol Buffers, common between internal services.