AlgoViz

Microservices or monolith

easy 28 min

A monolith is one program, built and released as a whole.

Video lesson · Chapter 1 of 5

One order in one building

0:00 / 4:02

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

  1. 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.

  2. 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.

  3. 2004

    On 29 June Martin Fowler describes the strangler application: growing a new system around the old one until the old one can go.

  4. 2011

    In May a workshop of software architects near Venice discusses the term microservice.

  5. 2014

    On 25 March James Lewis and Martin Fowler publish the article Microservices, which lists the common characteristics.

  6. 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.

Step 1 of 3

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.

Workshop and lane
PotsBasketsCandlesToysOne workshop

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

Users send requests to a load balancer. It sends them to two copies of one application. Each copy contains the user, order, payment and stock modules. Both copies use one database.
Every copy holds all modules. If one copy crashes, the other continues.

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

Users call an API gateway. The gateway calls a user service, an order service and a payment service, each with its own database. The order service publishes events to a message broker, from which the stock service, with its own database, reads.
Solid blue arrows are calls. Dashed orange arrows are events. Each service alone touches its database.

Six principles

PrincipleMeaning
Single responsibilityA service does one business job well
Loose couplingIt can change without changing the others
Own dataOnly it touches its database: see database per service
Independent releaseIt goes live without a common release
Failure isolationIts failure is contained, with timeouts and fallbacks
Technology freedomIt may use the tool that suits its job
Isolation does not come for free. If every request needs all services, one that is slow stops them all.

An order in microservices

A call when the answer is needed now; an event when the work may follow. Both are explained in microservice communication.

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

PartIts jobExamples
API gatewayOne entrance: see API gatewayKong, Amazon API Gateway
Service discoveryFind running copiesConsul, Eureka
Load balancerShare requestsNGINX, HAProxy
MetricsNumbers and alertsPrometheus, Grafana
Central logsOne place to searchElastic stack, Splunk
TracingFollow one requestJaeger, Zipkin
ContainersPackage and place servicesDocker, Kubernetes
Message brokerCarry eventsKafka, RabbitMQ

Compare

Head to head

QuestionMonolithMicroservices
Speed at the startFastSlower: a platform comes first
Speed with many teamsSlows down, unless well modularisedTeams work in parallel
ReleaseAll at onceEach on its own
ScalingBigger machines, or more copies of the wholeMore copies of one service
TechnologyMostly one stackMay differ by service
TestsEnd to end is simpleContract tests and integration tests
DebuggingOne stack traceDistributed tracing
ConsistencyOne ACID transactionMostly eventual, with sagas
Operating costLowerHigher
TeamsCoordinatedAutonomous
A callIn the processOver 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

10×2 GB=20 GB10×0.5+3×2×0.5=8 GB10 \times 2\,\text{GB} = 20\,\text{GB} \qquad 10 \times 0.5 + 3 \times 2 \times 0.5 = 8\,\text{GB}
Assumed sizes: the whole program needs 2 GB, one service needs 0.5 GB. Ten order copies, and two copies of each of the other three services. The sidecars, gateways and extra databases of the split are not counted.

Failure

Isolation, and its opposite

Five services in one chain

0.9995≈0.995043,200 min×0.0050≈216 min a month0.999^5 \approx 0.9950 \qquad 43{,}200 \text{ min} \times 0.0050 \approx 216 \text{ min a month}
Each is up 99.9% of the time, which allows 43 minutes a month. If a request needs all five, and they fail independently, the request path is down about five times as long.

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

n(n−1)2:n=8⇒28n=50⇒1,225\frac{n(n-1)}{2}: \quad n = 8 \Rightarrow 28 \qquad n = 50 \Rightarrow 1{,}225
Eight people manage one codebase by talking. Fifty do not. Boundaries with owners replace conversations with contracts.

Cost of change as the team grows

Microservices start with a higher fixed cost and grow more slowly. Rules of thumb put the crossover between 10 and 50 engineers, but no measurement fits every organisation.

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

Every path that lacks a reason ends at the modular monolith.

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.

Python
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]))
A boundary check that can run in every build
Edit and run it in your browser

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. 1

    Identify bounded contexts

    Use domain-driven design: where do words change their meaning?

  2. 2

    Start at the edge

    Take a loosely coupled, less critical module first.

  3. 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. 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. 5

    Shift traffic gradually

    Use a feature flag: 1%, 10%, 50%, 100%, with a way back at each step.

  6. 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

  1. Interviewer

    You have a small shop and five developers. Microservices?

  2. 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.

  3. Interviewer

    Two years later there are 60 developers.

  4. 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