Monolith vs Microservices: Get the Boundaries Right Before You Decide Whether to Split
System Design series · Part 7 Architecture evolution (1 of 4)
- Monolith vs Microservices: Get the Boundaries Right Before You Decide Whether to Split
- Service Discovery: How Services Find Each Other, and What Happens When an Instance Disappears
- Sagas and the Outbox Pattern: Keeping a Cross-Service Flow Consistent Without Distributed Transactions
- Batch and Stream: Monthly Settlement Reports and a Live Trending List, Two Ways to Process Data
System Design series Part 7-1 | Previous: Observability | Next: Service Discovery | Series map
Read first: Part 6-2 Timeouts, Retries, Backoff, and Jitter.
Scenario and problem
The talk platform has been live for two years. The engineering team has grown from 4 people to 30, split into four teams: sign-ups and payments, the speaker back office, live interaction, and recommendations and data. The whole platform is still one Spring Boot application and one MySQL database.
Lately the complaints keep piling up:
- Everyone releases together every Thursday. One failing test in the recommendations team delays everything the other three teams have finished by a week
- Live interaction’s SSE connections leak memory, the whole application hits OOM and restarts, and sign-ups and payments go down with it
- The speaker back office’s monthly report query runs for 3 minutes and slows down sign-up transactions on the same database
- To change one sign-up column, you first have to find out whether any of the other three teams reads that table directly in their SQL
In a meeting, someone says: “Let’s split it into microservices.”
- Four teams, one applicationThe engineering team has grown from 4 people to 30, split into four teams, but the whole platform is still one Spring Boot application and one MySQL database.
- One test blocks everyoneEveryone releases together every Thursday. One failing test in the recommendations team delays everything the other three teams have finished by a week.
- One leak takes everything downLive interaction's SSE connections leak memory, the whole application hits OOM and restarts, and sign-ups and payments go down with it.
- One report slows transactionsThe speaker back office's monthly report query runs for 3 minutes and slows down sign-up transactions on the same database.
- One column, three teams to askTo change one sign-up column, you first have to find out whether any of the other three teams reads that table directly in their SQL. In a meeting, someone says: "Let's split it into microservices."
This post answers three questions: which problems microservices solve, which problems they bring with them, and what you should do before you split.
The simplest approach and its limits
- Keep a monolith with no boundaries: any class can call any class, and any code can query any table. Over time it becomes what is called a “big ball of mud”: nobody dares to change it, and nobody knows what a change will affect
- Split services by technical layer or by table:
UserService,LectureService, andRegistrationServiceeach become a microservice, each responsible for the CRUD of one table. The result is that every feature has to change three or four services at once, and they have to be deployed together. This is a distributed monolith: you carry the coupling of a monolith and the complexity of a distributed system at the same time
Core mechanism
What microservices buy you, and what you pay
| What you buy | What you pay |
|---|---|
| Independent deployment: each team decides when to ship, without waiting for anyone else | Calls between services become network calls, which are slower and can fail (Part 6) |
| Team autonomy: choose the technology and the pace inside your own service | Transactions across services are gone; you need sagas and eventual consistency (Sagas and the Outbox Pattern in Part 7) |
| Independent scaling: live interaction scales with connection count, sign-ups scale with request count | You need service discovery, centralized logs, and distributed tracing (Observability) |
| Fault isolation: an OOM in live interaction does not take payments down | API version compatibility has to be managed; you can no longer change every caller in one go |
| Security isolation: payments and personal data can live in a stricter environment | Testing gets harder: one service passing its tests does not mean the whole flow is correct |
The core value of microservices is independent deployment; most of the other benefits follow from it. If the services still have to be deployed together after the split, you have paid every cost without getting the main benefit.
The cost of a network call
A method call inside one process takes nanoseconds to microseconds. An HTTP call within one availability zone, with serialization and deserialization, usually takes around 1 millisecond, and it can fail.
In the monolith, the checkout page calls 8 modules in sequence. After you split them into 8 services:
- Latency grows by at least 8 milliseconds, and the long tail of every hop adds up (Latency, Throughput, and p99)
- If each service has 99.9% availability, 8 of them in series give 0.999⁸ ≈ 99.2%, which adds about 60 hours of downtime a year
- Every call needs a decision on timeouts, retries, circuit breakers, and fallbacks
So draw boundaries where calls are infrequent. If two services have to call each other back and forth several times for every request, they should probably be one service.
Draw boundaries by business capability
In 1968 Melvin Conway observed that the structure of a system copies the communication structure of the organization that designs it. Use it in reverse: make service boundaries match team boundaries. One team owns one or a few services, and everyday changes need no coordination across teams.
Draw boundaries by business capability, not by technical layer or by table. The bounded context from domain-driven design (DDD) is the usual tool: the same word has different meanings and rules in different contexts. In the sign-up context, a “sign-up” is about seats and state transitions. In the speaker settlement context, it is just one piece of revenue used to calculate the speaker’s share. In the recommendation context, it is a signal of a user’s interests.
The talk platform’s business capabilities:
| Capability | Responsible for | Data it owns |
|---|---|---|
| Talk catalog | Talk details, sessions, speaker bios | Talks, sessions |
| Sign-up | Seats, sign-up status | Sign-ups, waitlists |
| Payment | Charges, refunds, reconciliation with the payment provider | Payment records |
| Notification | Email, push notifications | Notification records, users’ notification preferences |
| Live interaction | Live questions, pushing seat counts | Questions, connection state |
| Speaker settlement | Monthly revenue share | Settlement records |
| Recommendation | Personalized recommendations | User behavior, models |
The question that tests the boundaries: how many modules does the most common requirement have to change at once? If most requirements touch only one, the boundaries are probably right. If every requirement touches three, the boundaries are in the wrong place.
Data ownership
Each piece of data has exactly one owner, and only the owner can read and write its tables directly. Other modules get the data in one of two ways:
- Call the owner’s API: the data is always current, but you add a runtime dependency
- Subscribe to the owner’s events and keep your own copy of what you need: speaker settlement subscribes to the “sign-up completed” and “refund completed” events and adds up each speaker’s revenue in its own table. It does not depend on the sign-up service being available; the cost is that the data lags behind (CQRS read models are the same idea)
A shared database is the most hidden kind of coupling. On the surface the services are separate, but any one service changing a column can break the others, and neither the compiler nor the tests will catch it.
Signs of a distributed monolith
- Shipping one service means shipping several other services at the same time
- Several services read and write the same tables in the same database
- One user request passes synchronously through five or six services
- The services share a library that contains the domain model, so changing one field means redeploying every service
- When one service goes down, most features stop working
- Every requirement needs a slot in several teams’ schedules
Modular monolith: get the boundaries right first
Inside the monolith, split the business capabilities into modules with clear boundaries:
- Modules talk to each other only through public APIs or events, and cannot reference each other’s internal classes
- Each module uses its own tables (ideally its own schema) and cannot query another module’s tables directly
- Automated tests check these rules, and the build fails when one is broken
This keeps the simplicity of a monolith: one deployment, in-process calls, local transactions, a single log. And once the boundaries are clear, splitting a module out later only means replacing in-process calls with network calls and in-process events with a broker. It is not a redesign.
Boundaries are easiest to get wrong at the start. Moving a module boundary inside a monolith is just a refactor; moving a boundary between microservices is an API and data migration across teams.
How to split: the strangler fig pattern
Martin Fowler named the strangler fig pattern after the strangler fig plant. Instead of rewriting the whole system, you move features to new services step by step: put a routing layer in front and shift the traffic over one feature at a time, until that part of the old system can be removed.
Which one first? Pick a module that clearly benefits from being split out and whose boundaries are already stable:
- Live interaction: it behaves completely differently at runtime (many long-lived connections, scaling with connection count; see Real-Time Updates), and its failures should not affect sign-ups
- Payment: it needs stricter security controls and auditing; splitting it out shrinks the scope that has to comply with financial regulations
The core parts that often change together, such as the talk catalog and sign-ups, can stay in the monolith for a long time.
Comparing options
| Option | Fits | Main cost |
|---|---|---|
| Monolith (no clear module boundaries) | Small teams; early products whose requirements are still changing fast | Hard to change and to split once it grows |
| Modular monolith | One to a few teams; most business systems | Still deployed together and scaled together; a memory leak in one module affects everything |
| Microservices | Several teams need independent deployment; different parts have very different scaling, availability, or security needs | Network, data consistency, operations, and observability costs all go up |
| Modular monolith + a few split-out services | Most growing systems | You maintain the tools and processes for both models |
The talk platform’s choice: first turn the monolith into a modular monolith, where sign-up, payment, and speaker settlement communicate through events and each owns its own tables. Then split live interaction and payment out into separate services, and keep the rest in the monolith. The monthly report now comes from a read model maintained by the speaker settlement module, instead of querying the sign-up tables directly.
In Java
1. Module structure
Spring Modulith treats the direct subpackages of the package that holds the main application class as modules. Packages below those subpackages are, by default, the module’s internal implementation:
com.example.lectures
├── LectureApplication.java
├── catalog/ talk catalog module
├── registration/ sign-up module
│ ├── RegistrationService.java public API
│ ├── RegistrationCompleted.java public event
│ ├── package-info.java
│ └── internal/ internal implementation, other modules cannot reference it
│ ├── RegistrationRepository.java
│ └── SeatAllocator.java
├── payment/
├── notification/
└── settlement/// registration/package-info.java: the sign-up module may depend only on the talk catalog
@org.springframework.modulith.ApplicationModule(allowedDependencies = "catalog")
package com.example.lectures.registration;2. Let the build check the boundaries
class ModularityTests {
@Test
void modulesRespectTheirBoundaries() {
// No cycles between modules, no references to another module's internal package, dependencies only on allowed modules
ApplicationModules.of(LectureApplication.class).verify();
}
}If someone injects registration.internal.RegistrationRepository directly into the notification module, this test fails, and the build fails with it. The boundaries no longer depend on code review alone.
3. Modules talk through events
// registration module: the public event
public record RegistrationCompleted(UUID eventId, long registrationId, long memberId, long lectureId) {
}
@Service
public class RegistrationService {
private final RegistrationRepository registrations;
private final ApplicationEventPublisher events;
public RegistrationService(RegistrationRepository registrations, ApplicationEventPublisher events) {
this.registrations = registrations;
this.events = events;
}
@Transactional
public Registration register(long lectureId, long memberId) {
Registration registration = registrations.save(Registration.create(lectureId, memberId));
events.publishEvent(new RegistrationCompleted(UUID.randomUUID(), registration.id(), memberId, lectureId));
return registration;
}
}// notification module: needs to know nothing about the sign-up module's internals
@Component
class ConfirmationMailer {
private final MailSender mailSender;
ConfirmationMailer(MailSender mailSender) {
this.mailSender = mailSender;
}
@ApplicationModuleListener
void on(RegistrationCompleted event) {
mailSender.sendConfirmation(event.memberId(), event.registrationId(), event.eventId());
}
}@ApplicationModuleListeneris an event listener that runs after the transaction commits, asynchronously, in a new transaction. The sign-up transaction does not roll back because sending the email failed, and no email goes out after a sign-up rolls back- Once you add
spring-modulith-starter-jdbc, the Event Publication Registry writes a “pending delivery” record in the same transaction as the sign-up, and marks it complete only after the listener succeeds. If the application crashes midway, incomplete records can be redelivered throughIncompleteEventPublications. This is an in-process Outbox. Redelivery means the listener may run twice, so the mailer useseventIdas the idempotency key (Idempotency and Idempotency Keys) - When the notification module one day has to become a separate service, add
@Externalizedto the event and Spring Modulith sends it to Kafka or RabbitMQ. The sign-up module’s code does not change:
@Externalized("registration-events::#{#this.lectureId()}") // topic and routing key
public record RegistrationCompleted(UUID eventId, long registrationId, long memberId, long lectureId) {
}The code above follows the official Spring Modulith 2.1 and Spring Framework 7 documentation; it has not been compiled or run.
Pitfalls and gotchas
- Splitting for the sake of “microservices”: with no concrete need for independent deployment, independent scaling, or isolation, all you get is the cost of a distributed system
- Splitting before the boundaries are stable: the product direction is still changing, the boundaries change with it, and a refactor across services costs several times more than a refactor inside a monolith
- Services that are too fine-grained: one service has one table and a few CRUD APIs, and one feature touches ten services
- A shared database: the services are separate, but the coupling is still in the tables
- A shared domain-model library: every service depends on the same version of the
Registrationclass, so changing one field means redeploying all of them - Synchronous call chains: A calls B, B calls C, C calls D. If any one of them is slow, the whole chain is slow, and the availabilities multiply
- Splitting first and adding observability later: only after the split do you find that you cannot trace which services a request went through, and during an incident all you can do is guess
- Underestimating data migration: moving the code out is only half of it. Moving the data from the shared tables into the new service’s database, and keeping both sides consistent during the migration, is what takes the most time
- The organization does not change along with it: whether one team owns ten services or ten teams share one service, Conway’s law bends the system’s structure toward the shape of the organization
- Expecting microservices to solve performance problems: performance problems are usually about queries, indexes, and caching. Splitting into microservices adds network round trips and often makes things slower
Security
- A larger attack surface: a monolith has one external entry point; microservices have dozens of services, dozens of network endpoints, and dozens of sets of credentials. Every one of them needs patching, TLS configuration, and secrets management
- The internal network does not mean trusted: “Only internal services call this API, so it does not check permissions” is a common source of vulnerabilities. An attacker who gets into any machine on the internal network can call it directly. Services have to verify each other’s identity (with mTLS, for example), and every service has to do its own authorization instead of relying on the API gateway or the BFF having checked (Part 8 covers in detail how BOLA travels through microservices)
- Scattered authorization logic: a monolith checks “can this user see this sign-up” in one place. After you split into microservices, that check has to be repeated in every service that holds sign-up data, with the same rules everywhere. Miss one, and you have an unauthorized access vulnerability
- Events copy personal data: speaker settlement, recommendations, and notifications all subscribe to sign-up events and keep copies in their own databases. When a user asks for their personal data to be deleted, every copy has to be dealt with. Keep events to IDs where you can, and let the owner serve lookups of the personal data
- Isolation is a security advantage of microservices: put payments and personal data in separate services, separate network segments, and separate database accounts, so that when another service is compromised the attacker cannot reach them directly. This is a good reason to split, and it can shrink the scope that has to comply with standards such as PCI DSS
- The limits of a modular monolith: module boundaries exist only at the source code level. If any module has a remote code execution vulnerability, the attacker gets the memory of the whole process and a database connection that can reach every table. When you need real isolation, split into separate processes and separate database accounts
- Supply chain: every service has its own dependencies and container image. Standardize the base images, scan dependencies for vulnerabilities automatically, and generate SBOMs; otherwise patching one vulnerability means chasing it through dozens of repositories
When to use it, and when not to
- Use a modular monolith: most new systems, and systems built by one to a few teams. Get the boundaries right first; they are the foundation for every later choice
- Split out microservices: when you have a concrete reason, such as several teams held up by the same release process, one part with very different scaling or availability needs, or a need for security or regulatory isolation. And the team already has automated deployment, centralized logs and tracing, and authentication between services
- When to re-evaluate: release frequency drops because of coordination costs; failures in one module keep affecting other modules; one module’s resource needs drift further and further from the rest
- Don’t split: there is only one team; the boundaries are still changing; the only motive for splitting is “everyone else does it” or “the technology is newer”
References
- Melvin E. Conway, “How Do Committees Invent?”, Datamation, 1968: https://www.melconway.com/Home/Committees_Paper.html
- Martin Fowler, “MonolithFirst”, 2015: https://martinfowler.com/bliki/MonolithFirst.html
- Martin Fowler, “StranglerFigApplication”: https://martinfowler.com/bliki/StranglerFigApplication.html
- Martin Fowler, “MicroservicePrerequisites”, 2014: https://martinfowler.com/bliki/MicroservicePrerequisites.html
- Sam Newman, Building Microservices, 2nd Edition, O’Reilly, 2021; Monolith to Microservices, O’Reilly, 2019
- Matthew Skelton, Manuel Pais, Team Topologies, IT Revolution, 2019
- Eric Evans, Domain-Driven Design, Addison-Wesley, 2003
- Spring Modulith Reference Documentation: https://docs.spring.io/spring-modulith/reference/
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments