Monolith vs microservices

Junior Always asked 7 min

On this page

The question

What are the pros and cons of microservices compared with a monolith?

30-second answer

A monolith is one deployable: simple to build, test, debug and run, with fast in-process calls and local transactions. Its cost is coupling: teams share one release, and the whole app scales as one. Microservices let each team deploy, scale and fail independently, and choose its own stack. In exchange, every call crosses the network, data spreads over many databases, and you need automation, monitoring and tracing to run them.

Understand it

Monolith, modular monolith and microservices

Compare

One deployable and one database. Calls are fast method calls, but any module can call or query any other, so coupling grows with every release.

View as text

The same four modules, Orders, Payments, Catalog and Shipping, drawn three ways, with their databases below and four facts under the picture: deployables, calls between parts, data and main cost.

Monolith: One deployable and one database. Calls are fast method calls, but any module can call or query any other, so coupling grows with every release. Deployables: 1. Calls between parts: In-process, any to any. Data: One shared schema. Main cost: Coupling grows unseen.

Modular monolith: Still one deployable, but each module hides its internals behind a public API and owns its tables. A test fails the build when a module reaches past a border. Deployables: 1. Calls between parts: In-process, via module APIs. Data: A schema per module. Main cost: Discipline at the borders.

Microservices: Each service deploys, scales and fails on its own, with its own database. Every call now crosses the network, and data spread over four databases is only eventually consistent. Deployables: 4. Calls between parts: Network: HTTP or events. Data: A database per service. Main cost: Network, ops, consistency.

The same four modules, Orders, Payments, Catalog and Shipping, drawn three ways, with their databases below and four facts under the picture: deployables, calls between parts, data and main cost.

Monolith: One deployable and one database. Calls are fast method calls, but any module can call or query any other, so coupling grows with every release. Deployables: 1. Calls between parts: In-process, any to any. Data: One shared schema. Main cost: Coupling grows unseen.

Modular monolith: Still one deployable, but each module hides its internals behind a public API and owns its tables. A test fails the build when a module reaches past a border. Deployables: 1. Calls between parts: In-process, via module APIs. Data: A schema per module. Main cost: Discipline at the borders.

Microservices: Each service deploys, scales and fails on its own, with its own database. Every call now crosses the network, and data spread over four databases is only eventually consistent. Deployables: 4. Calls between parts: Network: HTTP or events. Data: A database per service. Main cost: Network, ops, consistency.

Takeaway: The same four modules, packaged three ways. A modular monolith gets most of the clarity of microservices without paying for the network; microservices buy independent deploys and scaling with distributed-systems problems.

Which architecture fits this team?

Explore

2 teams, even load, unclear boundaries: monolith. Unclear borders: do not split yet.

2
View as text

A row of team markers, one per team, and three cards: monolith, modular monolith and microservices. The recommended card is highlighted, and a line says why.

1 team, even load, unclear boundaries: monolith. Unclear borders: do not split yet.

4 teams, even load, clear boundaries: modular monolith. One deploy still serves every team.

4 teams, one part scales apart, clear boundaries: microservices. Extract only the hot part, first.

10 teams, even load, clear boundaries: microservices. Teams must deploy without waiting.

10 teams, one part scales apart, unclear boundaries: modular monolith. Unclear borders: do not split yet.

A row of team markers, one per team, and three cards: monolith, modular monolith and microservices. The recommended card is highlighted, and a line says why.

1 team, even load, unclear boundaries: monolith. Unclear borders: do not split yet.

4 teams, even load, clear boundaries: modular monolith. One deploy still serves every team.

4 teams, one part scales apart, clear boundaries: microservices. Extract only the hot part, first.

10 teams, even load, clear boundaries: microservices. Teams must deploy without waiting.

10 teams, one part scales apart, unclear boundaries: modular monolith. Unclear borders: do not split yet.

Takeaway: Architecture follows the organization. Start with one deployable, keep its modules clean, and split a service out when teams block each other or one part must scale on its own.

When is a service worth splitting out?Start from one deployable. If the domain boundaries are unclear, keep one deployable with clean modules. If they are clear, split a module out only when teams block each other's releases or the module needs to scale or fail on its own; otherwise keep the modular monolith.NoYesNoYesStart: onedeployableBoundariesclear?Keep onedeployable,clean the modulesTeams blocked, orscales apart?Modular monolithExtract that moduleas a service
When is a service worth splitting out?Start from one deployable. If the domain boundaries are unclear, keep one deployable with clean modules. If they are clear, split a module out only when teams block each other's releases or the module needs to scale or fail on its own; otherwise keep the modular monolith.NoYesNoYesStart: onedeployableBoundariesclear?Keep onedeployable,clean the modulesTeams blocked, orscales apart?Modular monolithExtract that moduleas a service
When is a service worth splitting out?

