---
title: Microservices vs Monolith: When to Use Which, With Code
url: https://www.masaischool.com/resources/microservices-vs-monolith-explained
description: Microservices vs monolith: a decision table, why a modular monolith is the honest default, the cost of network calls and a runnable retry example.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# Microservices vs monolith: when to use which

> **Short answer**
>
> **A monolith** is one application deployed as a single unit; microservices split it into small services, each deployed on its own and talking over the network. Start with a monolith, kept modular. Move to microservices only when independent teams or scaling needs justify the extra cost of network failures, data consistency and monitoring.

This page is for students heading into system design rounds and for first-job developers whose team "wants microservices". It gives a decision table you can use in a design discussion, then shows the main hidden cost with code you can run: a call over the network that fails, and the retry that makes it worse before it makes it better.

Opinions here follow Martin Fowler's [microservices article](https://martinfowler.com/articles/microservices.html), his [Monolith First](https://martinfowler.com/bliki/MonolithFirst.html) note (3 June 2015) and [Microservice Premium](https://martinfowler.com/bliki/MicroservicePremium.html), all opened on 1 December 2026. They are an argued position from experienced engineers, not a measurement.

1. **Monolith** - one codebase, one deploy
2. **Modular monolith** - same deploy, strict internal boundaries
3. **Extract one service** - only where there is a proven reason
4. **Microservices** - many services, many deploys, a platform to run them
The usual path. Many successful systems stop at step two.

## Microservices vs monolith: the decision table

Use a monolith unless you can name the specific problem microservices would solve. A monolith is one deployable application. Microservices are many small, independently deployable services, each owning its data and talking to the others over the network, usually through [REST APIs](https://www.masaischool.com/resources/rest-api-explained) or message queues.

| Question | Monolith | Microservices |
|---|---|---|
| Team size | One team up to a few teams | Many teams that block each other in one codebase |
| Deploying | One deploy; a bug anywhere ships together | Each service deploys alone; many pipelines to maintain |
| Scaling | Scale the whole app together | Scale only the hot service |
| Data | One database, joins and transactions are easy | One database per service; no joins, consistency is your job |
| Failure | In-process calls rarely fail | Every call can time out; partial failure is normal |
| Debugging | One stack trace, one log | A request crosses services; you need tracing |
| Tech choice | One language and framework | Different stacks per service, at the price of more to know |
| Early product | Fast to change; boundaries can move | Boundaries guessed too early are costly to move |
| Ops effort | Low: one app, one database | High: containers, orchestration, service discovery, monitoring |

Score yourself: if you have fewer than roughly ten developers, one product and no proven scaling hotspot, the left column wins. That threshold is a rule of thumb, not a published figure. The right column starts to pay off when separate teams must release on their own schedules, or one component has a very different load profile from the rest.

## The modular monolith is the honest default

Fowler observes that almost all the successful microservice stories he has heard started as a monolith that grew too big, and that systems built as microservices from scratch ended up in serious trouble. His argument is that microservices carry a "premium", the cost of managing a suite of services, which only complex systems earn back. His advice is to build a new application as a monolith first, even if you expect to split it later.

A modular monolith keeps one deployment but enforces boundaries inside it. Each module has a small public interface, owns its tables and never reaches into another module's internals. Done properly, extracting a module into a service later is a matter of replacing an in-process call with a network call, because the seams are already there.shop/ main.py one process, one deploy orders/ service.py api.py models.py payments/ service.py api.py models.py catalog/ service.py api.py models.py # rule: orders may call payments.service, never payments.models # rule: each module owns its own tables; no cross-module joins

- Enforce the rules with a linter or import checker in your pipeline, not with goodwill. See [CI/CD pipeline explained](https://www.masaischool.com/resources/ci-cd-pipeline-explained).
- Keep module data private: no foreign keys or joins across modules. That is the hardest rule and the one that makes extraction possible.
- Talk between modules through a service function or an event, never through another module's tables.
- Review the boundaries every quarter. Moving a line between modules is cheap now and expensive after a split.

## The cost of distribution: network, data and observability

### 1. The network fails in ways functions do not

A function call either returns or raises. A network call can also hang, return late, or do the work and lose the reply. The demo below simulates a payment service. Case 1 shows retry with exponential backoff and jitter (random waiting so thousands of clients do not retry in lockstep). Case 2 shows the trap: the reply is lost after the charge happened, the client retries, and the customer is charged three times. Case 3 fixes it with an idempotency key the server remembers. The delays are printed, not slept, so it runs instantly. Python 3.9.6, seeded, so your output matches.import random class Timeout(Exception): pass class PaymentService: """Pretend remote service. The first `fail_times` calls time out. A timeout can happen AFTER the work was done (the reply got lost).""" def __init__(self, fail_times, work_done_before_timeout=False): self.calls = 0 self.fail_times = fail_times self.lost_reply = work_done_before_timeout self.charges = [] # what actually happened on the server self.seen_keys = set() def charge(self, order_id, amount, key=None): self.calls += 1 duplicate = key is not None and key in self.seen_keys if not duplicate: if self.calls <= self.fail_times and not self.lost_reply: raise Timeout("no response") self.charges.append((order_id, amount)) if key is not None: self.seen_keys.add(key) if self.calls <= self.fail_times: raise Timeout("reply lost") return "charged" def call_with_retry(fn, attempts=4, base=0.1, cap=2.0, rng=None): rng = rng or random.Random(7) for n in range(1, attempts + 1): try: return fn() except Timeout as e: if n == attempts: print(f" attempt {n}: {e}; giving up") raise delay = rng.uniform(0, min(cap, base * 2 ** n)) # exponential backoff with full jitter print(f" attempt {n}: {e}; wait {delay:.2f}s then retry") print("1) Service is down for 2 calls, then recovers") svc = PaymentService(fail_times=2) print(" result:", call_with_retry(lambda: svc.charge("A1", 499)), "| server charges:", svc.charges) print("2) Reply is lost after the work was done, retry without an idempotency key") svc = PaymentService(fail_times=2, work_done_before_timeout=True) call_with_retry(lambda: svc.charge("B1", 499)) print(" server charges:", svc.charges) print("3) Same failure, but the client sends the same idempotency key each time") svc = PaymentService(fail_times=2, work_done_before_timeout=True) call_with_retry(lambda: svc.charge("C1", 499, key="order-C1")) print(" server charges:", svc.charges) print("4) Service never recovers") svc = PaymentService(fail_times=99) try: call_with_retry(lambda: svc.charge("D1", 499)) except Timeout: print(" caller must now fail the order or queue it; calls made:", svc.calls)

Output as printed on 1 December 2026:1) Service is down for 2 calls, then recovers attempt 1: no response; wait 0.06s then retry attempt 2: no response; wait 0.06s then retry result: charged | server charges: [('A1', 499)] 2) Reply is lost after the work was done, retry without an idempotency key attempt 1: reply lost; wait 0.06s then retry attempt 2: reply lost; wait 0.06s then retry server charges: [('B1', 499), ('B1', 499), ('B1', 499)] 3) Same failure, but the client sends the same idempotency key each time attempt 1: reply lost; wait 0.06s then retry attempt 2: reply lost; wait 0.06s then retry server charges: [('C1', 499)] 4) Service never recovers attempt 1: no response; wait 0.06s then retry attempt 2: no response; wait 0.06s then retry attempt 3: no response; wait 0.52s then retry attempt 4: no response; giving up caller must now fail the order or queue it; calls made: 4

