Skip to content
Cloud Computing

Microservices vs Monolith: Choose the Right Architecture

Compare monoliths, modular monoliths, and microservices by team needs, deployment, scaling, and operational complexity. Learn how to evaluate boundaries and make a gradual service extraction using Ubuntu, Docker, nginx, and PostgreSQL.

Microservices vs Monolith: Choose the Right Architecture

Microservices vs Monolith: Choosing an Architecture That Fits Your Team

Choosing an architecture is not a contest between old and new. The right choice for microservices vs monolith depends on how your product changes, how many teams need to work independently, and whether your organisation can run a distributed system.

A monolith is usually the practical starting point when a product, team or domain is still taking shape. Microservices help when clear business boundaries and independent scaling or releases solve real problems, and when your team can handle the extra operational work. A modular monolith gives you structure without a network of services.

What is the difference between microservices and monolith architecture?

A monolithic architecture packages an application's main functions into one deployable unit. A microservices architecture splits an application into independently deployable services that communicate over a network.

In a monolith, features may live in separate code modules, but they are usually built and released together. The application often calls between modules directly within the same process.

In microservices, each service owns a defined capability and usually owns its data. Services talk through network interfaces or messaging, so one request may depend on several separately running components. This allows independent releases, but it also brings network failures, service discovery, monitoring and data consistency problems. Practitioner perspectives on 2026 trade-offs describe the distinction and its operational costs.

You can see the difference in the artefact you ship and the number of network hops a request crosses. A monolith produces one image (or one process tree) that contains every module:

# Dockerfile — monolith: one image, every module inside
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY build/libs/shop-1.4.0.jar /app/app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/app.jar"]
docker build -t registry.example.com/shop/monolith:1.4.0 .
docker image ls registry.example.com/shop/monolith --format '{{.Repository}}:{{.Tag}} {{.Size}}'

Expected output is a single tag and size, for example registry.example.com/shop/monolith:1.4.0 312MB. If you need three images with three tags and three health endpoints, you are running a service-based system, no matter how the code looks.

Area Monolith Microservices
Deployment The application is released as one unit. Services can be released separately.
Communication Components can often communicate within one process. Services communicate over a network or messaging system.
Data Components may share a database. Each service should own its data; cross-service data work needs deliberate design.
Scaling The application is typically scaled as a whole. Individual services can scale separately when workloads differ.
Operations Fewer separately managed runtime components. More services, deployments, alerts and failure paths to manage.
Best fit A focused product or team that needs straightforward delivery. A system with stable boundaries and teams that can run services independently.

Which should you choose: monolith vs microservices?

A monolith is a sound choice when one team owns most of the product, requirements change quickly, or the application lacks clear service boundaries. Microservices suit organisations that need real team or service independence and can invest in the infrastructure and engineering practices to support it.

Choose based on the bottleneck you need to remove, not on a forecast that your application will someday become large. A monolith can be modular and well maintained. A set of services can still be tightly coupled and hard to change.

Ask these questions before you decide:

  1. Are the business boundaries clear? If teams cannot agree where one capability ends and another begins, separate services may turn that uncertainty into network dependencies.
  2. Do teams need to release independently? If your single release process is not slowing delivery, separate deployments add work without solving a current problem.
  3. Does one workload need different scaling? Separate scaling helps when a specific service has distinct resource demands, but you need to observe and manage that service on its own.
  4. Can your team operate the system? Microservices require reliable deployment automation, monitoring, logging, incident response and clear service ownership.
  5. Can the data be separated sensibly? If everyday operations depend on unrestricted access to shared tables, splitting the application may create complex coordination across services.

Answer questions 2 and 3 with data, not gut feeling. On the machine that holds your repository, measure how often each area of the code changes:

git log --since="90 days ago" --name-only --pretty=format: -- app/billing app/inventory \
  | sed '/^$/d' | sort | uniq -c | sort -rn | head -20

The output is a list of file paths ranked by change frequency. If the top entries keep mixing the two candidate areas, the change is not yet separable. Next, measure your delivery cadence:

git log --since="90 days ago" --merges --oneline | wc -l

Expected output is a single number, such as 24. A high number from a single team suggests the release process is not the bottleneck.

What is a modular monolith, and when is it better?

A modular monolith is a single deployable application divided into well-defined internal modules with controlled dependencies. It suits teams that need a well-structured codebase but do not yet need the independent deployment and operation of separate services.

