Microservices or monolith
easy 28 minA monolith is one program, built and released as a whole.
Video lesson · Chapter 1 of 5
One order in one building
One workshop or a lane of huts, in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A monolith is an application that is built, tested and released as one unit. Its parts, such as users, orders, payments and stock, call each other inside one process and usually share one database.
Microservices split the same application into a set of small services. Each runs in its own process, is released on its own, owns its data, and talks to the others through HTTP, RPC or messages.
Between them lies the modular monolith: still one program, but with clear modules that may only use each other through a public interface. It gives many of the benefits of good boundaries without the network.
Why it exists
As a program and its team grow, a single release becomes a meeting point: everybody waits for everybody. Splitting lets a team change and release its part without asking the others.
Parts also differ. One needs many machines, another needs few; one must never fail, another may. Separate services can be scaled, protected and even written differently.
But the split turns function calls into network calls and one transaction into several. So the question is never which style is better. It is whether your organisation and load already need what the split gives.
A short history
1968
Melvin Conway's article How Do Committees Invent? appears in Datamation in April. Its thesis: a system's design copies the communication structure of the organisation that made it.
1998
Senior engineers at Amazon write the Distributed Computing Manifesto, dated 24 May. It proposes moving from applications that access the database directly to services.
2004
On 29 June Martin Fowler describes the strangler application: growing a new system around the old one until the old one can go.
2011
In May a workshop of software architects near Venice discusses the term microservice.
2014
On 25 March James Lewis and Martin Fowler publish the article Microservices, which lists the common characteristics.
2015
On 3 June Fowler publishes Monolith First: almost all the successful microservice stories Fowler had heard of began with a monolith that grew too big.
Words to know
- Monolith
- One deployable unit that holds all parts of the application.
- Modular monolith
- A monolith whose modules use each other only through public interfaces.
- Microservice
- A small service that is released on its own and owns its data.
- Bounded context
- A part of the business in which words have one meaning. A good place for a boundary.
- Distributed monolith
- Services that must be released together: the cost of both styles, the benefit of neither.
- Strangler fig
- Replacing an old system piece by piece behind a facade.
- Polyglot
- Using different languages or databases for different services.
How it works
Step through the idea, or press Play.
One unit. Build, test and release together
Understand it
Start here
One workshop or a lane of huts
Four craftspeople make pots, baskets, candles and toys. They may share one big workshop, or work in a lane of small huts. Neither choice is wrong. Watch what becomes easy and what becomes hard.
A restaurant with one kitchen against a food court shows the same: a fire in one stall does not close the court, but every stall pays for its own oven.
The first style
The monolith on its own
Inside, a typical monolith has layers: the interface, the business logic, the data access, and below them one database. One unit does not mean one machine. You can run many copies behind a load balancer.
One program, two copies, one database
What a monolith makes easy
- Simple development: one codebase, easy to follow
- End-to-end tests in one place
- One artifact to release
- The editor can jump to any code
- Calls inside the process are fast
- One transaction can cover several modules
What becomes hard
- Every copy carries all modules, also the idle ones
- A bad release or a leak touches everything
- One main framework and runtime for all
- A small change releases the whole
- Many teams must coordinate one release
A monolith fits when
A start-up
First versions and early products change direction often.
A small team
Two to ten people can talk to each other.
A simple application
The domain has few separate parts.
A small budget
Fewer moving parts cost less to operate.
Little time
The first version must ship soon.
You are still learning
Boundaries drawn before you know the domain are often wrong.
The second style
Microservices on their own
Four services, four databases
Six principles
| Principle | Meaning |
|---|---|
| Single responsibility | A service does one business job well |
| Loose coupling | It can change without changing the others |
| Own data | Only it touches its database: see database per service |
| Independent release | It goes live without a common release |
| Failure isolation | Its failure is contained, with timeouts and fallbacks |
| Technology freedom | It may use the tool that suits its job |
An order in microservices
Calls (REST, gRPC) give an answer at once and couple the two sides in time. Events through a queue or a broker let the sender continue. Choosing between them is the subject of microservice communication.
What you must also run
| Part | Its job | Examples |
|---|---|---|
| API gateway | One entrance: see API gateway | Kong, Amazon API Gateway |
| Service discovery | Find running copies | Consul, Eureka |
| Load balancer | Share requests | NGINX, HAProxy |
| Metrics | Numbers and alerts | Prometheus, Grafana |
| Central logs | One place to search | Elastic stack, Splunk |
| Tracing | Follow one request | Jaeger, Zipkin |
| Containers | Package and place services | Docker, Kubernetes |
| Message broker | Carry events | Kafka, RabbitMQ |
Compare
Head to head
| Question | Monolith | Microservices |
|---|---|---|
| Speed at the start | Fast | Slower: a platform comes first |
| Speed with many teams | Slows down, unless well modularised | Teams work in parallel |
| Release | All at once | Each on its own |
| Scaling | Bigger machines, or more copies of the whole | More copies of one service |
| Technology | Mostly one stack | May differ by service |
| Tests | End to end is simple | Contract tests and integration tests |
| Debugging | One stack trace | Distributed tracing |
| Consistency | One ACID transaction | Mostly eventual, with sagas |
| Operating cost | Lower | Higher |
| Teams | Coordinated | Autonomous |
| A call | In the process | Over the network, and it can fail |
Scaling
Must you scale everything?
Suppose orders need ten times the capacity. With a monolith you add copies of the whole. Any copy can serve any request, so the processors are not wasted. What you pay for is the memory and the database connections of modules that are idle in each copy.
Memory for ten times the orders
Failure
Isolation, and its opposite
Five services in one chain
So microservices do not raise availability by themselves. They raise it when a page still works without the failed part: payment is down, and the order is accepted and charged later. That needs timeouts, a circuit breaker and a decision about what to do instead.
Does a failure stay small?
People
Teams decide more than load
Pairs who may need to talk
Cost of change as the team grows
Amazon's two-pizza team, a team that two pizzas can feed, is a common size for an owner. The 2014 article reports teams of up to a dozen per service at the large end, and half a dozen people looking after half a dozen services at the small end. More services than that and people spend their time on operations.
Decide
Choose with reasons
Stay with a monolith when
- Fewer than about ten developers
- A simple domain or a first version
- You need to ship quickly
- Little experience with operations
- A tight budget
Split when
- More than about twenty developers block each other
- A complex domain with clear boundaries
- Parts need to scale very differently
- A platform team exists
- Parts really need different technology
A decision in five questions
In between
The modular monolith
Keep one program. Give each module its own folder, its own tables and a public interface, and let a tool refuse everything else. You can split later, because the boundary is already there.
ALLOWED = { "orders": {"users.api", "payments.api"}, "payments": set(), "users": set(),}def violations(imports): """imports: list of (module, imported name).""" out = [] for module, name in imports: owner = name.split(".")[0] if owner != module and name not in ALLOWED[module]: out.append(f"{module} must not use {name}") return outprint(violations([ ("orders", "payments.api"), # fine: public interface ("orders", "orders.tables"), # fine: its own ("payments", "orders.tables"), # not fine]))Moving
From one to many, step by step
The strangler fig is a plant that grows around a tree until the tree can go. In software: put a facade in front, take out one piece, send a little traffic to it, then more, then remove the old code.
The strangler fig in four phases
Six steps in practice
- 1
Identify bounded contexts
Use domain-driven design: where do words change their meaning?
- 2
Start at the edge
Take a loosely coupled, less critical module first.
- 3
Decide about the data
Either share the tables for a short, dated time or move them at once. A new service that keeps sharing is not independent.
- 4
Add observability, then security and traffic rules
Metrics, logs and traces before the second service. A service mesh can help later, but is not a requirement.
- 5
Shift traffic gradually
Use a feature flag: 1%, 10%, 50%, 100%, with a way back at each step.
- 6
Retire the old code
Delete it once the service is stable, or you will maintain both.
Traps on the way
Big bang
Converting everything at once. Nothing is finished for a long time.
Distributed monolith
Services that must be released together. Join them again or fix the contract.
Shared tables
Several services use the same tables, so no schema can change.
No observability
Moving without metrics and traces is moving blind.
Habits
Do and avoid
Do
- Design around business capabilities
- Keep services focused
- Use events where the answer is not needed now
- Use circuit breakers and timeouts
- Own your data
Avoid
- Nano-services: too small to be worth a deployment
- Shared databases
- Long synchronous chains
- Releasing services together
- Pretending the network is reliable
In an interview
Interviewer
You have a small shop and five developers. Microservices?
You
No. One modular monolith with two copies behind a load balancer and one database. Orders, stock and payments are modules with public interfaces and separate tables, so I keep the option to split.
Interviewer
Two years later there are 60 developers.
You
Then I look for the pain. If releases queue up because of search changes, I extract search first: it has its own load, it can be a little behind, and the shop still works without it. A facade routes a small share of traffic to it. I would not split payments and orders first, because they share a transaction today.
Summary
The whole topic in one minute.
A monolith keeps calls fast, transactions simple and debugging in one place. Microservices give independent release, independent scaling and walls between failures, and they charge for it with network calls, eventual consistency and a platform to run.
Start with a modular monolith. Split a part out when you can name the reason: teams block each other, one part has a very different load, or one part needs its own safety. Move with a facade, one service at a time, and give each service its own data.
- A monolith is one unit of release, not one machine.
- Microservices buy independent release and scale with network calls, eventual consistency and a platform.
- Start modular. Split when you can name the reason.
- Five services in a chain at 99.9% are about 99.5% together.
- Move with a facade, one service at a time, each with its own data.
Sources
- Lewis and Fowler: Microservices (2014)
- Martin Fowler: Monolith First
- Martin Fowler: Original Strangler Fig Application
- Melvin Conway: How Do Committees Invent?
- Werner Vogels: Monoliths are not dinosaurs
- Shopify: Deconstructing the Monolith
- GitHub: Building GitHub with Ruby and Rails
- Segment: Goodbye Microservices