In code

// com.shop.payments: the module's public API, the only type other modules may use
package com.shop.payments;

public interface PaymentsApi {
    PaymentResult charge(OrderId order, Money amount);
}

// com.shop.payments.internal: package-private, invisible outside the module
package com.shop.payments.internal;

@Service
class StripePayments implements PaymentsApi {
    private final PaymentRepository payments;   // payments' own tables

    StripePayments(PaymentRepository payments) { this.payments = payments; }

    @Override
    public PaymentResult charge(OrderId order, Money amount) {
        // call the provider, save the payment, return the result
        return PaymentResult.ok(payments.save(new Payment(order, amount)).id());
    }
}
A modular monolith: each module exposes an API and hides the rest
class ModularityTest {
    @Test
    void modulesOnlyUseEachOthersApi() {
        ApplicationModules.of(ShopApplication.class).verify();   // fails on a cycle or a reach into internal
    }
}

@Service
class ShippingOnPayment {
    @ApplicationModuleListener               // runs after the payment's transaction commits
    void on(PaymentCompleted event) {
        // schedule the shipment; payments never calls shipping directly
    }
}
Spring Modulith checks the borders in a test, and modules talk through events
@Service
class CheckoutService {
    private final PaymentRepository paymentRepo;   // payments' internal repository
    private final PaymentsApi payments;            // payments' public API
 Wrong     void wrong(Order o) { paymentRepo.save(new Payment(o.id(), o.total())); }   // skips payments' rules

    // Right: ask the module; it owns its tables and its rules
 Right     void right(Order o) { payments.charge(o.id(), o.total()); }