Modules can represent business capabilities such as billing or inventory. Clear interfaces and limited cross-module access make changes easier to reason about, and a single deployment avoids network calls between those modules.

This approach is not an automatic stepping stone to microservices. A module should become a separate service only when a specific need, such as independent ownership, release cadence or scaling, justifies the added operational cost. The modular monolith discussion from Encore makes a similar case for building internal structure before introducing distributed boundaries.

Enforce boundaries with tooling, or they will erode over time. Here is a layout that keeps internals private:

app/
├── billing/
│   ├── api.py            # public surface other modules may import
│   ├── service.py
│   └── internal/
│       └── repository.py # private implementation detail
├── inventory/
│   ├── api.py
│   └── internal/
└── main.py
# .importlinter — declared at the repository root
[importlinter]
root_package = app

[importlinter:contract:billing-no-inventory-internals]
name = Billing must not reach into Inventory internals
type = forbidden
source_modules =
    app.billing
forbidden_modules =
    app.inventory.internal
python3 -m venv .venv
source .venv/bin/activate
pip install import-linter
lint-imports

Expected output ends with a summary line such as Contracts: 1 kept, 0 broken. A broken contract prints the offending import chain, which gives you the evidence you need before you decide to extract a service.

How do the pros and cons of monolith vs microservices compare?

A monolith reduces the number of separately deployed components. Microservices give teams more freedom to deploy and scale on their own. Neither comes free. Monoliths get hard to change when internal boundaries are neglected, and services get hard to run when their interactions are poorly managed.

Architecture Advantages Trade-offs
Monolith One release unit; simpler local development and deployment; direct calls between in-process components. The whole application may need rebuilding or redeploying for a change; components can become tightly coupled; scaling may include parts that do not need it.
Modular monolith One release unit with explicit internal boundaries; easier to refactor across modules than across networked services. Requires discipline to keep module boundaries intact; all modules still share the application's deployment lifecycle.
Microservices Independent service releases; teams can own separate capabilities; services can scale separately. More deployment and monitoring work; network failures and latency; harder cross-service testing and data coordination.

Scaling services independently pays off only when workloads or resource needs differ enough to justify it. If most parts of an application always change and scale together, separate services leave you managing extra components without gaining real independence.

What is the difference between a monolith, SOA and microservices?

Service-oriented architecture (SOA) exposes software capabilities as services, often for use across an organisation. Microservices are a style of service architecture that favours small services with clear ownership and independent deployment. A monolith is deployed as one application unit.

These terms are not interchangeable, and real systems rarely fit neatly into one category. For a practical decision, focus on how capabilities are owned, deployed and connected rather than on the label.

Property Monolith SOA Microservices
Unit of deployment One application Shared, often enterprise-wide services Small, independently deployable services
Typical integration In-process calls Enterprise service bus, SOAP/WS-* REST, gRPC, message brokers
Data ownership Often one shared database Frequently shared or centrally governed Per-service ownership
Governance Single codebase review Central platform or integration team Team autonomy with platform guardrails
Typical failure mode Tangled internals Bus becomes a bottleneck Distributed complexity

Serverless is a cloud execution model in which the provider manages the underlying servers for your workloads. So monolith vs microservices vs serverless is not a strict three-way comparison. A monolith or a service-based system can use serverless components, depending on your platform and design.

What are practical examples of choosing each architecture?

These three examples show how the right choice shifts with a team's needs. They are scenarios, not reports about named companies or measured results.

A small booking product: One team is building customer accounts, listings and reservations, and requirements change often. A modular monolith lets the team keep one deployment and set boundaries in code. Splitting into services before the domain settles could force the team to coordinate API and data changes across a network.

A growing commerce platform: Several teams own distinct capabilities, such as catalogues, payments and fulfilment, and each needs its own release schedule or capacity plan. Microservices may fit if each team can own its service, define its data boundaries and support it in production. If every service still needs coordinated releases and shares the same data tables, the separation may be mostly cosmetic.

A mature application with rising maintenance costs: A team sees slow releases but cannot point to a clear domain boundary behind the delay. Moving to microservices is unlikely to fix the underlying problem on its own. The team should first improve module boundaries, build automation and refine delivery practices. Then it can extract a service if the evidence shows a real need.

What do practitioners recommend about monolith vs microservices in 2026?

Practitioners generally treat architecture as a trade-off rather than a ranking. The DEV Community decision discussion argues that the right choice depends on the system, the team and the scale. The Codelit decision guide stresses the value of clear business boundaries.

