Skip to content

15 min read

Monolith vs microservices: when to split

In one sentence: A monolith is an application in a single codebase that is deployed all at once; microservices spread it across several programs that talk over the network. Splitting helps many teams work separately, but every call now travels over the network, transactions don’t cross services and there are more pieces to watch: that’s why almost everything starts as a monolith, and the shop stays one.

What you will learn

  • Explain what a monolith and microservices are, without caricatures.
  • Measure on your computer how much more a network call costs than a function call.
  • List what splitting costs and recognize when it’s worth it, with Conway’s law.
  • Organize a monolith inside, into modules with boundaries, so you can split it if the day comes.

Before you start, read: 01-queues.md 03-scaling.md

Imagine the shop is doing well and there are now three of you programming. Someone reads that “serious companies use microservices” and proposes splitting it: a products service, an orders service, an accounts service and an emails service, each with its own database.

A month later, Carmen pays for an order and the confirmation email never arrives: the emails service asked the accounts service for her email address, and the accounts service was in the middle of a deployment. What used to be a query to a table is now a request over the network, and it can fail.

Splitting has real advantages, and a price. Here you’ll see both, measure the price and understand why the shop is still a single program.

The analogy

Think of a restaurant kitchen with everyone in the same room. The dessert cook asks the cook next to them for the cream and has it in a second. If a menu comes out wrong, it’s redone in full, everyone together.

Now spread the kitchen across four places in the neighborhood that send each other things by courier. Each place changes its menu whenever it wants and has its own team. But every bit of cream takes a trip, the courier sometimes doesn’t come back, and if the meat comes out wrong, the dessert has already been made in another place.

Where the analogy breaks down

  • In the kitchen, a shout can get lost. In a program, a function call is never lost: either it finishes, or the whole program fails.
  • When the courier doesn’t come back, at least you notice. On the network, you sometimes can’t tell whether the order arrived and was carried out, or never arrived.

A MonolithA whole application in a single program that is deployed as one unit: orders, users and emails live in the same codebase and are released together. It is the simplest to build and understand, and almost always the best starting point.Go to definition is a whole application in a single codebase that is deployed all at once. The shop is one: products, orders, accounts, notifications and emails live in src/, ship in a single Docker image with a single deploy.sh and use a single database.

Monolith doesn’t mean messy or “a single copy”. The shop already runs as two copies, since lessons 3 and 4, and with two kinds of processes.

In lesson 1 the shop gained a WorkerA program that does not answer user requests: it keeps taking tasks from a queue and running them. It can be the same code as your server, started with a different command.Go to definition: the process that takes jobs from the queue and sends the notifications and the emails. See how Compose starts it:

compose.yaml
# The worker (Phase 9, lesson 1): the same image as the API, with another command. It doesn't
# listen on any port: it takes the jobs from the Redis queue and does them. The same configuration
# as the API, because it uses the same things: the database, Redis and the mail server. Also
# CACHE_URL: it is the same code, and if a job ever changed a product, it would delete its entry
# from the cache.
# docker compose stop worker the jobs wait in the queue
# docker compose start worker and they go out
worker:
build: .
command: ['node', 'scripts/worker.ts']
env_file: .env
environment:
DATABASE_URL: postgres://shop:${POSTGRES_PASSWORD}@db:5432/shop
REDIS_URL: redis://redis:6379
CACHE_URL: redis://cache:6379
SMTP_URL: smtp://mailpit:1025
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
migrate:
condition: service_completed_successfully
# The image's HEALTHCHECK asks /health, and the worker has none: it isn't a server. Its own
# instead: while it takes jobs, the worker writes to /tmp/heartbeat every 5 seconds
# (src/heartbeat.ts), and it's healthy if the file is less than 30 seconds old. Hung, or
# shutting down, it stops writing. In its first 10 seconds (start_period), Docker asks every
# second (start_interval): it's healthy almost as soon as it starts.
healthcheck:
test:
[
'CMD',
'node',
'-e',
"process.exit(Date.now() - require('node:fs').statSync('/tmp/heartbeat').mtimeMs < 30000 ? 0 : 1)",
]
interval: 10s
timeout: 3s
retries: 3
start_period: 10s
start_interval: 1s
  • build: .: the same image as the API.
  • command: only the start command changes, scripts/worker.ts instead of src/server.ts (outside Docker, npm run worker instead of npm start).
  • No ports, and no health check: it doesn’t listen for requests.
  • The same configuration: the same database, the same Redis, the same cache and the same mail server.

