What is a microservices to monolith migration, and why do teams do it?

A microservices to monolith migration, sometimes called a reverse migration, folds several independently deployed services into one deployable unit. This guide covers the incremental version. You move one service at a time into a modular monolith, keep module boundaries enforced in code, and keep each step reversible until the merged path has proven itself in production. It is not a rewrite. The business logic moves largely as-is. What goes away is the network between components.

Teams usually start this work after hitting the same set of problems:

  • Operational overhead per service. Every service has its own pipeline, dashboards, alerts, dependency upgrades and on-call surface, whether it changes weekly or yearly.
  • Chatty calls. A single user request fans out into a chain of synchronous calls. Each hop adds latency, a failure mode and retry logic.
  • Distributed transactions that are really one unit of work. Sagas, outbox tables and compensating actions exist only because data that changes together lives in separate services.
  • More services than teams. When four engineers own twelve services, the "independent ownership" argument behind the split no longer holds.

Consolidation saves engineering time by deleting that machinery. In-process calls replace network hops. One pipeline replaces several. A local transaction can replace sync and reconciliation code. Engineers spend less time keeping services consistent with each other and more time on features.

This guide is for backend and platform engineers running more services than they can realistically own.

When should you merge microservices, and when should a service stay separate?

The question is never "are microservices bad?" but "does this particular boundary earn its cost?" Evaluate each pair or cluster of services on its own. A boundary that forces coordinated releases gives you the costs of distribution without the independence it was meant to buy.

Signal to merge Signal to keep separate
Services are always deployed together, or one deploy routinely requires another Scaling profile differs sharply (e.g., a CPU-heavy worker beside a lightweight API)
A request fans out through a synchronous call chain where every hop must succeed Isolation or compliance rules require a separate runtime, network zone or audit scope
Services share a release train, so independent deployability exists only on paper A distinct team owns it end to end and ships on its own schedule
A saga or two-phase commit coordinates writes that one database transaction could handle It runs on a different language runtime, so merging means a rewrite
Contract changes always land in both repos at once Its dependencies conflict with the host's (incompatible library versions, native extensions)

The left column describes coupling that already exists but is mediated by the network. A synchronous chain of three services has roughly the availability of its weakest link multiplied across hops, plus serialization and retry overhead, while still behaving as one unit. Merging removes that machinery without changing how the code actually depends on itself.

The right column describes boundaries that do real work. The last two rows matter most for this guide. If consolidation would mean porting code to another language or replacing a dependency stack, it is no longer a merge without a rewrite. Leave that service out and revisit it later.

How do you map the current system before consolidating services?

Start from evidence rather than the architecture diagram, which usually describes the system as it was intended, not as it runs. Four maps matter.

Call graph. Aggregate a few weeks of distributed traces into service-to-service edges, weighted by call volume and by how often a call sits on a user-facing request path. Chatty pairs, where one request fans out into many synchronous calls between the same two services, are the strongest merge signals.

Data ownership. For each datastore, list which services write to it and which read from it, using database credentials, connection logs or query logs. Shared tables written by multiple services show where boundaries already leaked.

Deploy coupling. Mine deploy history for services that ship within the same window, or whose releases need coordinated version bumps. If two services always deploy together, separate pipelines give you ceremony without independence.

Team ownership. Record who is on call and who reviews changes, not just who is named in a service catalog.

Overlay the four maps and cluster services that share callers, data and owners into candidate bounded contexts. Each cluster becomes one module, or one deployable. This prevents the failure mode where everything collapses into a single undifferentiated codebase. Clusters with weak links between them should stay apart.

Pick the first seam carefully. Look for two or three services that are heavily coupled, owned by one team, low in traffic or business risk, and on the same language stack. A small, reversible merge lets you validate tooling and cutover before touching anything critical.

How does service consolidation into a modular monolith work?

The target is a modular monolith: one deployable, but each former service becomes an explicit module with a small public API (an interface package or facade) and private internals. Without enforcement, developers will reach past that API into another module's classes or tables because nothing stops them, and the codebase drifts into a big ball of mud. Add build-time or lint-time dependency rules: separate build modules with declared dependencies, an architecture test, or a linter that rejects imports of another module's internals. A boundary violation should fail CI.

The mechanical pattern for each service follows three stages:

  • Before: the caller uses an HTTP or gRPC client to reach Service B over the network.
  • Transition: B's code lives in the host repo as a module. The caller depends on B's existing interface, and a config flag selects either the remote client or an in-process adapter.
  • After: only the in-process adapter remains, and the remote client and B's deployment are deleted.

Keep B's existing interface unchanged at first. Callers already depend on its request and response shapes, so changing the contract at the same time as the transport makes it hard to tell which change caused a regression. The in-process adapter implements the same interface by calling B's module directly. It still maps types and errors the way the network client did, which means callers see the same failure semantics.

