What is a distributed monolith, and how do you recognize one?
A distributed monolith is a system deployed as separate services but still behaving as one unit. The services cannot change, ship, or fail independently, so you carry the costs of distribution (network hops, partial failures, versioned contracts, more infrastructure) without the main benefit, which is independent evolution. Service consolidation, sometimes called reverse migration, merges services whose boundaries were drawn in the wrong place. It fixes specific bad splits. It is not a rejection of distributed systems. Teams that merge microservices into a monolith usually keep other services separate where the boundaries hold up.
Signals that a split is not real
| Signal | What it looks like | Why it indicates a wrong boundary |
|---|---|---|
| Lockstep deploys | Releasing service A requires releasing B at the same time | The contract between them is not stable, so they are one deployable |
| Shared database or schema | Multiple services read and write the same tables | Data ownership is unsplit, and a schema change breaks several services |
| Synchronous call chains | One user request fans out through several services in sequence | Latency adds up across hops and any single failure fails the request |
| Coordinated cross-repo changes | Most features need pull requests in several repos | Code that changes together has been separated by an arbitrary line |
| Sagas covering a bad split | Compensating logic protects data that was once a single transaction | The workflow exists only to make up for the split |
Seeing one of these signals now and then is normal. When several appear together for the same pair of services, treat that pair as a strong candidate for consolidation.
Which services should you merge? Finding candidates with coupling evidence
Gut feeling about which services "belong together" is usually wrong in both directions, so collect evidence from four sources before proposing any merge.
Co-change history. Walk the version control history and count how often commits, or merged pull requests within the same day, touch two services at once. The script below does this with git log. Pairs that change together in a large share of their commits share a boundary in practice, whatever the architecture diagram says.
Call graphs and traces. Look in your trace data for pairs that exchange many calls per user request, or that sit in long synchronous chains on hot paths. Chatty pairs pay network and serialization cost on every request for a boundary that gives them nothing back.
Ownership maps. If one team owns both services, the split was never needed for team autonomy.
Data access overlap. Services that read or write each other's tables, or keep copies of the same entities, already share a schema in everything but name.
Plot the results as a graph and look for clusters that change together, fail together in incidents, and talk to each other constantly. Each cluster is a merge candidate. A single strong pair is not enough on its own.
Before any work starts, record baselines for each cluster:
- Deploy frequency
- Lead time
- Cross-service incident count
- p99 latency on the chatty paths
- Infrastructure cost
Without these numbers you cannot show that the consolidation helped.
A platform or architecture engineer should run this analysis, working with the owning teams. Do it before committing to a roadmap, and use at least a few months of history so a single release cycle does not skew the results.
#!/usr/bin/env bash
# Co-change analysis for a repo laid out as services/<name>/...
# Usage: ./cochange.sh [since] [min_shared_commits]
set -euo pipefail
SINCE="${1:-6 months ago}" # use months of history, not one release cycle
MIN="${2:-5}" # ignore pairs with too few shared commits to mean anything
printf '%-20s %-20s %6s %7s\n' SERVICE_A SERVICE_B SHARED SHARE
# One marker line per commit, then the files it touched under services/.
# --no-merges avoids double counting; with squash merges, one commit = one PR.
git log --no-merges --since="$SINCE" --name-only --pretty=format:'@@%H' -- services/ |
awk -v min="$MIN" '
function flush( a, b) {
for (a in seen) {
total[a]++ # commits touching this service
for (b in seen) if (a < b) pair[a SUBSEP b]++ # each unordered pair once
}
for (a in seen) delete seen[a]
}
/^@@/ { flush(); next } # new commit starts
/^services\// { if (split($0, p, "/") >= 3) seen[p[2]] = 1 }
END {
flush()
for (k in pair) {
n = pair[k]
if (n < min) continue
split(k, s, SUBSEP)
# Share = shared commits / commits of the less active service,
# so a small service that always changes with a big one still stands out.
lo = (total[s[1]] < total[s[2]]) ? total[s[1]] : total[s[2]]
printf "%-20s %-20s %6d %6.1f%%\n", s[1], s[2], n, 100 * n / lo
}
}' | sort -k4 -rn
A git log and awk script that counts how often each pair of services under services/ changes in the same commit and ranks pairs by the share of the less active service's commits that also touch its partner.
When should you avoid merging microservices into a monolith?
The same analysis can also tell you to stop. Consolidation is the wrong move in a few recognizable cases.
Divergent resource profiles. If one component handles spiky traffic, such as an image resizer or a batch export, and its neighbours idle, merging them means every replica must be sized for the worst case. You lose the ability to scale the hot path alone.
Mixed languages and runtimes. A Go service and a JVM service cannot share a process without one being rewritten. At that point you are doing a rewrite, with a rewrite's risk.
Weak coupling evidence. If the services rarely change together or call each other infrequently, the savings are small. Months of dual running, data migration and regression testing can cost more than you will ever recover.
Organizational cost. Teams that deploy independently today will have to coordinate releases, and they may resist for good reason. Losing independent deployment is a real cost, not just a political one.
When a full merge doesn't pay, consider a smaller change:
| Alternative | What changes | Fits when |
|---|---|---|
| Redraw boundaries | Move responsibilities between existing services | One concept is split across services |
| Merge data ownership only | One service owns the shared tables | Coupling lives mainly in the database |
| Combine deploy units | Separate codebases ship as one artifact | Release coordination dominates the pain |
| Improve contracts | Versioned APIs and consumer-driven tests | Coupling is real but stable |
Why the target should be a modular monolith, not a merged ball of mud
Merging codebases removes network hops, but it also removes the friction that kept services apart. Inside one process, any class can call any other class, and any query can join any table. Under deadline pressure, engineers take those shortcuts: the billing code reads the orders table directly, a shared utils package collects domain logic, and a "temporary" call into another module's internals becomes permanent. Within a few release cycles you have the coupling of the distributed monolith without the deployment isolation. Splitting again is now harder than it was before the merge.
The target is a modular monolith: one deployable artifact with boundaries enforced by tooling rather than by convention. Three rules carry most of the weight:
- Build-level dependency rules. Each former service becomes a module with declared dependencies. The build fails if a module imports something it has not declared, and cycles are rejected outright.
- Explicit internal interfaces. Each module exposes a small public surface, such as a facade or an in-process API, and hides everything else. A former HTTP contract maps naturally to this surface.
- Module-owned data. Each module owns its tables or schema. Other modules read that data through the owning module's interface, never by querying its tables directly.
A concept-level boundary rule reads like this: "classes in orders.internal may only be accessed from orders." You can enforce it with an architecture test that runs in CI, or with language-level visibility, such as Java module exports or Go's internal directories. Either way, a violation fails the build instead of waiting for code review to catch it. Because boundaries stay intact, extracting a module back into a service remains an option you can take later.
package com.example.architecture;
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.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices;
// Runs in CI as an ordinary JUnit 5 test, so a boundary violation fails the build.
@AnalyzeClasses(packages = "com.example", importOptions = ImportOption.DoNotIncludeTests.class)
class ModuleBoundaryTest {
// Only the orders module may touch its internals (domain logic, repositories, tables).
// Other modules must go through com.example.orders.api.
@ArchTest
static final ArchRule ordersInternalsArePrivate =
classes().that().resideInAPackage("com.example.orders.internal..")
.should().onlyBeAccessed().byAnyPackage("com.example.orders..");
// Billing depends on orders only through its public API, never its persistence code.
@ArchTest
static final ArchRule billingUsesOrdersApiOnly =
noClasses().that().resideInAPackage("com.example.billing..")
.should().dependOnClassesThat()
.resideInAPackage("com.example.orders.internal..");
// Each top-level package is a module; cycles between modules are rejected outright.
@ArchTest
static final ArchRule noCyclesBetweenModules =
slices().matching("com.example.(*)..").should().beFreeOfCycles();
}
An ArchUnit test that runs in CI and fails the build if another module reaches into orders internals or if any modules form a dependency cycle.
How does the reverse strangler pattern work?
The reverse strangler mirrors the original extraction. Callers keep the existing API contract. A routing layer sits in front of both the old services and the growing monolith, and logic moves inward one service at a time.
Step by step
- Before: gateway → Orders service → (network) → Pricing service. Every request pays a network hop between services.
- During: gateway → monolith. Inside it, the Orders module calls Pricing through a client interface. A flag decides whether that client makes a remote call to the still-running Pricing service or an in-process call to the absorbed Pricing module. Shift traffic by percentage or by tenant, and compare responses.
- After: gateway → monolith, with in-process calls only. Decommission the Pricing service once the flag has stayed fully on for long enough to trust it.
Each step can be rolled back with a single change: flip the flag or revert the route. The old service stays deployed until it has received no traffic for a while.
From remote to in-process calls
Keep the interface boundary even after the network is gone. It is what keeps the module separable. Then audit what the network used to justify:
- Timeouts and circuit breakers around a function call now mostly add noise.
- Retries may double-apply work if the callee isn't idempotent.
- Code that relied on failure semantics needs a decision. For example, a caller that treated a timeout as "skip the discount" now never times out. Decide whether that is acceptable.
- Async ordering can change. Events that once arrived "eventually" may now run synchronously inside the caller's transaction, and that can surface hidden ordering assumptions.
// Orders code depends only on this interface, never on a transport.
export interface PricingClient {
quote(orderId: string, sku: string, qty: number): Promise<{ totalCents: number }>;
}
// Remote call to the still-running Pricing service.
export class RemotePricingClient implements PricingClient {
constructor(private baseUrl: string) {}
async quote(orderId: string, sku: string, qty: number) {
const res = await fetch(`${this.baseUrl}/quotes`, {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": orderId },
body: JSON.stringify({ sku, qty }),
signal: AbortSignal.timeout(500), // only makes sense across a network
});
if (!res.ok) throw new Error(`pricing returned ${res.status}`);
return (await res.json()) as { totalCents: number };
}
}
// In-process call to the absorbed Pricing module: no timeout, no retry.
// Errors propagate directly, so review callers that treated timeouts as "skip".
export class InProcessPricingClient implements PricingClient {
constructor(private pricing: { quote(sku: string, qty: number): Promise<{ totalCents: number }> }) {}
quote(_orderId: string, sku: string, qty: number) {
return this.pricing.quote(sku, qty);
}
}
// Stable per-tenant bucket 0-99, so a tenant stays on the same path between requests.
function bucket(tenantId: string): number {
let h = 0;
for (const ch of tenantId) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return h % 100;
}
// Rollout flag: 0 = all remote (rollback), 100 = all in-process.
export function pricingClientFor(tenantId: string, inProcessPercent: number,
remote: PricingClient, local: PricingClient): PricingClient {
return bucket(tenantId) < inProcessPercent ? local : remote;
}
A PricingClient interface with remote and in-process implementations, chosen per tenant by a percentage flag. Setting the flag to 0 rolls every tenant back to the remote service.
How do you consolidate databases safely during a reverse migration?
Treat the data move as its own project, separate from the code merge. A code regression usually fails loudly. A data regression can stay invisible for weeks while it corrupts balances, counts or audit trails.
Merge schemas before merging tables
Start by moving each service's tables into its own schema inside one database instance. This removes network hops and enables cross-schema joins without forcing early decisions about overlapping entities. Once both copies live in one database, you can replace sagas and compensating actions with a single local transaction. Do this only where the business operation really is atomic. If the saga modeled a real-world delay, such as a payment provider callback, keep it.
Resolve collisions explicitly
Two services may both have a customer table with independent sequences, different nullability rules or different meanings for status. Do not unify these silently. Choose a canonical ID scheme, keep a mapping table from old IDs to new ones, and record every semantic difference before writing any migration.
Backfill, then reconcile continuously
Use dual writes or change data capture to populate the consolidated tables while the old services remain authoritative. Run reconciliation on a schedule. A typical reconciliation query full-outer-joins source and target on the mapped key, compares a row hash or the critical columns, and returns rows that are missing on either side or that differ. Alert on any non-zero result.
Watch contention
Workloads that used to be isolated now compete for the same locks and connection pool. Before you cut over, load-test the merged hot paths and check lock waits.
-- Reconcile legacy billing customers against the consolidated table (PostgreSQL).
-- Any returned row is a discrepancy; alert on a non-zero count.
WITH src AS (
SELECT c.id AS old_id,
m.new_id, -- NULL means the row was never mapped
lower(c.email) AS email,
CASE c.status WHEN 'A' THEN 'active' -- documented semantic mapping
WHEN 'S' THEN 'suspended'
ELSE 'closed' END AS status,
c.balance_cents
FROM billing_svc.customer c
LEFT JOIN core.customer_id_map m
ON m.source_service = 'billing' AND m.old_id = c.id
WHERE c.updated_at < now() - interval '5 minutes' -- skip rows still in replication flight
),
tgt AS (
SELECT t.id AS new_id, lower(t.email) AS email, t.status, t.balance_cents
FROM core.customer t
WHERE t.origin_service = 'billing'
AND t.updated_at < now() - interval '5 minutes'
)
SELECT coalesce(s.new_id, t.new_id) AS new_id,
s.old_id,
CASE
WHEN t.new_id IS NULL THEN 'missing_in_target'
WHEN s.new_id IS NULL THEN 'missing_in_source'
ELSE 'value_mismatch'
END AS problem
FROM src s
FULL OUTER JOIN tgt t ON t.new_id = s.new_id
WHERE s.new_id IS NULL -- unmapped source or orphan target
OR t.new_id IS NULL
OR (s.email, s.status, s.balance_cents)
IS DISTINCT FROM (t.email, t.status, t.balance_cents) -- NULL-safe comparison
ORDER BY problem, new_id;
A PostgreSQL reconciliation query that full-outer-joins legacy and consolidated customer rows through an ID mapping table, normalizes known semantic differences, and lists missing, unmapped or mismatched rows.
How does consolidation change operations, team ownership and engineering cost?
Consolidation replaces many small operational problems with a few larger ones, and each needs a deliberate response.
| Concern | Split services | Modular monolith |
|---|---|---|
| Deploys | One pipeline per service | One pipeline with module-level stages |
| Scaling | Each service scales alone | Hottest module sets instance size for all |
| Observability | Per-service dashboards, network traces | One dashboard set, metrics tagged by module |
| On-call | Rota per service | Rota per module, shared process-level escalation |
| Blast radius | One service | Whole process, so add bulkheads: per-module thread pools, connection limits and timeouts |
Conway's law works in both directions. Team boundaries produced the over-split, and merged code with unchanged ownership produces contested modules that nobody maintains. Give every module exactly one owning team in the code-ownership file before cutover, and route its alerts to that team.
Development costs rise first. You pay for the migration, then for dual running, and build and test times grow with the codebase. Budget for build caching, test selection based on changed modules, and CI that builds and tests each module independently. The savings come from fewer coordinated releases, less contract versioning, and debugging from a single stack trace instead of correlated logs.
Illustrative estimate (assumed numbers, not a benchmark)
- Monthly savings = coordinated releases avoided × engineers per release × hours each = 8 × 4 × 3 = 96 h
- Monthly added CI wait = extra minutes per build × builds ÷ 60 = 6 × 300 ÷ 60 = 30 h
- Net savings = 96 − 30 = 66 h per month
- Payback = migration effort ÷ net savings = 600 ÷ 66 ≈ 9 months
Check these figures against the metrics you defined before migrating. If the result falls short, stop consolidating further services.
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.