That advice is most useful when you turn it into observable conditions. If the application is hard to change because its internal code is tangled, improve its structure first. If independent teams are blocked by shared releases even though their capability boundaries are clear, separating services may solve the problem.

A popular monolith vs microservices meme contrasts a "simple monolith" with "complicated services." The joke captures a real risk: adopting distributed systems too early. But it is not a decision framework. A well-structured monolith can become hard to change, and a carefully designed service architecture can support independent teams. Implementation and operational discipline matter more than the label.

How can a team move from a monolith to microservices safely?

Split a monolith only after you have identified a capability that needs independent ownership, deployment or scaling. The transition can happen gradually. You do not need a full rewrite.

The walkthrough below targets Ubuntu 24.04 LTS with Docker Engine 27.x and Compose v2, nginx 1.24.0 and PostgreSQL 16 from the distribution archives. Keep the whole toolchain on these versions so paths, flags and package names match.

Prerequisites

You need a server with sudo access, a DNS record for your_domain pointing at YOUR_SERVER_IP, and ports 80 and 443 reachable if the service is public.

sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg nginx postgresql-16 postgresql-client-16 dnsutils

Install Docker Engine from the official repository:

sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
  | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
  | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

Verify each component before you change anything:

docker --version
docker compose version
nginx -v
psql --version
systemctl is-active docker

Expected output looks like Docker version 27.3.1, build ce12230, Docker Compose version v2.29.7, nginx version: nginx/1.24.0 (Ubuntu), psql (PostgreSQL) 16.4 (Ubuntu 16.4-1.pgdg24.04+1) and active. If the Docker daemon is not active, start it with sudo systemctl enable --now docker, then run the check again.

Warning

Adding a user to the docker group gives that user root-equivalent control of the host. On shared servers, run Compose with sudo instead of granting permanent membership.

Step 1: Map business capabilities and dependencies

Identify which parts of the application change together and where teams need a clearer ownership boundary. Run the change-frequency command from the decision section against your real repository paths. Then confirm the coupling with a quick inventory of the current schema:

sudo -u postgres psql -d shop -c "\dt" | head -30
sudo -u postgres psql -d shop -c "SELECT table_name FROM information_schema.tables WHERE table_schema='public' ORDER BY 1;"

Expected output is the list of tables. Any table that every candidate capability depends on will make the split expensive. Note those tables before you go on.

Step 2: Strengthen module boundaries

Limit direct access between components and make dependencies explicit before you add network calls. Add the .importlinter file shown earlier, run lint-imports, and require a passing result in CI. A passing run looks like this:

source .venv/bin/activate
lint-imports
=============
Import Linter
=============

---------
Contracts
---------

Analyzed 42 files, 118 dependencies.
------------------------------------

Billing must not reach into Inventory internals KEPT
Contracts: 1 kept, 0 broken.

Do not extract anything until this passes. A service boundary drawn over tangled code just moves the tangle behind an HTTP call.

Step 3: Choose one justified extraction

Pick one capability with a clear interface and manageable data ownership. Don't split every module at once. For the billing capability, create a dedicated role and database so the service cannot depend on the monolith's tables:

-- /tmp/billing_db.sql — run as the postgres superuser
CREATE ROLE billing_svc LOGIN PASSWORD 'YOUR_BILLING_DB_PASSWORD';
CREATE DATABASE billing OWNER billing_svc;
REVOKE ALL ON DATABASE billing FROM PUBLIC;
sudo -u postgres psql -v ON_ERROR_STOP=1 -f /tmp/billing_db.sql
psql "postgresql://billing_svc:YOUR_BILLING_DB_PASSWORD@127.0.0.1:5432/billing" -c '\dt'

Expected output is Did not find any relations. This means the database is empty and the service owns it from start to finish.

Warning

Never drop or rename shared tables during cutover. Keep the monolith's tables writable until the new service has handled production traffic. Take a verified backup first with sudo -u postgres pg_dump -Fc shop > /var/backups/shop-pre-split.dump.

Step 4: Automate testing and releases

Independent deployments need reliable checks and a repeatable release process. A CI/CD pipeline guide can help you plan those stages. The minimum gate for an extracted service is a build, a unit test run and a consumer contract check:

# .github/workflows/billing.yml
name: billing
on:
  push:
    paths: ["services/billing/**"]