With that, the shop already has something of what you look for when splitting: the worker fails and scales on its own. In lesson 1 you stopped it and the API kept taking payments. But it’s the same code, the same version and the same deployment: it’s still a monolith.

Microservices: several programs that talk over the network

Section titled “Microservices: several programs that talk over the network”

MicroservicesAn application split into several small, independent programs, each with its own job and often its own database, talking to each other over the network. Each can be changed and scaled separately, at the cost of more pieces that can fail and need watching.Go to definition spread the application across several small programs, each with its own code, its own deployment and, almost always, its own database, which the others don’t touch. If the emails service needs Carmen’s email address, it doesn’t read the users table: it asks the accounts service, over HTTP or with gRPCA way for two programs to talk in which one calls a function of the other as if it were in its own code. The data travels in Protobuf over HTTP/2, and a .proto file describes the functions and their data. It’s used mostly between the services of a single company. Google created it.Go to definition, the way to call a function of another service that you saw in Phase 4.

  1. Worker → Emails servicesend the confirmation for order 21
  2. Emails service → Accounts serviceGET /users/… (Carmen's account)
  3. Accounts service → Accounts DBSELECT email FROM users WHERE id = …
  4. Accounts DB → Accounts servicecarmen@example.com
  5. Accounts service → Emails service200 and the email
  6. Emails service → Workeremail sent

In today’s shop, all of that is one query from sendConfirmation, in src/email.ts, to the users table. Two arrows in the diagram are network calls that didn’t exist before.

What you gain by splitting:

  • Each team deploys its own part whenever it wants, without waiting for the others.
  • Each service scales on its own: ten copies of the one that works the most, one of the one that hardly works.
  • Each one can use another tool: Python for an AI model, Node for everything else.
  • A failure stays inside, if it’s done well: if recommendations go down, people can still buy.

What it costs: every call travels over the network

Section titled “What it costs: every call travels over the network”

Calling a function costs a fraction of a microsecond. Calling another program over the network, even on the same computer, costs on the order of a millisecond: thousands of times more. You’ll measure it in “Try it”.

And that’s the best case: between two machines the network’s RTTRTT stands for round-trip time.The round-trip time between two computers. Every handshake costs at least one RTT, so with a faraway server everything starts later.Go to definition is added, and between two cities, much more, as you saw in Phase 0.

The network also brings things a function doesn’t have:

  • It can fail or take forever. Every call needs a maximum wait time, and a plan for when it runs out.
  • Sometimes you don’t know what happened. Like nginx’s 504 in Phase 8, the other side may or may not have done it. Retrying is safe only if the operation is IdempotentSaid of an operation that leaves things in the same state whether you do it once or ten times. In HTTP, GET, PUT and DELETE are idempotent and POST isn’t, so repeating a POST can create two orders.Go to definition, or carries an id to discard the repeats.
  • Calls in a loop add up. It’s Phase 5’s N+1 problem, now between services: asking for the email of 100 orders one by one, at a millisecond each, is 100 ms just waiting.

What it costs: a transaction doesn’t cross services

Section titled “What it costs: a transaction doesn’t cross services”

When an order is placed, createOrder takes the stock out and saves the order in a single TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition, as you learned in Phase 5: either both things happen, or neither.

With a stock service and an orders service, each with its own database, there’s no longer a single BEGIN that covers both. If the stock is subtracted and saving the order fails, nobody gives it back on its own: you need a step that compensates on purpose (“give back 1 mug”). A chain of steps, each with its opposite step, is called a saga.

In the meantime, someone can see the stock subtracted with no order: that’s the Eventual consistencyThe guarantee that, if changes stop arriving, all copies of a piece of data will end up with the same value, even though for a while some show the old one. It is accepted in exchange for speed and for continuing to work when the network fails.Go to definition of lesson 6. And making sure a step isn’t lost between two writes is the topic of lesson 7.

What it costs: many pieces to deploy and watch

Section titled “What it costs: many pieces to deploy and watch”

Every service needs its tests, its image, its deployment, its health checks and its logs: the deploy.sh of lesson 4, multiplied by ten.

Also, every service is a client of others. A change in the accounts service has to keep serving the old version of the emails service, because they aren’t deployed at the same time: it’s Phase 4’s API contractAPI stands for Application Programming Interface.What an API promises to whoever uses it: which routes it has, which data each one accepts and what it answers, including when something goes wrong. When it’s written in a format like OpenAPI, programs can read it too and check whether it’s kept.Go to definition and versioning, but between your own programs.

And finding a failure costs more: a purchase goes through several services, and you have to follow its requestId through all of them. That’s what traces are for (the path of a request through all the services), part of Phase 10’s observability.

Monolith Microservices
Talking to another part A function call A network request, which can fail
Changing the data of two parts at once A transaction A saga, with steps that compensate
Deploying One image, one script One per service, and versions that coexist
Finding a failure One program’s logs Following a request through several
Scaling More copies of everything More copies only of what needs it
Teams Everyone in the same code Each with their own part

Conway’s law: the system copies the teams

Section titled “Conway’s law: the system copies the teams”

In 1968, Melvin Conway wrote that an organization that designs a system ends up with a design that copies how the organization communicates. If three teams that hardly talk to each other build something, three pieces will come out, joined exactly where the teams talk.

That’s why microservices are, above all, a way of organizing people: when a hundred people touch the same code, splitting it by teams lets each one deploy at its own pace.

With a small team the opposite happens. As Martin Fowler writes, one or two dozen people talk to each other effortlessly, so, according to Conway, they’ll build a monolith. And that’s fine.

The modular monolith: boundaries inside a single program

Section titled “The modular monolith: boundaries inside a single program”

There’s a middle ground that works very well: the modular monolith. One codebase and one deployment, divided into parts with clear boundaries: orders, accounts, email.

The rules of microservices, without the network:

  • Each part owns its tables. The others neither read nor write them.
  • Things are requested through public functions, like findEmail(id) from the accounts module, instead of with a query to its table.

The shop doesn’t fully follow this: sendConfirmation reads the users table directly. It’s exactly the shortcut that makes it harder to separate something the day it’s needed.

Shopify, one of the largest Ruby on Rails applications that exist (a framework, like Hono, for the Ruby language), with more than a thousand people programming on it, chose this path instead of microservices, and wrote about it in 2019.

Splitting pays off when staying together costs more than the network:

  • Many teams getting in each other’s way in the same code and the same deployment.
  • Very different needs: one part that needs a lot of CPU or a graphics card, and the rest, almost nothing.
  • Another tool: one part that works better in another language.
  • Isolating the delicate: payments, with tougher security rules than the rest.

In 2015, Martin Fowler described in “Monolith First” a pattern he kept seeing: almost all the successful microservice stories started as a monolith that got too big and was split. And almost all the people he knew who started with microservices from scratch ended up in serious trouble.

He gives two reasons. At the beginning you don’t know whether the application will be useful, and what matters is moving fast. And at the beginning you don’t know where the boundaries are: moving something from one service to another costs far more than inside one program.

The shop has one team, a database that fits on one server and a load that two copies can handle. It will stay a monolith.

The goal: measure on your computer how much more expensive a network call is than a function call.

In your project, ~/backend-course/phase-3/shop-api, start the shop with docker compose up --build --wait, as in the previous lessons. Then save this program in that same folder, with the name call-vs-network.js:

call-vs-network.js
const N = 1000;
const health = () => ({ status: 'ok' });
// The sum uses every answer, so the engine cannot skip the calls.
let sum = 0;
let t0 = performance.now();
for (let i = 0; i < N; i++) sum += health().status.length;
const call = performance.now() - t0;
t0 = performance.now();
for (let i = 0; i < N; i++) {
const res = await fetch('http://api:3000/health');
sum += (await res.text()).length;
}
const network = performance.now() - t0;
console.log(`${N} calls to a function: ${call.toFixed(3)} ms in total, ${((call / N) * 1000).toFixed(3)} µs per call`);
console.log(`${N} fetch to /health: ${network.toFixed(1)} ms in total, ${(network / N).toFixed(3)} ms per call`);
console.log(`the network call is ${Math.round(network / call)} times slower (checksum ${sum})`);
  • performance.now() gives the milliseconds the program has been running, with decimals: the difference between two readings is how long what’s in between took.
  • The first loop calls health a thousand times, a function that returns the same thing as the /health route. The second asks the API for /health a thousand times with fetch.
  • Careful: the /health route isn’t free. It asks PostgreSQL with a SELECT 1 (Phase 7), so each fetch is two trips: to the API’s container, and from there to the database’s.
  • sum uses every answer: without it, the JavaScript engine could skip calls whose result nobody uses.

A function against the network, a thousand times each

Ventana de terminal
docker run --rm --network shop_default node:26 node --input-type=module --eval "$(cat call-vs-network.js)"

What you will see:

1000 calls to a function: 0.459 ms in total, 0.459 µs per call
1000 fetch to /health: 722.2 ms in total, 0.722 ms per call
the network call is 1575 times slower (checksum 17000)
  • docker run --rm … node:26 starts a Node 26 container and deletes it when it finishes (the first time, Docker downloads the image).
  • --network shop_default puts it on the shop’s Compose network, where the API is called api, as in Phase 7. The fetch goes from one container to another.
  • --eval "$(cat call-vs-network.js)" hands the program to Node, and --input-type=module lets you use await outside a function.

Look at “per call”: 0.459 µs against 0.722 ms. The checksum, 17000, says every call was made: a thousand times the 2 letters of ok and a thousand times the 15 characters of {"status":"ok"}.

If Docker says the network doesn’t exist, the shop isn’t running or your project has another name: in compose.yaml: find the network with docker network ls. If the fetch fails, wait for the API to be healthy.

Your numbers will be different, and they’ll change from one run to the next. We ran it three times in a row, on October 22, 2026, on an Apple M1 Pro with Docker in Colima (4 CPUs and 2 GiB):

Run One function One fetch to /health Times slower
1 0.459 µs 0.722 ms 1,575
2 0.187 µs 0.631 ms 3,368
3 0.229 µs 0.616 ms 2,682

Keep the order of magnitude, not the ratio, which swings between 1,575 and 3,368: a fraction of a microsecond against most of a millisecond. And it’s the most favorable case: the same computer, the shop with no load and fetch reusing the connection.

To be fair, the comparison exaggerates a little: /health queries PostgreSQL and health() doesn’t. But looking up an email is a query in both worlds: what microservices add is the extra trip, which costs less than these two, but still costs far more than a function, even though we haven’t measured it on its own.

Challenge: imagine email becomes a separate service, with its own database. What has to change in sendConfirmation to get Carmen’s email address, and what happens if the accounts service doesn’t answer?Show answer

It can no longer read the users table. It has two paths:

  • Ask the accounts service, with a maximum wait time. If it doesn’t answer, the job fails and the queue retries it, as in lesson 1: five attempts in about 15 seconds. If the accounts service takes longer to come back, the job ends up among the failed ones and the email doesn’t go out, as happened to Carmen in “The problem”.
  • Receive the email inside the job, copied when the order was paid. There’s no need to ask, but if Carmen changes her email just before, the message goes to the old one: a copy can go stale.

When you finish, run docker compose down to stop the shop and delete call-vs-network.js if you don’t want to keep it.

  • “Sign in with Google,” in Phase 6: another company’s service, with its own users. The shop doesn’t read its tables: it asks over the network. Conway in its purest form: two organizations, two systems and a contract.
  • The payment gateway and the delivery company, in Phase 4: outside services that talk to the shop through webhooks, which can fail and repeat.
  • A web page that loads halfway: a box is missing, like the recommendations. Often it’s a separate service that didn’t answer in time, and the page carried on without it.
  • Splitting to make the application respond faster. Every hop between services adds time. Measure first: more copies (lesson 3) or a cache are almost always enough.
  • Services that share the database. A change in a table breaks them all, and they have to be deployed together: a monolith, spread over the network.
  • Treating a network call like a function: no maximum wait time, no retries and assuming it went fine.
  • Splitting by technical layers, like a “database” service and a “logic” service: every change touches both. You split by what the business does: orders, accounts, payments.
  • A monolith is a single codebase deployed all at once, even with several copies and processes, like the shop.
  • Microservices are programs with their own code, deployment and data, which talk over the network.
  • Splitting costs: thousands of times more per call (a fraction of a microsecond against most of a millisecond in our measurement, with a query included), network failures, split transactions and more pieces.
  • Conway’s law: the system copies the organization. Splitting pays off with many teams.
  • Start with a monolith, organized into modules with boundaries.
There are three of you and the shop is slow at peak hours. Someone proposes splitting it into five microservices to make it faster. What do you answer?

In the shop, the API and the worker run in different containers and don’t share a process. Are they two microservices?

You move the stock into a service with its own database. An order subtracts a mug in that service, and then fails to save in the orders service. What happens to the mug?

A company has three teams that hardly talk to each other: web, mobile app and payments. According to Conway’s law, what shape will the system they build together have?

You measured 0.2 µs per function call and 0.7 ms per fetch. A page asks the accounts service for the email of each of its 100 orders, one after another. How much time does that add?

In your monolith, the email code reads the users table directly. You want to be able to separate it someday. Which change best prepares for that day?

phase-9 · lesson 5/7