Polski

Article · Monolith · Modular Monolith

The Monolith: one application, one deployment, and why it is often the right start

What a monolith really is, when it is the best choice, how it turns into a big ball of mud and how to get out of it without a revolution. Structure in .NET, Java, Node.js, Go and Python.

By · · 11 min read

The first version of the ordering system for Halina's pierogi place was built in six weeks: one project, one database, one deployment on a Friday afternoon. It was a monolith, and it was a good choice. This article opens the "From monolith to microservices" path and explains why a monolith is not an insult but a starting point you need to keep in shape.

1
deployment unit – one artifact, one pipeline, one log
2.8M
lines of Ruby in Shopify's monolith – company figures from 2019
90%
lower cost of a Prime Video service – after moving back from microservices to a monolith (2023)

Context and forces

Halina wants to take orders through a website. The team is three people, the budget is modest and little is known about the domain: it isn't clear whether deliveries, wedding catering or a loyalty programme will turn out to matter most. In such a situation, these forces are at play:

  • Speed of delivery – the idea has to be tested on the market before the money runs out.
  • An uncertain model – the boundaries between "order", "menu" and "customer" will keep shifting.
  • A small team – there is nobody dedicated to Kubernetes, queues and distributed tracing.
  • Data consistency – the order, the stock level and the loyalty points must agree to the last penny.

A monolith answers all four: one codebase where refactoring is a "Rename" in the IDE, one deployment and one database transaction.

Structure: what exactly is "one"

In Monolith to Microservices (2019), Sam Newman distinguishes three kinds of monolith: the single-process monolith (the classic one), the modular monolith (one process, but clear modules) and the distributed monolith (many services that still have to be deployed together). The common denominator: the system is deployed as a whole.

Diagram: Container view (C4 style): the pierogi place monolith
ElementRoleTypical form
Deployment unitEverything that goes to production at onceone .jar file, a Docker image, a publish/ folder
Logical modulesOrders, menu, loyalty – often just folderspackages, namespaces, Django apps
Shared databaseOne source of truth, transactions across modulesPostgreSQL, SQL Server, MySQL
IntegrationsPayments, SMS, emailHTTP clients called from the code

What it looks like in code

Whatever the tech stack, a monolith has a similar shape: one entry point, one database configuration and modules that call each other directly.

One app, one deployment

dotnet/Pierogarnia.sln.txt
Pierogarnia/
├── Pierogarnia.Web/              ← ONE deployable: ASP.NET Core
│   ├── Controllers/              ← Orders, Menu, Loyalty, Admin
│   ├── Services/                 ← OrderService, LoyaltyService, StockService
│   ├── Data/PierogarniaDb.cs     ← ONE DbContext, ONE database
│   ├── Views/ + wwwroot/         ← server-rendered UI
│   └── Program.cs
└── Pierogarnia.Tests/
java/pierogarnia-tree.txt
pierogarnia/                      ← ONE Spring Boot jar
└── src/main/java/pl/pierogarnia/
    ├── PierogarniaApplication.java
    ├── web/                      ← @RestController classes
    ├── service/                  ← OrderService, LoyaltyService, StockService
    ├── repository/               ← Spring Data JPA, ONE DataSource
    └── model/                    ← @Entity classes shared by everything
node/pierogarnia-tree.txt
pierogarnia/                      ← ONE Node.js process (Express or NestJS)
├── src/
│   ├── routes/                   ← orders.ts, menu.ts, loyalty.ts
│   ├── services/                 ← orderService.ts, stockService.ts
│   ├── db/                       ← ONE Prisma/Knex client, ONE schema
│   └── server.ts
└── package.json
go/pierogarnia-tree.txt
pierogarnia/                      ← ONE binary
├── cmd/server/main.go
├── internal/
│   ├── http/                     ← handlers for orders, menu, loyalty
│   ├── service/                  ← business logic
│   └── store/                    ← ONE *sql.DB
└── go.mod
python/pierogarnia-tree.txt
pierogarnia/                      ← ONE Django project
├── manage.py
├── pierogarnia/settings.py       ← ONE DATABASES["default"]
├── orders/                       ← Django app: models, views
├── menu/
└── loyalty/                      ← apps import each other's models freely

The monolith's biggest advantage shows in a use case that touches several areas at once. Placing an order saves the order, takes the pierogi off the stock and adds loyalty points – in one transaction. If the dough runs out, everything is rolled back:

Order, stock and points in one transaction