jobs:
  verify:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4
      - name: Build
        run: docker build -t billing:${{ github.sha }} services/billing
      - name: Unit tests
        run: docker run --rm billing:${{ github.sha }} pytest -q
      - name: Contract check
        run: |
          docker run --rm pactfoundation/pact-cli:latest \
            broker can-i-deploy \
            --pacticipant BillingWeb \
            --version "${{ github.sha }}" \
            --to-environment production \
            --broker-base-url https://pact.your_domain

A passing contract check prints a table that ends with Computer says yes \o/. A failing one prints Computer says no along with the verification that broke. Catching the mismatch here costs far less than finding it in production.

Step 5: Add operational ownership

Before you rely on the service in production, define how it is monitored, how failures are investigated and who responds. Put both units under Compose with health checks, and bind published ports to the loopback interface only:

# /srv/shop/compose.yaml
name: shop

services:
  monolith:
    image: registry.example.com/shop/monolith:1.4.0
    restart: unless-stopped
    ports:
      - "127.0.0.1:8080:8080"
    environment:
      DATABASE_URL: postgresql://shop_app:${SHOP_DB_PASSWORD}@127.0.0.1:5432/shop
    healthcheck:
      test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/healthz || exit 1"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 40s

  billing:
    image: registry.example.com/shop/billing:0.3.0
    restart: unless-stopped
    ports:
      - "127.0.0.1:8081:8081"
    environment:
      DATABASE_URL: postgresql://billing_svc:${BILLING_DB_PASSWORD}@127.0.0.1:5432/billing
    healthcheck:
      test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8081/healthz || exit 1"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 40s
# /srv/shop/.env
SHOP_DB_PASSWORD=YOUR_SHOP_DB_PASSWORD
BILLING_DB_PASSWORD=YOUR_BILLING_DB_PASSWORD
cd /srv/shop
chmod 600 .env
docker login registry.example.com
docker compose up -d
docker compose ps

Expected output shows both containers with a status of Up ... (healthy). If a container reports unhealthy, read the probe output with docker inspect --format '{{json .State.Health}}' shop-billing-1.

Route traffic gradually with nginx instead of switching the DNS record:

# /etc/nginx/sites-available/shop.your_domain
upstream monolith_app {
    server 127.0.0.1:8080;
    keepalive 32;
}

upstream billing_app {
    server 127.0.0.1:8081;
    keepalive 32;
}

