Microservices solve a real problem: many teams, changing fast, needing to ship without waiting on each other. They also carry a real cost. Every function call becomes a network call. Every transaction becomes a distributed one. Every release becomes a coordination exercise.
When the problem microservices solve is not your problem, you pay the cost and get nothing back.
This article covers why teams reverse course, what a modular monolith actually is, the rules that keep it from rotting into a big ball of mud, a code walk-through, a step-by-step migration plan, and the trade-offs you accept. It also covers when microservices are still the right call, so you can decide with facts and not fashion.
TL;DR
Microservices work when you have independent teams, independent data, stable contracts, and a mature platform. When those are missing, you get a distributed monolith: all the complexity, none of the independence.
A modular monolith is one deployable unit with hard internal boundaries. Each module owns its data, exposes a small public API, and hides everything else.
Boundaries only hold if tools enforce them. Convention alone fails within months.
You keep most of the benefits teams want from services: clear ownership, isolated change, and testable parts. You drop the network, the distributed transactions, and most of the operational overhead.
Design modules so any of them could be extracted later. That keeps your options open without paying for them today.
Measure before and after. Deploy frequency, lead time, change failure rate, recovery time, cost per request, and pages per week tell you whether the move worked.
Table of contents
Why microservices look right on paper
The problems that show up in production
What a modular monolith is, and what it is not
Seven rules that make it work
A code walk-through
Data: ownership, transactions, and events
Migration plan: from services back to modules
Testing strategy
Deploying, scaling, and owning a modular monolith
What you give up
Pitfalls of the modular monolith
When microservices still win
Measure the result
Checklist
1. Why microservices look right on paper
The case for microservices is strong, and it is worth stating fairly.
Independent deployment. A team ships its service without waiting for others.
Independent scaling. The busy part scales without scaling the rest.
Fault isolation. One service failing does not have to take down everything.
Technology freedom. Each service can use the language and database that suit it.
Team autonomy. Small teams own small codebases and move fast.
Every one of these benefits rests on assumptions. Check them honestly against your own situation:
| Assumption | What it means in practice |
|---|---|
| Teams are independent | Teams can plan and ship without asking other teams |
| Data is independent | Each service owns its data and no one reads another's tables |
| Contracts are stable | Interfaces change rarely and change safely |
| Scaling needs differ | Parts of the system have truly different load shapes |
| The platform is mature | CI/CD, tracing, service discovery, secrets, and on-call are solved |
If three or four of these are false, the benefits do not appear, but the costs do. That mismatch is where most regret comes from.
Microservices are an organizational pattern as much as a technical one. They map well to a company with many teams and clear domain ownership. They map badly to a single team of eight that splits its code into fifteen services because the diagrams looked clean.
2. The problems that show up in production
None of these problems is a surprise to people who have run services at scale. They become painful when the team is too small, or the domain too tangled, to absorb them.
2.1 The distributed monolith
This is the most common failure. The system is split into services, but they cannot live apart:
Services must be deployed together, in a specific order.
A change in one service requires matching changes in three others.
Services share a database, or read each other's tables.
One service calls another, which calls another, in a synchronous chain.
You pay for network calls, serialization, and deployment pipelines. You get none of the independence. It is a monolith with a network in the middle.
A quick test: pick your last ten changes. How many touched more than one service? If it is most of them, your boundaries are in the wrong place, or the services are too fine-grained for your domain.
2.2 The network is not a function call
In a monolith, calling another part of the system is a function call. It is fast, it either returns or throws, and it shares a transaction.
Across a network, every call can be slow, fail, time out while still succeeding on the other side, or arrive twice after a retry. You now need to design for each of these:
Timeouts on every call.
Retries with backoff and jitter.
Idempotency keys, so a retry does not charge a customer twice.
Circuit breakers, so a failing dependency does not drag down its callers.
Fallback behavior, so a missing answer does not become an outage.
Availability also compounds in the wrong direction. If each service in a serial chain is 99% available, five in a row give you roughly 95% (0.99 to the power of 5). The more synchronous hops in a request path, the worse the end result.
None of this is impossible to handle. It is work, and it is work that adds nothing to your product.
2.3 Data consistency and sagas
Inside one database, "create the order, reserve the stock, record the payment" is one transaction. It all works or none of it does.
Across three services with three databases, there is no shared transaction. You need a saga: a sequence of local transactions with compensating actions for failure. If payment fails after stock is reserved, something must release the stock. If that release fails, something must retry it. If the retry fails, someone must be alerted.
Sagas are a legitimate tool, but they are hard to design, hard to test, and hard to debug at 3 a.m. Teams often build them for flows that never needed to be distributed in the first place.
2.4 Contract versioning and deploy order
When an interface changes, every caller must handle both versions during the rollout. You need backward-compatible changes, versioned APIs, consumer-driven contract tests, and deprecation schedules.
Done well, this is a discipline. Done under deadline pressure, it becomes version skew: service A expects a field that service B stopped sending an hour ago. These bugs show up only in production, because no test environment ever matches the exact combination of versions that is live.
2.5 Testing and local development
Testing a feature that spans five services needs one of these:
A shared staging environment that is always slightly broken because someone else is deploying to it.
A heavy local setup with containers for every service, and a laptop that sounds like a jet engine.
Mocks for every dependency, which drift from reality.
End-to-end tests become slow and flaky. Developers stop running them. Bugs move later in the pipeline, where they cost more.
Onboarding also gets slower. A new engineer needs to understand the repos, the deploy flow, the local stack, and the service map before shipping a small change.
2.6 The observability tax
With one process, a stack trace tells most of the story. With many services, you need:
Distributed tracing with context propagated across every call and queue.
Centralized, structured logging with correlation IDs.
Per-service dashboards and alerts.
Service maps to understand who calls whom.
All of this is good engineering, and all of it costs money and time. Observability vendors often price by volume, and a chatty microservice system produces a lot of volume. For a small team, the observability setup can become a part-time job.
2.7 Cost: infrastructure and cognitive
Infrastructure cost grows in less obvious ways than people expect:
Each service has a baseline footprint: containers, replicas for availability, sidecars, and load balancers, even when idle.
Network traffic between services, between zones, and through gateways adds up.
Duplicated work: every service has its own build, pipeline, config, secrets, dashboards, and runbooks.
Cognitive cost is larger still. Engineers must hold more of the system in their heads: which service owns what, how they talk, and what happens when each fails. Smaller teams feel this most, because each person touches many services.
2.8 On-call and ownership blur
When a user-facing error crosses four services, who owns it? The first person paged often cannot fix it, and must find the right team, who may also be asleep. Incident time goes into finding the cause across systems, not fixing it.
Combine this with a small team that owns many services, and the on-call rotation becomes a burden that drives people away.
2.9 Public examples worth reading
Several well-known engineering teams have written publicly about this trade-off. Segment described moving a set of per-destination services back into a single service after the operational overhead outweighed the benefits. Shopify has described running a very large Rails application as a modular monolith and building tooling to enforce internal boundaries. A 2023 write-up from an Amazon Prime Video team described consolidating a video quality monitoring pipeline from a distributed design into a single process, and reported large cost savings. Read the originals for the details, since each case has its own context. The shared lesson is that architecture should follow the actual problem, not the other way around.
3. What a modular monolith is, and what it is not
A modular monolith is a single deployable application whose code is divided into modules with strict boundaries. Think of it as microservices' discipline without microservices' network.
Each module:
Represents a business capability, such as Orders, Billing, Inventory, or Identity.
Exposes a small, explicit public API.
Hides its internals, so other modules cannot import them.
Owns its data, and no other module reads or writes its tables.
Communicates with other modules only through public APIs or events.
+-----------------------------------------------------+
| One deployable app |
| |
| +---------+ +---------+ +-----------+ |
| | Orders |--->| Billing | | Inventory | |
| | [API] | | [API] | | [API] | |
| | internal| | internal| | internal | |
| | + data | | + data | | + data | |
| +----+----+ +---------+ +-----------+ |
| | ^ |
| +------------------------------+ |
| calls only through public APIs / events |
+-----------------------------------------------------+
What it is not
It is not a layered monolith. A classic layered app organizes code by technical role: controllers, services, repositories. Anyone can call anything. A change to one feature touches every layer, and boundaries between features do not exist.
It is not a big ball of mud. A ball of mud has no enforced structure, and any file can import any other file. A modular monolith is structured on purpose, and the structure is checked automatically.
It is not a stepping stone you must leave. Many teams stay on it for years, and some forever.
A comparison
| Layered monolith | Modular monolith | Microservices | |
|---|---|---|---|
| Deployable units | One | One | Many |
| Organized by | Technical layer | Business capability | Business capability |
| Boundaries enforced | No | Yes, by tooling | Yes, by the network |
| Data ownership | Shared | Per module | Per service |
| Cross-boundary call | Function call | Function call via public API | Network call |
| Cross-boundary transaction | Easy | Possible, with care | Hard (sagas) |
| Independent deploy | No | No | Yes |
| Independent scaling | No | Limited (by process role) | Yes |
| Operational overhead | Low | Low | High |
4. Seven rules that make it work
Without rules, a modular monolith decays into a ball of mud within a year. These seven rules, enforced by tools, prevent that.
Rule 1: Split by business capability, not by technical layer.
Use domain-driven design thinking. Find bounded contexts: parts of the business where words have one clear meaning. "Order" in Sales and "Order" in Fulfillment may deserve separate modules with separate models.
Start with fewer, larger modules. It is easier to split a module later than to merge two that were split wrongly.
Rule 2: Every module has one public entry point.
Other modules may import only from that entry point. Everything else is internal.
Rule 3: Modules own their data.
No module reads or writes another module's tables. No foreign keys across module boundaries. No joins across modules in SQL. If you need data from another module, ask its API or react to its events.
Rule 4: Dependencies point one way and never form cycles.
If Orders depends on Inventory, Inventory must not depend on Orders. When two modules need each other, you have found a boundary problem. Either merge them, extract a third concept, or invert one direction with events.
Rule 5: Share very little.
A shared kernel is allowed, but keep it tiny: basic types such as IDs, money, and time; and cross-cutting plumbing such as logging and the event bus interface. A shared utils folder that grows without limit is how the ball of mud returns.
Rule 6: Pass data across boundaries as plain contracts.
Public APIs accept and return simple data types (DTOs), not internal entities. If Orders receives Inventory's internal database entity, it is now coupled to Inventory's internals.
Rule 7: Enforce the rules with automation.
Architecture tests and import linters run in CI and fail the build. Code review is not enough, because people miss things and deadlines win. A rule that is not checked by a machine is a suggestion.
5. A code walk-through
The examples use TypeScript on Node, but the ideas carry over to any language. Equivalent tooling for other stacks is listed at the end of this section.
5.1 Folder structure
src/
app/
compose.ts # wires modules together (composition root)
main.ts # starts the process
shared-kernel/
ids.ts
money.ts
event-bus.ts # interface only
unit-of-work.ts # interface only
modules/
orders/
index.ts # PUBLIC API: the only importable file
internal/
place-order.ts
order-repository.ts
http-routes.ts
billing/
index.ts
internal/
inventory/
index.ts
internal/
The rule: code outside modules/orders/ may import modules/orders (which resolves to index.ts), and nothing under modules/orders/internal/.
5.2 A public API
// src/modules/inventory/index.ts
import type { UnitOfWorkContext } from "../../shared-kernel/unit-of-work";
import type { EventBus } from "../../shared-kernel/event-bus";
export type ReserveStockInput = {
orderId: string;
items: { sku: string; quantity: number }[];
};
export type ReserveStockResult =
| { ok: true; reservationId: string }
| { ok: false; reason: "OUT_OF_STOCK" | "UNKNOWN_SKU"; sku: string };
export interface InventoryApi {
reserveStock(
input: ReserveStockInput,
ctx?: UnitOfWorkContext
): Promise<ReserveStockResult>;
releaseStock(reservationId: string, ctx?: UnitOfWorkContext): Promise<void>;
}
export type InventoryDeps = {
db: import("../../shared-kernel/db").Db;
events: EventBus;
};
export function createInventoryModule(deps: InventoryDeps): InventoryApi {
// implementation lives in ./internal and is never exported
return require("./internal/create").create(deps);
}
Three things to notice. The API is an interface, so callers depend on a contract and not on a class. The inputs and outputs are plain data. The result type models expected failures as values, so callers handle them explicitly instead of catching strings.
(In real code, use a normal static import for the factory. The require here only keeps the snippet short.)
5.3 A module using another module
// src/modules/orders/internal/place-order.ts
import type { InventoryApi } from "../../inventory";
import type { BillingApi } from "../../billing";
import type { UnitOfWork } from "../../../shared-kernel/unit-of-work";
type Deps = {
uow: UnitOfWork;
inventory: InventoryApi;
billing: BillingApi;
orders: OrderRepository;
};
export async function placeOrder(deps: Deps, cmd: PlaceOrderCommand) {
return deps.uow.run(async (ctx) => {
const order = await deps.orders.insert(cmd, ctx);
const stock = await deps.inventory.reserveStock(
{ orderId: order.id, items: cmd.items },
ctx
);
if (!stock.ok) {
throw new OrderRejected(stock.reason, stock.sku);
}
const payment = await deps.billing.authorize(
{ orderId: order.id, amount: order.total, customerId: cmd.customerId },
ctx
);
if (!payment.ok) {
throw new OrderRejected("PAYMENT_DECLINED");
}
await deps.orders.markConfirmed(order.id, ctx);
return order;
});
}
Note the imports. Orders imports only types from ../../inventory and ../../billing, the public entry points. It never reaches into inventory/internal.
Also note what the unit of work buys you: if payment fails, the order insert and stock reservation roll back in one database transaction. In a microservices design, this flow needs a saga. Here, it needs a rollback.
5.4 The composition root
All wiring happens in one place. Modules never construct each other.
// src/app/compose.ts
import { createInventoryModule } from "../modules/inventory";
import { createBillingModule } from "../modules/billing";
import { createOrdersModule } from "../modules/orders";
export function compose(infra: Infra) {
const inventory = createInventoryModule({ db: infra.db, events: infra.events });
const billing = createBillingModule({ db: infra.db, events: infra.events });
const orders = createOrdersModule({
uow: infra.uow,
inventory,
billing,
events: infra.events,
});
return { orders, inventory, billing };
}
This is where you will later swap an in-process module for a network client if you ever extract a service. Callers see the same interface either way.
5.5 Enforce the boundaries
Use dependency-cruiser (or an equivalent) to fail the build when someone breaks a rule.
// .dependency-cruiser.js
module.exports = {
forbidden: [
{
name: "no-deep-imports-into-modules",
comment: "Import another module only through its index file.",
severity: "error",
from: { path: "^src/modules/([^/]+)/" },
to: {
path: "^src/modules/([^/]+)/internal/",
pathNot: "^src/modules/$1/",
},
},
{
name: "no-circular-dependencies",
severity: "error",
from: {},
to: { circular: true },
},
{
name: "shared-kernel-is-a-leaf",
comment: "The shared kernel must not depend on any module.",
severity: "error",
from: { path: "^src/shared-kernel/" },
to: { path: "^src/modules/" },
},
],
};
Run it in CI:
npx depcruise src --config .dependency-cruiser.js
If a developer writes import { x } from "../../inventory/internal/stock-repo" inside Orders, the pipeline fails with the rule name and file. Fast feedback keeps the boundaries real.
5.6 Equivalent tools in other stacks
| Stack | Boundary enforcement options |
|---|---|
| Java / Kotlin | ArchUnit, Spring Modulith, Java modules |
| .NET | NetArchTest, separate projects with restricted references |
| Python | import-linter, per-package public __init__ conventions |
| Ruby | Packwerk |
| Go |
internal/ directories, separate packages with small exported surfaces |
| JS / TS monorepos | dependency-cruiser, ESLint boundary rules, Nx module boundaries |
Tool features change over time, so check current documentation before you adopt one.
6. Data: ownership, transactions, and events
Data is where a modular monolith succeeds or fails. If modules share tables, the boundaries are fiction.
6.1 One database, separate schemas
You do not need a database per module on day one. One database with one schema per module gives most of the benefit:
CREATE SCHEMA orders;
CREATE SCHEMA billing;
CREATE SCHEMA inventory;
CREATE TABLE orders.orders (
id UUID PRIMARY KEY,
customer_id UUID NOT NULL,
status TEXT NOT NULL,
total_cents BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
Rules for the schema:
Each module reads and writes only its own schema.
No foreign keys across schemas. Reference other modules' entities by ID only, and treat the ID as an opaque value.
No joins across schemas. If a screen needs data from two modules, one module calls the other's API, or a read model is built from events.
You can enforce this at the database level with separate roles per module:
-- One role per module; each role can only touch its own schema.
CREATE ROLE orders_app LOGIN;
GRANT USAGE ON SCHEMA orders TO orders_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA orders TO orders_app;
ALTER DEFAULT PRIVILEGES IN SCHEMA orders
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO orders_app;
Give each module its own connection pool and credentials, and a stray query against another module's tables fails with a permission error. Set the credentials through your secrets system, not in the migration file.
Per-module roles cost some extra setup and make cross-module transactions harder, because transactions are per connection. Many teams start with one role and rely on the import linter plus a SQL review rule, then add roles for the modules where boundaries matter most.
6.2 Transactions across modules
The in-process model gives you a choice that microservices do not:
One transaction for a use case. Pass a unit-of-work context into each module API, as in the walk-through. All changes commit or roll back together. This is simple and strongly consistent, at the cost of a little coupling between modules in the same request.
Separate transactions with events. Each module commits its own change and publishes an event. Other modules react. This is more decoupled and eventually consistent.
A sensible default: use one transaction when the business rule demands atomicity (an order must not be confirmed without a payment authorization). Use events for reactions that can happen a moment later (send a confirmation email, update a search index, refresh a read model).
6.3 Events inside the process
An in-process event bus is a small interface:
// src/shared-kernel/event-bus.ts
export type DomainEvent = {
id: string;
type: string;
occurredAt: string;
payload: unknown;
};
export interface EventBus {
publish(event: DomainEvent): Promise<void>;
subscribe(type: string, handler: (e: DomainEvent) => Promise<void>): void;
}
If a handler must run reliably after a commit, use the transactional outbox pattern. The module writes the event to an outbox table in the same transaction as its data change. A dispatcher then publishes it.
CREATE TABLE orders.outbox (
id BIGSERIAL PRIMARY KEY,
type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
export async function dispatchOutbox(db: Db, bus: EventBus, batch = 50) {
await db.transaction(async (tx) => {
const rows = await tx.query(
`SELECT id, type, payload
FROM orders.outbox
WHERE published_at IS NULL
ORDER BY id
LIMIT $1
FOR UPDATE SKIP LOCKED`,
[batch]
);
for (const row of rows) {
await bus.publish({
id: String(row.id),
type: row.type,
occurredAt: new Date().toISOString(),
payload: row.payload,
});
await tx.query(
`UPDATE orders.outbox SET published_at = now() WHERE id = $1`,
[row.id]
);
}
});
}
Delivery here is at least once, so handlers must be idempotent. Use the event ID to detect and skip duplicates.
The outbox has a bonus: if you ever extract a module into a service, the same events can go out to a message broker with no change to the module's logic.
6.4 Reads that span modules
Screens often need data from several modules, such as an order list that shows customer names and payment status. Avoid cross-schema joins. Options, from simplest to most complex:
API composition. A query layer calls each module's API and merges the results in memory. Fine for small lists.
Read models. A module builds a denormalized view from events it receives, stored in its own schema. Fast reads, eventual consistency.
A dedicated reporting store. For heavy analytics, replicate data to a warehouse. This is a separate concern from your transactional boundaries.
7. Migration plan: from services back to modules
Going from microservices to a modular monolith is a refactor, not a rewrite. Do it in small, reversible steps.
Step 1: Measure before you touch anything
Record your baseline: deploy frequency, lead time for changes, change failure rate, time to recover, infrastructure cost, and pages per week. Without a baseline, you cannot show the move worked, and you cannot argue with the person who says it did not.
Step 2: Find the merge candidates
Not every service should merge. Look for these signals:
Services that always deploy together or in a fixed order.
Services that change together in the same pull requests or in linked ones. Check your history.
Chatty pairs: many synchronous calls between the same two services.
Shared tables, or one service reading another's database.
Flows that need sagas but are conceptually one business transaction.
Services owned by the same small team.
Services with no distinct scaling or isolation need.
Rank candidates by how much pain they cause. Start with the most painful pair.
Step 3: Define the target modules
Draw the target map before moving code. For each module, write down its responsibility, its public API, the data it owns, and the events it publishes and consumes. Keep the module count small at first.
Step 4: Put the code in one repository
If services live in separate repositories, consolidate into a monorepo with the module structure from section 5. Keep history if you can, so blame and context are not lost. Set up CI for the monorepo with affected-only builds and tests, so build time does not balloon.
Step 5: Hide the network behind an interface
Before merging, make sure callers depend on an interface, not on an HTTP client. If a caller uses fetch against the other service directly, wrap that in a class that implements the module's API:
// Transitional: same interface, HTTP implementation
class InventoryHttpClient implements InventoryApi {
constructor(private baseUrl: string) {}
async reserveStock(input: ReserveStockInput) {
const res = await fetch(`${this.baseUrl}/reservations`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(input),
});
return (await res.json()) as ReserveStockResult;
}
async releaseStock(reservationId: string) {
await fetch(`${this.baseUrl}/reservations/${reservationId}`, {
method: "DELETE",
});
}
}
This step is safe, because behavior does not change. It prepares the swap.
Step 6: Swap the adapter
Move the service's code into a module and change the composition root:
// Before
const inventory = new InventoryHttpClient(process.env.INVENTORY_URL!);
// After
const inventory = createInventoryModule({ db: infra.db, events: infra.events });
The calling code does not change. A network hop becomes a function call. You can deploy this behind a feature flag and switch back if something looks wrong.
Step 7: Handle the data
You have two paths:
Keep the database separate first. The module still connects to its old database. This is the safest first move. Merge the databases later, or never.
Consolidate into one database with schemas. Move tables into a per-module schema. Use a migration with a tested rollback, and run a dual-write or a replication period if downtime is not acceptable.
Do not merge data and code in the same release. Change one thing at a time.
Step 8: Replace sagas with transactions where it makes sense
Once two modules share a database, flows that needed a saga may become a single transaction. Simplify them one at a time, with tests, and remove the compensation code that is no longer needed. Keep events for reactions that are truly asynchronous.
Step 9: Retire the old pipeline and infrastructure
Remove the old service's deployment, dashboards, alerts, secrets, and load balancers. Leftover infrastructure is a hidden cost and a security risk. Update runbooks and the on-call guide.
Step 10: Measure again
Compare against your baseline after a few weeks of real traffic. Share the numbers with the team. If a specific module hurt performance or reliability, you have data to decide what to do next.
Migration safety tips
Move one pair of services at a time.
Keep every step reversible with a flag or a rollback.
Run the old and new paths side by side where possible, and compare results.
Avoid freezing feature work for a long "big migration." Interleave it with product work.
Watch latency and error rates after each step.
8. Testing strategy
A modular monolith changes your test mix for the better.
Module tests. Test each module through its public API with a real database (a container or an in-memory equivalent that matches production behavior). Replace other modules with fakes that implement their public interfaces.
const fakeInventory: InventoryApi = {
async reserveStock() {
return { ok: true, reservationId: "res-1" };
},
async releaseStock() {},
};
Contract tests at module boundaries. A shared test suite runs against both the real module and its fake, so the fake never drifts from reality. This replaces consumer-driven contract testing across services.
Architecture tests. The dependency checks from section 5.5 run on every pull request. They are fast and catch boundary breaks before review.
A small number of end-to-end tests. Because the whole system runs in one process, end-to-end tests are easier to write and much less flaky. Keep them for critical user journeys.
Local development. One process, one database, one command. New engineers can run the whole system and ship a first change quickly.
9. Deploying, scaling, and owning a modular monolith
9.1 One artifact, several roles
A single deployable does not mean a single runtime shape. You can run the same build in different roles and scale each role on its own:
// src/app/main.ts
const role = process.env.APP_ROLE ?? "web";
const app = compose(await createInfra());
if (role === "web") startHttpServer(app);
if (role === "worker") startJobWorkers(app);
if (role === "scheduler") startScheduler(app);
Run ten web replicas, three worker replicas, and one scheduler. You get independent scaling of request handling and background work without separate codebases. A heavy module, such as report generation, can run on workers with its own resource limits.
9.2 Deployment safety without independent deploys
You lose per-service deploys, so make whole-app deploys safe and boring:
Feature flags so code can ship dark and turn on gradually.
Blue-green or canary releases with automatic rollback on error spikes.
Backward-compatible database migrations, using expand then contract steps.
Fast pipelines. Use affected-only builds and tests, caching, and parallel test runs.
Small, frequent deploys work well here. A deploy with ten changes is risky. A deploy with one change is not.
9.3 Ownership without separate repos
Ownership is what gives microservices their team autonomy. Keep it with modules:
# CODEOWNERS
/src/modules/orders/ @your-org/orders-team
/src/modules/billing/ @your-org/billing-team
/src/modules/inventory/ @your-org/inventory-team
/src/shared-kernel/ @your-org/platform-team
Changes to a module need review from its owners. Changes to the shared kernel need extra care and review from the platform team. This preserves clear accountability.
9.4 Performance
In-process calls remove network latency, serialization, and most of the partial-failure handling on those paths. Request paths that crossed four services can become plain function calls. Watch for the opposite risk: one module's slow query or memory leak now affects the whole process. Use per-module metrics, timeouts on external calls, and bulkhead patterns such as separate worker pools for heavy jobs.
10. What you give up
A fair article must include the costs. These are real.
| You give up | Why it matters | Mitigation |
|---|---|---|
| Independent deploys | One bad change can block everyone's release | Feature flags, fast CI, small PRs, trunk-based development |
| Fine-grained scaling | You scale the whole app, though heavy modules waste memory | Process roles, workers, vertical tuning; extract a module if the need is proven |
| Strong fault isolation | A crash or leak in one module can affect all | Timeouts, bulkheads, resource limits, per-module metrics |
| Language and stack freedom | One runtime for the app | Accept it; extract a service for the rare case that needs another stack |
| Hard boundaries by the network | Developers can break boundaries by accident | Architecture tests in CI, code owners, review discipline |
| Build and test speed at large size | A big codebase can slow CI | Affected-only builds, caching, module-level test targets |
If several of these hurt a lot, that is useful information. It may mean one or two modules deserve to become services.
11. Pitfalls of the modular monolith
Teams that adopt this pattern still fail in predictable ways.
Boundary erosion. Someone needs a quick fix, imports an internal file, and the linter is turned off "just for now." Fix: make the rules non-negotiable in CI, and review any suppression.
The giant shared or common module. Everything unclear goes there, and soon every module depends on it. Fix: keep the shared kernel tiny, with a strict review process for additions.
God modules. One module grows until it holds half the system. Fix: watch size and change rate, and split when a module has more than one reason to change.
Shared tables by stealth. A report query joins across schemas "because it is faster." Fix: ban cross-schema queries in review, use database roles, and build read models for reports.
Circular dependencies. Two modules call each other. Fix: treat the cycle as a design signal. Merge, extract a shared concept, or invert one direction with an event.
Too many modules too early. Twenty modules for a small domain recreates microservice overhead in code. Fix: start coarse and split with evidence.
Anemic public APIs. Modules expose raw CRUD for their tables, which leaks internals. Fix: expose business operations ("reserve stock"), not data access ("update row").
Ignoring the database. Code boundaries are clean while the schema is a tangle. Fix: treat data ownership as part of the boundary.
12. When microservices still win
Choosing a modular monolith is not an argument against services. It is an argument for earning each service. Extract a module into its own service when you have evidence of at least one of these:
A truly different scaling profile. A module needs very different resources or traffic handling than the rest, and process roles are not enough.
A different runtime need. It needs a different language or runtime, such as a machine learning workload or a specialized media pipeline.
A hard isolation requirement. Compliance, security, or fault isolation demands a separate failure and access boundary, such as payment card data.
Independent teams at scale. You have many teams that are blocked by shared release trains, and clear, stable domain boundaries between them.
Different release cadence. A part of the system must change daily while another must change quarterly, with strong controls.
Even then, extract one module at a time and keep the interface the same, as shown in the migration steps in reverse:
The module already has a public API, owns its data, and uses events. That is the preparation.
Build the service around the module's code and expose the API over the network.
Write an HTTP or message-based adapter that implements the same interface.
Swap the adapter in the composition root behind a flag.
Move the module's schema to its own database.
Remove the in-process module from the monolith.
If your modules are clean, extraction is a mechanical job. That is the real payoff of the modular monolith: you keep the option without paying for it early.
13. Measure the result
Pick metrics before the change, and review them after. Use the four widely used delivery metrics, plus cost and operational load:
| Metric | What it tells you |
|---|---|
| Deployment frequency | How often you ship to production |
| Lead time for changes | Time from commit to production |
| Change failure rate | Share of deploys that cause a failure |
| Time to restore service | How fast you recover from incidents |
| Infrastructure cost per request or per active user | Whether simplification saved money |
| Pages or alerts per week | On-call load |
| Time to first merged change for a new engineer | Onboarding cost |
| Share of changes touching more than one deployable | Whether coupling dropped |
Be honest with the numbers. If delivery metrics improve and cost drops, you have a clear win. If a metric gets worse, such as lead time because the CI pipeline grew, treat it as a problem to fix with affected-only builds and caching, not as a reason to give up.
14. Checklist
Use this before and after the move.
Decide
[ ] You listed the benefits you expected from services, and checked whether you actually get them.
[ ] You have baseline numbers for delivery speed, reliability, cost, and on-call load.
[ ] You identified services that always change or deploy together.
Design
[ ] Modules map to business capabilities, and start coarse.
[ ] Each module has one public entry point and hides the rest.
[ ] Each module owns its data, with no cross-module joins or foreign keys.
[ ] Dependencies flow one way, with no cycles.
[ ] The shared kernel is tiny and depends on nothing.
Enforce
[ ] Architecture tests or an import linter fail the build on violations.
[ ] CODEOWNERS maps each module to a team.
[ ] Suppressing a rule needs explicit review.
Operate
[ ] Deploys are small, frequent, and reversible, with flags and canaries.
[ ] Process roles let web, worker, and scheduler scale separately.
[ ] Per-module metrics, timeouts, and resource limits are in place.
[ ] Old service pipelines, dashboards, and infrastructure are removed.
Keep the option
[ ] Events and the outbox pattern are used for asynchronous reactions.
[ ] The composition root can swap a module for a network client.
[ ] You have written down the criteria that would justify extracting a service.
Conclusion
The lesson is not that microservices are bad, and it is not that monoliths are good. The lesson is that the unit of deployment and the unit of design are two separate decisions.
Good design means clear boundaries, owned data, small public interfaces, and one-way dependencies. You can have all of that inside one deployable. The network is a powerful tool, but it is a tool you should reach for when you can name the problem it solves.
If your services must deploy together, share data, and call each other in chains, you are paying for independence you do not have. Merging them into well-enforced modules gives you faster changes, simpler operations, easier testing, and lower cost. Keep the boundaries clean, and the door to services stays open for the day the evidence says it should.
Top comments (0)