Case 4 is the one design reviews skip: after the last retry, the caller still has to decide what to do. That means timeouts, a fallback, a queue or a clear error. Retrying forever across many services is a known way a small slowdown becomes an outage; see Google's [cascading failures chapter](https://sre.google/sre-book/addressing-cascading-failures/) and the AWS Builders' Library on [timeouts, retries and backoff with jitter](https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/).

### 2. Data consistency

In a monolith, one database transaction can create an order, reduce stock and record a payment, all or nothing. Once those are three services with three databases, there is no single transaction. You get eventual consistency: designs such as sagas, where each step has a compensating undo, and events with retries. You must also decide what the user sees while the steps are in flight. This is the cost students underestimate most.

### 3. Observability

One user click now crosses several processes. You need a correlation id passed in every call, structured logs in one searchable place, metrics per service, and distributed tracing to see where a request spent its time. Without these, an outage becomes a guessing game across five dashboards. Budget for them before the first split, not after.

## Migration steps if you really need to split

1. **Name the pain.** Write one sentence: "Team X cannot release because of team Y" or "search needs 20 times the capacity of everything else". No sentence, no migration.
2. **Make it modular first.** Put the candidate behind an interface and remove cross-module joins inside the monolith.
3. **Build the platform basics.** CI/CD per service, containers ([Docker for beginners](https://www.masaischool.com/resources/docker-for-beginners-explained)), centralised logs, metrics, tracing, health checks.
4. **Extract the edge first.** Choose a module with few dependencies and clear data ownership: notifications, search, file processing. Avoid starting with the core domain.
5. **Route gradually.** Put a gateway or proxy in front and send a small share of traffic to the new service, then widen. This is the canary idea from the [deploy strategies](https://www.masaischool.com/resources/ci-cd-pipeline-explained) section.
6. **Move the data.** Copy, dual-write or sync until the service owns its table, then remove the monolith's access. Plan the rollback.
7. **Delete the old code.** A migration that leaves both copies alive doubles the maintenance. Repeat for the next module only after this one is stable.

If you are preparing for interviews, the same trade-offs appear in [system design interview preparation](https://www.masaischool.com/resources/system-design-interview-preparation). A good answer names the team and scaling reason, proposes a modular monolith first, and states the three costs above. For the wider picture of where backends sit, see the [backend developer roadmap](https://www.masaischool.com/resources/backend-developer-roadmap) and the [software development learning path](https://www.masaischool.com/resources/software-development).

## Frequently asked questions

### What is the difference between a monolith and microservices?

A monolith is a single application built and deployed as one unit, with one codebase and usually one database. Microservices split the same system into small services that are deployed independently, own their data and communicate over the network. The monolith is simpler to run; microservices let separate teams ship and scale separately.

### When should you use microservices?

When the monolith blocks you: many teams stepping on each other, one component needing very different scaling, or a part needing to release on its own schedule. You also need CI/CD, monitoring and on-call practice in place. If you cannot name the problem, a modular monolith is the better choice.

### What is a modular monolith?

A single deployable application divided into modules with strict boundaries: each exposes a small interface, owns its data and does not reach into others. It keeps the simplicity of one deploy while making a later extraction into services much easier. Many teams stay at this stage permanently, and that is fine.

### Are microservices faster than a monolith?

Not by default. An in-process function call is far quicker than a network call, so a request that crosses several services is usually slower. Microservices help you scale a hot component independently and deploy teams separately; they are an organisation and scaling tool, not a speed-up.

### What are the disadvantages of microservices?

Network calls can fail or be slow, so you need timeouts, retries and idempotency. Data is split across databases, so consistency becomes your job. Debugging needs tracing and central logs. There is also more infrastructure and more pipelines to maintain. Fowler calls this the microservice premium.

### How do I answer microservices vs monolith in an interview?

Do not pick a side first. Ask about team size, load and release needs. Recommend starting with a modular monolith, say what would make you split (independent teams, uneven scaling), then name the costs: network failure, eventual consistency and observability. Mention extracting one service at a time.