OrderService.cs
public sealed class OrderService(PierogarniaDb db)
{
    public async Task<Guid> PlaceOrder(PlaceOrderRequest req, CancellationToken ct)
    {
        // One process, one database, one ACID transaction: the monolith's superpower.
        await using var tx = await db.Database.BeginTransactionAsync(ct);

        var order = new Order(req.CustomerId, req.Lines);
        db.Orders.Add(order);

        foreach (var line in req.Lines)
        {
            var stock = await db.Stock.SingleAsync(s => s.Dumpling == line.Dumpling, ct);
            stock.Take(line.Quantity);              // throws when Halina runs out of dough
        }

        var customer = await db.Customers.FindAsync([req.CustomerId], ct);
        customer!.AddLoyaltyPoints(order.Total);    // a plain method call, no network

        await db.SaveChangesAsync(ct);
        await tx.CommitAsync(ct);                   // all three changes or none
        return order.Id;
    }
}
orderService.ts
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function placeOrder(req: PlaceOrderRequest): Promise<string> {
  // One process, one database, one ACID transaction: the monolith's superpower.
  return prisma.$transaction(async (tx) => {
    const total = req.lines.reduce((sum, l) => sum + l.quantity * l.unitPrice, 0);
    const order = await tx.order.create({
      data: { customerId: req.customerId, total, lines: { create: req.lines } },
    });

    for (const line of req.lines) {
      const stock = await tx.stock.update({
        where: { dumpling: line.dumpling },
        data: { pieces: { decrement: line.quantity } },
      });
      if (stock.pieces < 0) throw new Error("Halina ran out of dough"); // rolls everything back
    }

    // A plain function call, no network, no eventual consistency.
    await tx.customer.update({
      where: { id: req.customerId },
      data: { loyaltyPoints: { increment: Math.floor(total) } },
    });
    return order.id;
  });
}
OrderService.java
@Service
public class OrderService {
    private final OrderRepository orders;
    private final StockRepository stock;
    private final CustomerRepository customers;

    public OrderService(OrderRepository orders, StockRepository stock, CustomerRepository customers) {
        this.orders = orders;
        this.stock = stock;
        this.customers = customers;
    }

    // One process, one database, one ACID transaction: the monolith's superpower.
    @Transactional
    public UUID placeOrder(PlaceOrderRequest req) {
        var order = orders.save(new Order(req.customerId(), req.lines()));

        for (var line : req.lines()) {
            stock.findByDumpling(line.dumpling())
                 .orElseThrow()
                 .take(line.quantity());          // throws -> the whole transaction rolls back
        }

        customers.findById(req.customerId())
                 .orElseThrow()
                 .addLoyaltyPoints(order.total()); // a plain method call, no network
        return order.id();
    }
}
order_service.go
package service

import (
	"context"
	"database/sql"
	"errors"
)

type OrderService struct{ DB *sql.DB }

// PlaceOrder: one process, one database, one ACID transaction.
func (s OrderService) PlaceOrder(ctx context.Context, req PlaceOrderRequest) (string, error) {
	tx, err := s.DB.BeginTx(ctx, nil)
	if err != nil {
		return "", err
	}
	defer tx.Rollback() // no-op after Commit

	var orderID string
	err = tx.QueryRowContext(ctx,
		`INSERT INTO orders (customer_id, total) VALUES ($1, $2) RETURNING id`,
		req.CustomerID, req.Total()).Scan(&orderID)
	if err != nil {
		return "", err
	}

	for _, l := range req.Lines {
		res, err := tx.ExecContext(ctx,
			`UPDATE stock SET pieces = pieces - $1 WHERE dumpling = $2 AND pieces >= $1`,
			l.Quantity, l.Dumpling)
		if err != nil {
			return "", err
		}
		if n, _ := res.RowsAffected(); n == 0 {
			return "", errors.New("halina ran out of dough") // deferred Rollback undoes the order
		}
	}

	if _, err = tx.ExecContext(ctx,
		`UPDATE customers SET loyalty_points = loyalty_points + $1 WHERE id = $2`,
		int(req.Total()), req.CustomerID); err != nil {
		return "", err
	}
	return orderID, tx.Commit()
}
orders/services.py
from django.db import transaction
from django.db.models import F

from loyalty.models import Customer
from menu.models import Stock
from orders.models import Order


class OutOfDough(Exception):
    pass


@transaction.atomic  # one process, one database, one ACID transaction
def place_order(customer_id: int, lines: list[dict]) -> int:
    order = Order.objects.create(customer_id=customer_id)
    for line in lines:
        order.lines.create(dumpling=line["dumpling"], quantity=line["quantity"])
        updated = Stock.objects.filter(
            dumpling=line["dumpling"], pieces__gte=line["quantity"]
        ).update(pieces=F("pieces") - line["quantity"])
        if updated == 0:
            raise OutOfDough(line["dumpling"])  # rolls back the order as well

    # A plain function call into another "module": no network, no retries.
    Customer.objects.filter(pk=customer_id).update(
        loyalty_points=F("loyalty_points") + int(order.total())
    )
    return order.pk

