What is a distributed monolith, and how do you know you have one?
A distributed monolith is a system deployed as separate services but still behaving like one program. The services run in different processes and talk over the network, yet they cannot change, ship, or fail independently. You pay the operational cost of distribution without getting the autonomy that justifies it.
The usual signs:
- Lockstep deploys. Service A cannot ship until B and C ship compatible versions, so releases are coordinated by calendar instead of contract.
- Cross-repo features. A single user-facing change routinely needs pull requests in three or four repositories, merged in a specific order.
- Synchronous call chains on every request. One inbound call fans out through several services in series. Latency accumulates at each hop, and any one of them being down fails the whole request.
- Shared databases or schemas. Services read and write the same tables, so a schema change is effectively a change to every service at once.
- One team, many tightly coupled services. The service boundaries don't match any organizational boundary, so there is no one to grant independence to.
Reverse migration means folding those services back into a single deployable unit, ideally a modular one, while keeping the system running. Deciding to merge microservices into a monolith corrects boundaries drawn before the domain was understood. It does not admit that splitting was wrong in principle.
This guide is for backend and platform engineers who inherited, or built, services that split too early and now spend more effort coordinating them than building features.
BEFORE: distributed monolith -- one team, lockstep deploys
client
|
v
+---------+ sync +---------+ sync +---------+
| Orders |-------->| Pricing |-------->| Stock |
| service | HTTP | service | HTTP | service |
+---------+ +---------+ +---------+
| | |
+-------------------+-------------------+
|
v
+-------------------+
| shared DB/schema |
+-------------------+
AFTER: modular monolith -- one deployable, one release
+-----------------------------------------------------+
| one deployable, modules call via interfaces |
| +--------+ call +---------+ call +-------+ |
| | orders |-------->| pricing |-------->| stock | |
| +--------+ +---------+ +-------+ |
+-----------------------------------------------------+
|
v
+--------------+
| one database |
+--------------+
A distributed monolith has the same coupling as a monolith: serial network hops on every request, one shared schema, and services that must ship together. Merging the services turns it into a single modular deployable.
Why merge microservices into a monolith, and what evidence should drive the decision?
Every synchronous hop between two services adds latency, serialization, and a new failure mode. That cost is worth paying when the split buys independent scaling, deployment, or ownership. When two services are owned by one team, change together, and ship together, the hop buys nothing. The timeouts, retries, idempotency keys, and compensating logic then exist only to survive a boundary that delivers no benefit.
Base the decision on three kinds of evidence, not on frustration.
Call graphs
Use distributed tracing or correlated request logs to find services that call each other on the same request path. Strong candidates are pairs that make several calls per user request, or chains where one service cannot respond without the other.
Co-change history
The accompanying script reads git log --name-only, maps each changed path to its service directory, and counts how often each pair of services appears in the same commit. Pairs that change together in most commits are coupled, whatever the architecture diagram says. In a polyrepo setup, correlate commits by ticket ID instead.
Boundary incidents
Tag postmortems by cause. Count how many came from timeouts, retry storms, version skew between services, or partial writes across services.
Illustrative estimate. All inputs are assumptions:
- 4 cross-service changes per week.
- 3 extra hours each for contract updates, staged deploys, and compatibility shims.
- 2 boundary incidents per month at 8 hours each.
That comes to about 12 + 4 = 16 hours per week, or roughly 40% of one engineer's time spent on coordination.
#!/usr/bin/env bash
# Rank pairs of services by how often they change in the same commit.
# Assumes a monorepo laid out as services/<name>/...; adjust the awk match otherwise.
set -euo pipefail
SINCE="${1:-12 months ago}"
printf 'together\tsvc_a\tsvc_b\tcommits_a\tcommits_b\n'
# '@@' marks the start of each commit; the file paths follow it.
git log --no-merges --since="$SINCE" --name-only --pretty=format:'@@' |
awk -F/ '
function flush( n, i, j, k, t, names) {
n = 0
for (s in seen) names[++n] = s
# Sort names so the pair key is always "a b", never "b a".
for (i = 2; i <= n; i++) {
t = names[i]
for (j = i - 1; j > 0 && names[j] > t; j--) names[j+1] = names[j]
names[j+1] = t
}
for (i = 1; i <= n; i++) {
total[names[i]]++
for (k = i + 1; k <= n; k++) pair[names[i] " " names[k]]++
}
split("", seen) # portable way to clear the array
}
$0 == "@@" { flush(); next }
# Map services/<name>/any/file to <name>; ignore everything else.
$1 == "services" && NF >= 3 { seen[$2] = 1 }
END {
flush()
for (p in pair) {
split(p, ab, " ")
printf "%d\t%s\t%s\t%d\t%d\n", pair[p], ab[1], ab[2], total[ab[1]], total[ab[2]]
}
}' | sort -rn | head -n 20
# Read the output: if 'together' is close to the smaller of commits_a and commits_b,
# that pair rarely changes independently and is a merge candidate.
A git log and awk script that maps changed paths to service directories and ranks service pairs by how often they change in the same commit, alongside each service's total commit count.
Which services should you merge, and when should you avoid service consolidation?
Once you know what the boundaries cost, decide which ones to remove. Group candidates by bounded context and change coupling, not by tech stack. Two Node services that share nothing are not merge candidates just because they share a runtime. Two services in different languages that change in lockstep for every feature are better candidates. Your version-control history is the best evidence: if most commits to pricing come with a matching commit to quotes within the same day, the split boundary is not a real seam.
| Signal | Merge | Keep separate |
|---|---|---|
| Change coupling | Features routinely touch both services | Changes rarely cross the boundary |
| Scaling profile | Similar load shape and resource needs | One is CPU-bound, bursty, or needs very different capacity |
| Isolation and security | Same trust level and data sensitivity | Handles payments, secrets, or untrusted input that needs a separate blast radius |
| Ownership | One team owns both | Different teams with separate on-call |
| Release cadence | Shipped together anyway | One deploys hourly, the other quarterly |
| Runtime | Same language, or rewriting is small | Different runtime that would require a rewrite |
The organizational side matters as much as the technical one. Teams can read consolidation as a loss of ownership, and a resentful team will route around the merged codebase. Conway's law also works against you: if two teams stay split with separate backlogs, they will rebuild the boundary inside the monolith, or pull the code apart again. Merge services only when their owning teams merge too, or when ownership of each module stays explicit within the shared codebase.
How does a modular monolith keep the merge from becoming a big ball of mud?
The network boundary was doing work nobody had to think about. A service could not import another service's classes, read its tables, or call a private helper, because none of those things were reachable over HTTP or a queue. Once the code shares a process and a build, every one of those shortcuts becomes a one-line change, and under deadline pressure someone will take it. A modular monolith keeps one deployable but rebuilds those seams on purpose.
Make the module API the only way in
Each former service becomes a module with a small public surface: a facade or a set of interfaces, plus the data types they accept and return. Everything else is hidden through the language's visibility rules. Examples include package-private classes in Java, internal directories in Go, or non-exported symbols in a TypeScript workspace package. Callers depend on the facade and never on repositories, entities, or another module's database schema. This keeps the old contract recognizable, so extracting a module again later means putting a network adapter behind an interface that already exists.
Enforce dependency rules in CI
Visibility rules alone do not stop a module from depending on another module's public types in the wrong direction. Add architecture tests that run with the normal test suite. Write rules like these:
billingmay depend onaccounts.apibut not on anything else inaccounts.- No module may import another module's persistence package.
- No dependency cycles are allowed between modules.
When a pull request adds a forbidden import, the build fails and names the offending class and rule. A boundary that only lives on a diagram will erode. A boundary checked on every commit will hold.
// Runs with the normal JUnit 5 suite (archunit-junit5), so CI fails on a forbidden import.
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideInAPackage;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.resideOutsideOfPackage;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices;
// Scan production code only; test fixtures may cross boundaries.
@AnalyzeClasses(packages = "com.example", importOptions = ImportOption.DoNotIncludeTests.class)
class ModuleBoundaryTest {
// billing may use accounts' published API, nothing behind it.
@ArchTest
static final ArchRule billingUsesOnlyAccountsApi =
noClasses().that().resideInAPackage("com.example.billing..")
.should().dependOnClassesThat(
resideInAPackage("com.example.accounts..")
.and(resideOutsideOfPackage("com.example.accounts.api..")));
// Only accounts itself may touch its repositories and entities.
@ArchTest
static final ArchRule accountsPersistenceIsPrivate =
noClasses().that().resideOutsideOfPackage("com.example.accounts..")
.should().dependOnClassesThat()
.resideInAPackage("com.example.accounts.persistence..");
// Each top-level package is a module; cycles between them block later extraction.
@ArchTest
static final ArchRule noCyclesBetweenModules =
slices().matching("com.example.(*)..")
.should().beFreeOfCycles();
}
An ArchUnit test class that encodes the three module rules from this section, failing the CI build and naming the offending class whenever a pull request adds a forbidden dependency.
How do you implement the reverse migration incrementally?
Move one service at a time, starting with the one whose callers already sit inside the monolith. Copy its code in as a module and keep the interface its callers already depend on. Keep the request and response types and the error semantics too. Callers then compile against the same contract, and the only thing that changes is where the work runs.
Swap the transport, not the contract
Give the client interface two implementations. One makes the existing network call. The other invokes the module directly in-process. A flag selects between them at startup or per request. Because both satisfy one abstraction, rolling back is a configuration change rather than a revert. The in-process path also removes failure modes the network path had, such as timeouts and partial failures. Check that callers aren't relying on retry or timeout behavior that no longer applies.
Prove equivalence before cutting over
Run both paths in parallel for a sample of traffic. Serve the network result, call the in-process path in shadow, and log any differences. Shadow only read-only operations, or writes that are safely idempotent. Otherwise you will apply side effects twice. Once differences stop appearing, shift traffic to the in-process path, then retire the old deployment along with its pipeline, alerts and on-call runbook.
Keep consumers out of the migration
External clients should not notice the move. Route their endpoints to the monolith through the gateway or a facade. Keep publishing to the same event topics with the same schemas. This lets consumers upgrade on their own schedule.
Commit to finishing. A migration abandoned halfway leaves you running both architectures at once. You carry two code paths, flags nobody dares remove, and the operational cost of both end states without the benefits of either.
import { InventoryModule } from "./modules/inventory"; // service code moved in as a module
export type StockLevel = { sku: string; available: number };
// The contract callers already compile against. It does not change.
export interface InventoryClient {
getStock(sku: string): Promise<StockLevel>;
}
// Existing path: a network call to the standalone service.
class HttpInventoryClient implements InventoryClient {
constructor(private baseUrl: string) {}
async getStock(sku: string): Promise<StockLevel> {
const res = await fetch(`${this.baseUrl}/stock/${encodeURIComponent(sku)}`);
if (!res.ok) throw new Error(`inventory: HTTP ${res.status}`);
return (await res.json()) as StockLevel;
}
}
// New path: same contract, but the work runs in-process.
class InProcessInventoryClient implements InventoryClient {
constructor(private mod: InventoryModule) {}
getStock(sku: string) { return this.mod.getStock(sku); }
}
// Serve the network result and run the in-process path in the background to compare.
// Use this only for read-only or idempotent operations so side effects are not applied twice.
class ShadowInventoryClient implements InventoryClient {
constructor(private primary: InventoryClient, private shadow: InventoryClient) {}
async getStock(sku: string) {
const served = await this.primary.getStock(sku);
this.shadow.getStock(sku)
.then((s) => { if (JSON.stringify(s) !== JSON.stringify(served)) console.warn("inventory mismatch", { sku, served, s }); })
.catch((err) => console.warn("inventory shadow error", { sku, err }));
return served;
}
}
// A flag picks the transport. Rolling back is a config change, not a revert.
export function makeInventoryClient(mod: InventoryModule): InventoryClient {
const http = new HttpInventoryClient(process.env.INVENTORY_URL ?? "");
const local = new InProcessInventoryClient(mod);
switch (process.env.INVENTORY_CLIENT_MODE ?? "network") {
case "inprocess": return local;
case "shadow": return new ShadowInventoryClient(http, local);
default: return http;
}
}
A single InventoryClient interface has network and in-process implementations plus a shadow mode that compares their results, and an environment flag chooses which one callers get.
Consolidating data and operations safely
Data
Start by moving the services' databases onto one database server, with each module keeping its own schema. This removes network hops and lets you join across modules when needed. Schema boundaries also prevent table and sequence names from colliding, and each module's data stays clearly owned. Fully merging the schemas is a separate decision that you can defer.
Once two modules share a database, a saga that coordinated them can become a single local transaction, and its compensating logic can be deleted. Check what each side assumed first. A service built around eventual consistency may tolerate stale reads that a transactional caller will now treat as bugs, and the reverse also happens.
Run backfills in batches that can be resumed, and throttle them so they don't saturate I/O. Rehearse the cutover against a copy of production. Keep the old write path as your rollback until reconciliation checks pass. While both paths run, compare row counts and checksums regularly, because drift builds up quietly.
Operations
Combine configuration, secrets, health checks and alerting into one deployable unit. Every log line and metric should still carry a module tag, so you can tell which module caused a latency spike. Rebuild dashboards around those tags, and assign on-call ownership by module.
One process means one bad deploy can take down everything. Offset that larger blast radius with canary releases, contract tests at module boundaries, and a rollback you have actually practiced.
What are the alternatives, and how do you measure whether the merge saved engineering time?
Full consolidation is not the only fix for services that split too early. Compare it against cheaper options before committing:
| Option | What it fixes | Main trade-off |
|---|---|---|
| Full consolidation | Network hops, cross-service transactions, deploy coordination | Larger builds, shared pipeline, no independent scaling |
| Fix contracts, keep services | Breaking changes, chatty APIs | Coupling remains if boundaries are wrong |
| Co-deploy services together | Release coordination | Still pays network and serialization cost |
| Async messaging | Synchronous call chains, cascading timeouts | Eventual consistency, harder debugging |
| Merge data layer only | Cross-service joins, distributed transactions | Shared schema couples teams again |
Consolidation moves cost to new places. Builds and test suites grow, and startup time rises because one process now initializes every module. A shared pipeline means more merge conflicts and queued builds. All modules must agree on one version of each library, so a single upgrade can block everyone. You also lose independent scaling. A CPU-heavy module forces you to scale the whole process, which can raise infrastructure cost. The usual mitigation is to run that module as a separate worker pool from the same codebase.
Measuring the outcome
Record your own baselines before the merge, then compare them over the same length of time afterward. Track five measures:
- Lead time for changes: commit to production.
- Deploy frequency: how often you ship.
- Critical-path latency: p95 latency of the requests that previously crossed service boundaries.
- Incident counts: split by cause.
- Infrastructure cost: monthly spend for the workloads you consolidated.
If lead time and incidents fall but build queues grow, apply build caching and module-level test selection before you consider splitting the services again.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to merge microservices into monolith, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.