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.
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.
| Element | Role | Typical form |
|---|---|---|
| Deployment unit | Everything that goes to production at once | one .jar file, a Docker image, a publish/ folder |
| Logical modules | Orders, menu, loyalty – often just folders | packages, namespaces, Django apps |
| Shared database | One source of truth, transactions across modules | PostgreSQL, SQL Server, MySQL |
| Integrations | Payments, SMS, email | HTTP 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
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/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 everythingpierogarnia/ ← 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.jsonpierogarnia/ ← ONE binary
├── cmd/server/main.go
├── internal/
│ ├── http/ ← handlers for orders, menu, loyalty
│ ├── service/ ← business logic
│ └── store/ ← ONE *sql.DB
└── go.modpierogarnia/ ← ONE Django project
├── manage.py
├── pierogarnia/settings.py ← ONE DATABASES["default"]
├── orders/ ← Django app: models, views
├── menu/
└── loyalty/ ← apps import each other's models freelyThe 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
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;
}
}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;
});
}@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();
}
}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()
}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.pkIn microservices, the same scenario requires a saga, compensations and idempotent consumers. Here it's a dozen lines and a COMMIT.
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.
| Monolith without boundaries | Monolith with modules | |
|---|---|---|
| month 1 | 2 days | 3 days |
| month 6 | 3 days | 3 days |
| year 1 | 5 days | 4 days |
| year 2 | 9 days | 4 days |
| year 3 | 14 days | 5 days |
| year 4 | 21 days | 5 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:
- Several teams block each other at deployment time despite good modularity.
- One area has radically different requirements (e.g. GPU image processing or 100× more traffic).
- 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:
- Step 1 Dependency map – Draw who calls whom and who reads which tables. Tools: NDepend, ArchUnit, dependency-cruiser, go list -deps, import-linter.
- Step 2 Modular monolith – Extract modules with a public API and their own tables. Guard the boundaries with architecture tests.
- Step 3 In-process events – Replace direct calls between modules with events wherever eventual consistency is enough.
- Step 4 Strangler Fig – Put a new service alongside, route part of the traffic through a gateway and gradually retire the old code.
- 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/Commonclass used by every module – invisible glue that makes any split impossible. - Entities shared by everybody – a single
Customerclass 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.
Related topics
Modular monolith – The next step on the path: one process, but hard module boundaries
Layered architecture – How to organise code inside a module
Pierogi in the Hexagon – A hexagonal architecture course in .NET built around a pierogi place
Microservices – When splitting into services really pays off
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.