TExcelTAD
Home › System Design › Microservices vs Monolith

Microservices vs Monolith

A monolith is one deployable application that contains all features: users, catalogue, orders, payments, all in one codebase, one process type and usually one database. A microservice architecture splits those features into separately deployed services that talk over the network, each owning its own data.

text
Monolith                               Microservices
+--------------------------+           [users] [catalog] [orders] [payments]
| users | catalog | orders |              |       |        |   \      |
| payments | search | ...  |            (db)    (db)     (db)  queue  (db)
+--------------------------+
          |                            each: own repo/pipeline, own team, own scaling
       (one db)

The trade-offs

Monolith Microservices
Getting started Simple: one repo, one deploy Heavy: service discovery, CI/CD per service, observability
Calls between modules Function calls: nanoseconds, never "partially fail" Network calls: milliseconds, timeouts, retries
Transactions One database transaction Sagas and eventual consistency
Scaling Scale the whole app Scale only the hot service
Deploys Everything ships together Teams ship independently
Failure isolation A memory leak takes down everything A crashing service can degrade gracefully (if designed to)
Team scaling Merge conflicts and coordination with many teams Clear ownership boundaries

The main reason to adopt microservices is organisational: letting many teams work and deploy independently. The technical costs are real, which is why "start with a well-structured monolith, extract services when a boundary is clear" is the usual advice.

The cost of network calls

Turning a function call into a network call changes its latency and its failure behaviour. If a page needs five services in a chain, their availabilities multiply and their latencies add:

python · try it yourself
from math import prod

def chain(services):
    latency = sum(ms for ms, _ in services.values())
    availability = prod(a for _, a in services.values())
    return latency, availability

in_process = {name: (0.01, 1.0) for name in ["users", "cart", "pricing", "stock", "orders"]}
over_network = {"users": (4, 0.999), "cart": (6, 0.999), "pricing": (5, 0.9995),
                "stock": (8, 0.999), "orders": (7, 0.999)}

for label, services in [("monolith (function calls)", in_process), ("5 chained services", over_network)]:
    ms, a = chain(services)
    print(f"{label:<26} latency {ms:6.2f} ms, availability {a:.3%}")
monolith (function calls)  latency   0.05 ms, availability 100.000%
5 chained services         latency  30.00 ms, availability 99.551%

That is why microservice designs avoid long synchronous chains: call in parallel where possible, cache, and move non-critical work to asynchronous events.

Circuit breakers

When a downstream service is failing, hammering it with retries makes things worse and ties up your own threads. A circuit breaker counts failures; after a threshold it "opens" and fails fast for a cool-down period, then lets one trial request through ("half-open") to see whether the service has recovered.

python · try it yourself
class CircuitBreaker:
    def __init__(self, threshold=3, cooldown=5):
        self.state, self.failures, self.opened_at = "closed", 0, None
        self.threshold, self.cooldown = threshold, cooldown

    def call(self, now, service_ok):
        if self.state == "open":
            if now - self.opened_at < self.cooldown:
                return "fail fast (circuit open)"
            self.state = "half-open"                 # allow one trial request
        if service_ok:
            self.state, self.failures = "closed", 0
            return "ok"
        self.failures += 1
        if self.state == "half-open" or self.failures >= self.threshold:
            self.state, self.opened_at = "open", now
        return "error"

cb = CircuitBreaker()
service_up = lambda t: t < 2 or t >= 10          # the service is down from t=2 to t=9
for t in range(16):
    result = cb.call(t, service_up(t))
    print(f"t={t:2} service {'up  ' if service_up(t) else 'DOWN'} -> {result:<26} state={cb.state}")
t= 0 service up   -> ok                         state=closed
t= 1 service up   -> ok                         state=closed
t= 2 service DOWN -> error                      state=closed
t= 3 service DOWN -> error                      state=closed
t= 4 service DOWN -> error                      state=open
t= 5 service DOWN -> fail fast (circuit open)   state=open
t= 6 service DOWN -> fail fast (circuit open)   state=open
t= 7 service DOWN -> fail fast (circuit open)   state=open
t= 8 service DOWN -> fail fast (circuit open)   state=open
t= 9 service DOWN -> error                      state=open
t=10 service up   -> fail fast (circuit open)   state=open
t=11 service up   -> fail fast (circuit open)   state=open
t=12 service up   -> fail fast (circuit open)   state=open
t=13 service up   -> fail fast (circuit open)   state=open
t=14 service up   -> ok                         state=closed
t=15 service up   -> ok                         state=closed

After three errors the breaker opens at t=4. At t=9 the cool-down is over and one trial request goes through, but the service is still down, so the breaker opens again. The trial at t=14 succeeds and closes it. While the circuit is open, callers get an instant error (or a fallback such as cached data) instead of waiting for timeouts, and the struggling service gets breathing room.

Finding service boundaries

Good boundaries follow the business, not the technical layers. Domain-driven design calls them bounded contexts: areas with their own language and data (Catalogue, Ordering, Billing, Shipping). A useful test is to count how often modules call each other: split where coupling is low.

python · try it yourself
calls = {   # calls per request between modules, measured in the monolith
    ("orders", "billing"): 1, ("orders", "cart"): 9, ("cart", "pricing"): 14,
    ("orders", "shipping"): 1, ("pricing", "catalog"): 11, ("cart", "catalog"): 6,
    ("billing", "users"): 1, ("shipping", "users"): 1,
}

proposal = {"commerce": {"orders", "cart", "pricing", "catalog"},
            "billing": {"billing"}, "shipping": {"shipping"}, "identity": {"users"}}
service_of = {m: s for s, members in proposal.items() for m in members}

internal = sum(n for (a, b), n in calls.items() if service_of[a] == service_of[b])
remote = sum(n for (a, b), n in calls.items() if service_of[a] != service_of[b])
print(f"calls inside services: {internal}, network calls between services: {remote}")
for (a, b), n in sorted(calls.items()):
    if service_of[a] != service_of[b]:
        print(f"  {service_of[a]} -> {service_of[b]}: {n}/request")
calls inside services: 40, network calls between services: 4
  billing -> identity: 1/request
  commerce -> billing: 1/request
  commerce -> shipping: 1/request
  shipping -> identity: 1/request

Splitting cart and pricing into separate services would have turned 14 function calls per request into 14 network calls. Keeping chatty modules together and splitting where there are 1 or 2 calls keeps the network overhead small.

Warning signs

  • Distributed monolith: services that must be deployed together or share one database. You pay the microservice costs and get none of the benefits.
  • Nano-services: one function per service; the network overhead dominates.
  • Shared database: two services writing the same tables are coupled through the schema. Each service should own its data and expose it through an API or events.

Tip: A modular monolith (one deployable, strictly separated modules with their own schemas and interfaces) gets many benefits of microservices and makes a later split easy.

Test yourself

What is usually the strongest reason to adopt microservices?

  1. Lower latency
  2. Letting many teams develop and deploy independently
  3. Simpler transactions
  4. Less infrastructure

What does an open circuit breaker do?

  1. Retries the request faster
  2. Fails calls immediately for a cool-down period instead of calling the failing service
  3. Restarts the downstream service
  4. Routes calls to a random service

Two services read and write the same database tables. What is this an example of?

  1. A bounded context
  2. A distributed monolith / tight coupling
  3. Event sourcing
  4. A circuit breaker