    CheckoutService(PaymentRepository paymentRepo, PaymentsApi payments) {
        this.paymentRepo = paymentRepo;
        this.payments = payments;
    }
}
Reaching into another module's tables couples them for good
Strangler fig, moving one route at a timeClients call a gateway. The gateway sends requests for checkout to the new checkout service, which has its own database, and every other request to the monolith. Each release moves one more route, until the monolith is empty or small./checkout/**everything elseClientsGatewayCheckout serviceMonolithCheckout DBMonolith DB
Strangler fig, moving one route at a timeClients call a gateway. The gateway sends requests for checkout to the new checkout service, which has its own database, and every other request to the monolith. Each release moves one more route, until the monolith is empty or small./checkout/**everything elseClientsGatewayCheckout serviceMonolithCheckout DBMonolith DB
Strangler fig: move one route at a time

Solve it

Should we move our monolith to microservices?

Your company runs one Spring Boot application with 40 developers in five teams. Releases are weekly and often slip because one team’s change breaks another’s tests. During sales, checkout needs ten times the usual capacity, while the rest of the app is idle. The head of engineering asks you whether to rewrite everything as microservices.

  1. Name the pain. There are two concrete problems: teams block each other’s releases, and checkout must scale alone. Fashion is not a reason; each split must remove one of these pains.
  2. Fix the coupling first. Make the code a modular monolith: one module per business area, public APIs, a test that fails on a reach into internals. If modules cannot be separated in-process, they will not separate over a network.
  3. Extract the module that pays. Checkout scales apart and has one team, so move it first behind a gateway route: the strangler fig. Give it its own database and keep a rollback route.
  4. Accept the costs. The checkout call now crosses the network, so add timeouts, retries and tracing, and replace the shared transaction with events.
  5. Check. Measure release frequency, failed releases and checkout cost under load before and after. Stop splitting when the numbers stop improving.
# Spring Cloud Gateway: the first matching route wins
# Extracted first, because it scales on its own
spring.cloud.gateway.server.webflux.routes[0].id=checkout
spring.cloud.gateway.server.webflux.routes[0].uri=http://checkout-service:8080
spring.cloud.gateway.server.webflux.routes[0].predicates[0]=Path=/checkout/**

# Everything else stays in the monolith until it moves
spring.cloud.gateway.server.webflux.routes[1].id=monolith
spring.cloud.gateway.server.webflux.routes[1].uri=http://monolith:8080
spring.cloud.gateway.server.webflux.routes[1].predicates[0]=Path=/**
The gateway sends checkout to the new service and the rest to the monolith

How to answer

  • Microservices solve an organizational problem first, teams blocking each other, and a scaling problem second.
  • The network is not free: calls can be slow or fail, so timeouts, retries and circuit breakers become mandatory.
  • A local ACID (atomicity, consistency, isolation, durability) transaction becomes eventual consistency across services.
  • A modular monolith keeps one deployable with enforced module borders, and is the usual starting point.

Common mistakes

  • Saying microservices are always better, or that they scale better by default. A monolith can run many replicas behind a load balancer.
  • Splitting by technical layer, such as a database service and a UI service, instead of by business capability.

Follow-up questions

When should you NOT use microservices?

When one or two teams own the product, when the domain is new and its boundaries are still moving, when there is no automated deployment, monitoring and on-call to run many services, or when the load is even and a few replicas of one app handle it. In those cases a wrong split costs more than a monolith ever would.

  • Moving a boundary between modules is a refactoring; moving one between services is a migration.
  • Each service needs its own pipeline, dashboards, alerts and on-call.
  • Martin Fowler's advice is monolith first, then extract once the boundaries are proven.

See it in the infographic: Which architecture fits this team?

What is a modular monolith?

One deployable application split into modules along business capabilities, such as orders, payments and shipping. Each module owns its data and exposes a small public API; everything else is internal. Tools such as Spring Modulith or ArchUnit fail the build when a module reaches past a border. You keep in-process calls and one release, and gain the clear boundaries you need to extract a service later.

  • Modules talk through public interfaces or in-process events, never through each other's tables.
  • A schema per module keeps data ownership clear inside one database.
  • Extracting a well-kept module later is mostly moving code, not untangling it.

See it in the infographic: Monolith, modular monolith and microservices

What does Conway's law say, and how does it affect the choice of architecture?

Conway's law says a system's structure copies the communication structure of the organization that builds it. Five teams that rarely talk will produce five loosely connected parts, whatever the diagram says. So service boundaries should match team boundaries: one team owns one or a few services end to end. The inverse Conway maneuver shapes the teams first to get the architecture you want.

  • A service owned by two teams turns every change into a meeting.
  • Team size is a real input to the choice, not an afterthought.
  • Team Topologies calls these stream-aligned teams, each owning a business flow.

See it in the infographic: Which architecture fits this team?

How would you migrate a monolith to microservices without a big-bang rewrite?

Use the strangler fig pattern. Put a gateway or proxy in front of the monolith, modularize the code, then extract one module at a time: build it as a service with its own database, move its route in the gateway, and delete the old code. Pick first a module with clear borders and a real reason to leave, such as its own scaling.

  • Keep a rollback route in the gateway until the new service has proven itself.
  • Move the data too, or the services stay coupled through the old schema.
  • Big-bang rewrites stop feature work for months and usually miss behavior nobody documented.

See it in the infographic: Monolith, modular monolith and microservices

What must a team have in place before running microservices in production?

Automated build and deployment per service, so releasing is cheap. Centralized logs, metrics and distributed tracing, so one request can be followed across services. Health checks and an orchestrator such as Kubernetes to restart and scale them. Resilience in every client: timeouts, retries and circuit breakers. And clear ownership: each service has one team that runs it in production.

  • Martin Fowler lists rapid provisioning, basic monitoring and rapid deployment as prerequisites.
  • Without tracing, a slow request across five services is a guessing game.
  • Contract tests replace much of the end-to-end testing a monolith had for free.

See it in the infographic: Monolith, modular monolith and microservices

Can a monolith scale horizontally?

Yes. A stateless monolith runs as many identical replicas behind a load balancer, and that covers most loads. What it cannot do is scale one part alone: every replica carries every module, so a hot checkout forces you to scale the whole app, memory and all.

What is a distributed monolith?

Services that are deployed separately but cannot change separately: they share a database, call each other synchronously in long chains, or must be released together. You pay for the network and get none of the independence. It usually comes from splitting before the boundaries are understood.

Check yourself

1. In a single Spring Boot app, checkout needs ten times more instances during sales, and the rest of the app does not. Which option does this point to?
Show answers
  • Extract checkout as its own service: Correct. A part that scales apart, with clear borders, is the classic first extraction.
  • Split every module into a service at once: Incorrect. Only checkout has the problem. Splitting the rest adds network cost for nothing.
  • Nothing can help a monolith scale: Incorrect. A monolith can scale out as replicas; it just cannot scale one part alone.
2. How many deployables does a modular monolith with five modules have?
Show answers
  • One: Correct. The modules have enforced borders, but they ship and run as a single application.
  • Five: Incorrect. That would be five services. A modular monolith keeps one deployable.
  • Six, with a gateway: Incorrect. A gateway is optional and is not part of the modular monolith itself.
3. Which sign shows that a system is a distributed monolith?
Show answers
  • Three services must always be released together: Correct. Services that cannot change alone have the network's costs without its independence.
  • Each service has its own database: Incorrect. That is the intended design, not a warning sign.
  • One service runs ten replicas: Incorrect. Scaling one service alone is a benefit of microservices.