Put the choice behind configuration or a feature flag. You can then route a percentage of traffic, one environment, or one tenant in-process, compare results, and switch back to the remote service without redeploying.

// modules/billing/api/index.ts: billing's public API. Other modules may import only this file.
import { findInvoice } from "../internal/invoices"; // allowed: same module

export interface Invoice { id: string; totalCents: number; }
export class InvoiceNotFoundError extends Error {}

// Unchanged contract that callers already used over the network.
export interface BillingClient {
  getInvoice(id: string): Promise<Invoice>;
}

// Remote implementation: the existing HTTP client, kept as the fallback route.
export class RemoteBillingClient implements BillingClient {
  constructor(private baseUrl: string) {}
  async getInvoice(id: string): Promise<Invoice> {
    const res = await fetch(`${this.baseUrl}/invoices/${encodeURIComponent(id)}`);
    if (res.status === 404) throw new InvoiceNotFoundError(id);
    if (!res.ok) throw new Error(`billing returned HTTP ${res.status}`);
    return (await res.json()) as Invoice;
  }
}

// In-process adapter: a direct call that maps types and errors the same way the remote client does.
export class InProcessBillingClient implements BillingClient {
  async getInvoice(id: string): Promise<Invoice> {
    const row = await findInvoice(id);
    if (!row) throw new InvoiceNotFoundError(id); // same failure semantics as a 404
    return { id: row.id, totalCents: row.total_cents }; // same response shape as the JSON body
  }
}

// Selected per environment or tenant through config, so routing back needs no redeploy.
export function createBillingClient(cfg: { billingInProcess: boolean; billingUrl: string }): BillingClient {
  return cfg.billingInProcess
    ? new InProcessBillingClient()
    : new RemoteBillingClient(cfg.billingUrl); // e.g. ""
}

A single BillingClient interface with a remote HTTP implementation and an in-process adapter that keeps the same types and errors, chosen by a config flag so traffic can be moved back to the remote service at any time.

How do you handle data, transactions and network-era machinery after merging?

Merging code does not mean merging data. Move each service's tables into one database instance, but keep a separate schema per module and allow a module to read or write only its own. Other modules go through that module's public interface. Enforce this with database grants or an architecture test, because a shared connection makes cross-module joins easy to add and hard to remove. Merge tables only after the module boundaries have held for a while, since a premature merge locks in today's possibly wrong boundary.

Once both sides of a sync run in one process, the dual writes, outbox tables and replication consumers that existed to bridge them can go. Do not retire them until no remote caller remains.

Sagas need more care. Replace a compensation chain with a single local transaction only when every step now touches the same database and none of them calls an external system such as a payment provider. Asynchronous events can become in-process events. If downstream consumers still run remotely during the transition, leave those events on the queue.

Delete retries, timeouts and circuit breakers on hops that no longer exist. Left in place, they hide real failures and can retry operations that are not idempotent.

Watch for behavior that changes under load. A single transaction holds locks longer than separate per-service commits, so contention increases. Code that relied on the network's delay to order operations, such as a consumer that always saw a write before the event about it, can now race. Load-test these paths before raising the in-process traffic percentage.

-- PostgreSQL: one instance, one schema per module, one role per module.
-- The monolith opens a separate connection pool per module using that module's role,
-- so a cross-module join fails with a permission error instead of shipping quietly.

-- Close the shared default schema so nothing lands there by accident.
REVOKE ALL ON SCHEMA public FROM PUBLIC;

-- Owner roles hold DDL rights and never log in. App roles are what the code uses.
CREATE ROLE orders_owner  NOLOGIN;
CREATE ROLE billing_owner NOLOGIN;
CREATE ROLE orders_app    LOGIN;
CREATE ROLE billing_app   LOGIN;

CREATE SCHEMA orders  AUTHORIZATION orders_owner;
CREATE SCHEMA billing AUTHORIZATION billing_owner;

-- Each app role gets DML on its own schema only. There is no grant across modules.
-- If billing needs order data, it calls the orders module's public interface.
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 FOR ROLE orders_owner IN SCHEMA orders
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO orders_app;
ALTER DEFAULT PRIVILEGES FOR ROLE orders_owner IN SCHEMA orders
  GRANT USAGE, SELECT ON SEQUENCES TO orders_app;

GRANT USAGE ON SCHEMA billing TO billing_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA billing TO billing_app;
ALTER DEFAULT PRIVILEGES FOR ROLE billing_owner IN SCHEMA billing
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO billing_app;
ALTER DEFAULT PRIVILEGES FOR ROLE billing_owner IN SCHEMA billing
  GRANT USAGE, SELECT ON SEQUENCES TO billing_app;