In microservices, the same scenario requires a saga, compensations and idempotent consumers. Here it's a dozen lines and a COMMIT.

Diagram: One request, one process, one transaction

Trade-offs

Pros

  • one deployment, one log, one debugger – a low barrier to entry
  • ACID transactions spanning the entire business process
  • refactoring in the IDE instead of negotiating contracts between teams
  • in-memory calls instead of the network: no latency and no partial failures
  • simple local start: dotnet run, mvn spring-boot:run, npm start

Cons

  • you scale the whole thing, even when only one area is under load
  • a single failure (e.g. a memory leak) takes down the entire system
  • long builds and test runs once the code grows without boundaries
  • everyone deploys together: teams wait for each other
  • one tech stack for all modules

In 1997, Brian Foote and Joseph Yoder described the "Big Ball of Mud": a system in which nobody knows any more what depends on what. That is not a property of the monolith but of missing boundaries – a distributed ball of mud is even worse, because the network is added to the tangle.

The design stamina hypothesis: cost of a new feature over time – An illustration of Martin Fowler's Design Stamina Hypothesis, made-up values – not a measurement from a project.
Monolith without boundariesMonolith with modules
month 12 days3 days
month 63 days3 days
year 15 days4 days
year 29 days4 days
year 314 days5 days
year 421 days5 days

When to choose a monolith, and when not to

A monolith is a sensible default when the team is small (up to a dozen or so people), the domain is still taking shape and the scaling requirements are moderate. In Monolith First (2015), Martin Fowler observes that most successful microservice systems started as a monolith that was split over time, while projects that started with microservices more often ran into trouble.

A monolith stops being enough when concrete signals appear, not fashion:

  1. Several teams block each other at deployment time despite good modularity.
  2. One area has radically different requirements (e.g. GPU image processing or 100× more traffic).
  3. Part of the system needs a different release cycle or different compliance requirements (e.g. payments).

Migration paths

Leaving a monolith is a process, not a rewrite from scratch. The typical route looks like this:

  1. Step 1 Dependency map – Draw who calls whom and who reads which tables. Tools: NDepend, ArchUnit, dependency-cruiser, go list -deps, import-linter.
  2. Step 2 Modular monolith – Extract modules with a public API and their own tables. Guard the boundaries with architecture tests.
  3. Step 3 In-process events – Replace direct calls between modules with events wherever eventual consistency is enough.
  4. Step 4 Strangler Fig – Put a new service alongside, route part of the traffic through a gateway and gradually retire the old code.
  5. Step 5 Separate databases – Split the data only at the very end – it's the hardest and most expensive step.

Martin Fowler described the strangler pattern in 2004, inspired by fig trees that wrap around a host tree until they eventually replace it. It works because the system is deployable at every moment.

In practice

  • Shopify runs one of the largest Ruby on Rails monoliths and, instead of splitting it, organises it into a modular monolith; it built the Packwerk tool to enforce boundaries between components.
  • Basecamp and HEY – in The Majestic Monolith (2016), David Heinemeier Hansson defends the monolith as a deliberate choice for small teams.
  • Segment described in 2018 how it went back from more than a hundred microservices handling integrations to a single service, because the maintenance cost outweighed the benefits.
  • Amazon Prime Video in 2023 moved its stream-quality monitoring service from a distributed serverless architecture to a single process and cut its infrastructure cost by 90%.

In every ecosystem the monolith is simply the default template: dotnet new webapi, Spring Initializr, nest new, django-admin startproject or a single main.go with net/http.

Anti-patterns

  • A 3,000-line Utils / Common class used by every module – invisible glue that makes any split impossible.
  • Entities shared by everybody – a single Customer class with 80 fields used by sales, delivery and accounting.
  • The distributed monolith – a split into services that need a joint deployment and synchronous call chains; you pay for the network and don't get independence.
  • A big-bang rewrite instead of a gradual migration – the new system chases the old one, which keeps changing.

Test yourself

Question: What is the defining property of a monolith?

  • No split of the code into modules
  • The whole system is deployed as one unit
  • Using a single programming language
  • No automated tests
Interview question: when would you NOT split a monolith into microservices?

When the problem is missing boundaries in the code rather than scale or team independence. Splitting a tangled monolith gives you a distributed monolith: the same dependencies, only over the network, with partial failures and without transactions. Modularise first and add architecture tests; then – if concrete needs appear (independent deployments for several teams, different scaling profiles) – extract services using the strangler pattern.