server {
    listen 80;
    server_name your_domain;

    location /api/billing/ {
        proxy_pass http://billing_app/;   # trailing slash strips /api/billing/
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location / {
        proxy_pass http://monolith_app;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
sudo ln -s /etc/nginx/sites-available/shop.your_domain /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
curl -sS -o /dev/null -w '%{http_code}\n' http://your_domain/api/billing/healthz
curl -sS -o /dev/null -w '%{http_code}\n' http://your_domain/

Expected output is nginx: configuration file /etc/nginx/nginx.conf test is successful, followed by 200 for both requests. Open the firewall only after this works locally:

sudo ufw allow 'Nginx Full'
sudo ufw status verbose

Warning

ufw allow 'Nginx Full' exposes ports 80 and 443 to the internet. Confirm the site is meant to be public and that TLS certificates are in place before you run it.

Step 6: Review the result

Confirm the extraction removed a real bottleneck. Don't keep splitting services just because the first split happened. Compare delivery and reliability signals against your pre-split baseline:

docker compose ps
docker stats --no-stream --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'
sudo tail -n 20 /var/log/nginx/access.log
git log --since="30 days ago" --oneline -- services/billing | wc -l

Expected output includes healthy containers, per-container CPU and memory, request lines in the access log, and a deploy count. The memory and CPU figures show whether billing really scales differently from the monolith. If billing's resource profile matches the monolith's, the case for independent scaling has not materialised.

Rolling back takes one change. Remove the /api/billing/ location block, then run sudo nginx -t and sudo systemctl reload nginx. Keep that path available until the new service has run through at least one full traffic cycle.

Troubleshooting

502 Bad Gateway after routing traffic to the new service

2026/01/14 09:12:44 [error] ... connect() failed (111: Connection refused) while connecting to upstream

Cause: nginx is running, but the billing container is stopped, has crashed or is bound to a different port. Check the actual listener and the container state:

docker compose ps
ss -lntp | grep -E ':(8080|8081)\b'
curl -fsS http://127.0.0.1:8081/healthz; echo "exit=$?"

A non-zero exit code means the upstream is down. Fix the service, then reload nginx. If another process holds the port, stop that process rather than changing the proxy port.

permission denied while trying to connect to the Docker daemon socket

permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Cause: the user running the command is not in the docker group. Either prefix the command with sudo, or add the user to the group and open a new session:

sudo usermod -aG docker "$USER"
newgrp docker
docker info --format '{{.ServerVersion}}'

bind: address already in use when starting Compose

Error response from daemon: driver failed programming external connectivity on endpoint shop-billing-1: Bind for 127.0.0.1:8081 failed: port is already allocated

Cause: a leftover container or a host process is holding the port. Find it and remove it:

docker ps --filter "publish=8081"
docker rm -f shop-billing-1
ss -lntp | grep :8081
docker compose up -d

Container is unhealthy with exec: "curl": executable file not found

OCI runtime exec failed: exec failed: unable to start container process: exec: "curl": executable file not found in $PATH

Cause: the runtime image is distroless or slim and has no HTTP client. Either install a client in the image or switch the probe to a tool the image already includes:

    healthcheck:
      test: ["CMD", "wget", "--spider", "-q", "http://127.0.0.1:8081/healthz"]

pull access denied while deploying

Error response from daemon: pull access denied for shop/billing, repository does not exist or may require 'docker login'

Cause: the image path is wrong, or registry credentials are missing. Log in and confirm the tag exists:

docker login registry.example.com
docker manifest inspect registry.example.com/shop/billing:0.3.0 > /dev/null && echo "tag exists"

psql: FATAL: Peer authentication failed for user "billing_svc"

psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL:  Peer authentication failed for user "billing_svc"

Cause: a socket connection uses peer authentication, which matches the OS user, not the database role. Connect over TCP so PostgreSQL checks the password with scram-sha-256:

psql "postgresql://billing_svc:YOUR_BILLING_DB_PASSWORD@127.0.0.1:5432/billing" -c 'SELECT current_user, current_database();'

Duplicate invoices after enabling dual writes

Cause: retries that are not idempotent, or a backfill job that ran twice. Add a unique idempotency key on the write path and reconcile counts before you remove the old path:

psql "postgresql://billing_svc:YOUR_BILLING_DB_PASSWORD@127.0.0.1:5432/billing" \
  -c "SELECT count(*) FROM invoices WHERE created_at >= now() - interval '1 hour';"
sudo -u postgres psql -d shop \
  -c "SELECT count(*) FROM invoices WHERE created_at >= now() - interval '1 hour';"

Matching row counts are necessary but not enough. Compare a checksum of amounts too before you stop writing to the monolith's table.

Key takeaways

  • A monolith is usually a good fit when a product or domain is still evolving and one team can deliver it as a single application.
  • Microservices help when clear boundaries support independent ownership, releases or scaling, and your team can operate the resulting system.
  • A modular monolith adds internal structure without requiring separate deployments or network calls between modules.
  • Extract a service to solve a problem you can measure, not because you expect the application to grow.
  • Base architecture decisions on data ownership, release processes, monitoring and incident response as well as code structure.

If you are planning where to run an application as it grows, Ritik Barnwal's cloud hosting resources can help you make hosting decisions alongside the architecture choice.

Frequently asked questions

Is a monolith a bad choice for a new application?

No, a monolith is not automatically a poor choice for a new application. A monolith is practical when one team owns most of the product, requirements are changing quickly, or business boundaries are not clear. A modular monolith can add internal structure without separate deployments or network calls between modules.

Can you scale a monolith independently?

No, a monolith is typically scaled as a whole, rather than by individual module. Microservices can scale separately when workloads differ. Separate scaling is useful when a service has distinct resource demands; if most parts change and scale together, separate services add operational work without delivering real independence.

When is it worth extracting a service from a monolith?

Extract a service when a specific capability needs independent ownership, deployment, or scaling and has a clear interface with manageable data ownership. Strengthen module boundaries first, then extract one justified capability rather than splitting every module. Keep the monolith's tables writable during cutover until the new service has handled production traffic.

What software versions does the migration walkthrough use?

The walkthrough targets Ubuntu 24.04 LTS, Docker Engine 27.x with Compose v2, nginx 1.24.0, and PostgreSQL 16 from the distribution archives. The prerequisites also include sudo access, a DNS record for your domain pointing to the server IP, and ports 80 and 443 reachable if the service is public.

Comments

Loading comments…

Leave a comment

All articles