-- Boundary check for CI: this should return false for every module pair.
SELECT has_schema_privilege('orders_app', 'billing', 'USAGE') AS orders_can_see_billing,
       has_schema_privilege('billing_app', 'orders', 'USAGE') AS billing_can_see_orders;

PostgreSQL setup that keeps one schema and one role per module inside a shared instance, so cross-module table access fails at the database, plus a privilege check that CI can run to catch any grant that breaks a module boundary.

Cutover, repository and team changes: implementing the migration safely

Shift traffic in steps

Use the gateway or load balancer you already run to move traffic gradually: 1%, then 10%, then half. Keep the old service deployed and route a copy of read requests to both paths, comparing responses and error rates. Before each step, write down the rollback trigger, such as a higher 5xx rate or a p99 regression on a named endpoint. A threshold agreed in advance gets acted on; one debated during an incident usually does not. Each module needs the same dashboards, logs and alerts the old service had. Without that parity you cannot tell whether a problem is a regression or something you could not see before.

One repository, fast feedback

Merge into a single repository and deployable with one version of each dependency. Unifying versions forces conflicts out early. Keep feedback fast with module-scoped test targets and CI path filters, so that a change under one module runs only that module's suite. Shared code and integration tests run on every change.

Path Owners CI on change
modules/billing/ billing team billing tests
modules/catalog/ catalog team catalog tests
shared/, build files platform team full suite

Illustrative configuration

Ownership

Code-owner rules require approval from the owning team when a change touches a module's public interface. Agree in writing who owns the shared pipeline, who schedules dependency upgrades and how on-call is split. A single deployable makes these shared decisions, and without explicit owners they get left undone.

#!/usr/bin/env bash
# CI path filter: run only the suites for modules a change touches.
set -euo pipefail
BASE_REF="${BASE_REF:-origin/main}"

# Illustrative ownership and test target per module path.
declare -A OWNERS=( [modules/billing/]="billing-team" [modules/catalog/]="catalog-team" )
declare -A TARGETS=( [modules/billing/]="test-billing" [modules/catalog/]="test-catalog" )

changed=$(git diff --name-only "${BASE_REF}...HEAD")
[ -z "$changed" ] && { echo "No changes"; exit 0; }

# Shared code and build files affect every module, so run everything.
if grep -qE '^(shared/|Makefile$|build/)' <<<"$changed"; then
  echo "Shared or build files changed: platform-team review, full suite"
  exec make test-all
fi

# Files outside any known module are unclassified; fail safe to full suite.
if grep -vqE '^modules/(billing|catalog)/' <<<"$changed"; then
  echo "Unmapped paths changed: running full suite"
  exec make test-all
fi

targets=()
for prefix in "${!TARGETS[@]}"; do
  if grep -q "^${prefix}" <<<"$changed"; then
    echo "${prefix} changed: needs review from ${OWNERS[$prefix]}"
    targets+=("${TARGETS[$prefix]}")
  fi
done

# Module suites stay fast; integration tests guard the boundaries on every change.
make "${targets[@]}" test-integration

An illustrative CI script that maps changed paths to owning teams and module-scoped test targets, falling back to the full suite for shared code, build files or unmapped paths.

What are the trade-offs and alternatives to a reverse migration?

Consolidation trades one set of costs for another.

  • Deployability: You lose independent releases. A one-line billing fix now ships with everyone else's changes and waits on everyone's test suite.
  • Blast radius: It grows. A memory leak or an exhausted thread pool in one module degrades the whole process, not one service.
  • Scaling: It becomes coarse. Adding capacity for one hot path means replicating the entire application.
  • Boundaries: Module boundaries erode unless a build-time check enforces them.
  • Shared runtime: Every module must use the same language version and the same versions of shared libraries.
  • Stalling halfway: This is the worst outcome. You run a partial monolith beside the remaining services and pay for both architectures.
  • Organizational resistance: Expect pushback from teams that lose ownership of a deployable.

Two mitigations help. Bulkheads, such as separate thread pools and connection pools per module, keep one module from starving the others. You can also deploy the same codebase as separate workloads selected by entry point. That restores isolation and independent scaling for hot paths without splitting the code again.

Option Deployability Operational cost Scaling Migration effort
Full modular monolith Single unit Lowest Whole app High
Merge within bounded contexts Per context Moderate Per context Medium
One codebase, multiple deployables Per workload Moderate Per workload Medium
Cut platform overhead, keep services Per service Reduced Per service Low
Do nothing Per service Unchanged Per service None

Avoid consolidation entirely in three cases. The first is when services genuinely differ in scaling profile, runtime or compliance scope. The second is when teams already deploy independently without coordination pain. The third is when the real problem is platform overhead you can reduce without moving any code.

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 microservices to monolith migration, 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.