What coupling matters when you extract a microservice from a monolith?

Service extraction means moving one capability out of a monolith into a separately deployed process that owns its code and data. Teams do it for two concrete payoffs: deploying that capability without releasing everything else, and keeping its failures from taking down the rest of the system. Coupling determines whether you get either payoff. A service that still shares tables or must deploy in lockstep with the monolith is a distributed monolith with extra latency.

Five kinds of coupling decide whether a seam can be extracted:

Coupling type How it shows up Why it blocks extraction
Shared database tables Multiple modules read or write the same tables Schema changes need coordinated deploys
Synchronous in-process calls Direct method calls across module boundaries Each call becomes a network hop that can fail or slow down
Shared domain models One Customer class used everywhere Changing the model ripples into both sides
Transactional boundaries One database transaction spans both modules You lose atomicity and must design for partial failure
Temporal coupling Files that change together in commit history The modules can't evolve or deploy independently

Data coupling is usually the hardest to undo. Code can be wrapped behind an interface in an afternoon. Data is different: shared tables carry implicit contracts, such as joins, foreign keys, triggers and reports nobody remembers writing. Splitting them means migrating live state while both sides keep running.

The thesis of this guide follows from that. Choose the first service by measured coupling, not by business importance or by which team is most eager. The first extraction should teach you the mechanics at low risk.

Who should use this approach?

This approach suits teams with a working monolith whose pain can be traced to specific capabilities rather than to the codebase as a whole. Typical signs:

  • Unrelated changes block each other in a shared release. One team's failing test or risky migration holds up everyone else's deploy.
  • One capability has different scaling needs, such as a CPU-heavy rendering job or a bursty import, and scaling the whole monolith to serve it wastes resources.
  • A failure in one area, such as a memory leak in a background job or a slow dependency, takes down request handling for everything.
  • Several teams work in the same code and step on each other through merge conflicts, shared models and unclear ownership.

It also assumes some baseline capability. You need automated tests good enough to tell you whether a refactor broke behavior. You need deploy automation you can replicate for a second service, logs and metrics you can correlate across processes, and a team willing to own the new service on call. Without these, the first extraction turns into building them under pressure.

It is a poor fit for an early product whose domain boundaries are still shifting, because you would be freezing boundaries you don't yet understand. It is also a poor fit for a single small team with no release contention, which is the case covered in the cost section below. In both situations the modular-boundary step is still worth doing on its own.

How do you run a coupling analysis with tools you already have?

You need three views of the codebase, and each one catches coupling the others miss.

Static dependency graph. Parse module imports and build a directed graph. Most languages have an import analyzer, and a short script that walks source files works too. For each candidate module, count the edges that cross its boundary in both directions. Few inbound edges means few callers to rewire. Few outbound edges means the new service won't need many remote calls to do its job.

Data access map. Record which code paths read and write which tables. You can get this from database query logs or from ORM instrumentation that tags each query with its call site. Shared writes are the strongest form of coupling. If two modules both write to the same table, splitting them means coordinating those writes across a network.

Change history. Run git log --name-only over a year or two and count file pairs that appear in the same commit. Files that keep changing together are coupled in practice, whatever the import graph shows.

Change history has known blind spots. Large refactors, formatting sweeps, and old team boundaries all produce co-changes that say nothing about current design, so filter those commits out. The opposite error also happens. Stable code that rarely changes can still be tightly coupled at runtime through shared tables or synchronous calls. The data access map exists to catch that case.

None of this requires touching production code. A candidate that fails on any of the three views can be dropped after an afternoon of analysis, before anyone spends weeks finding the same problem in a half-built service.

#!/usr/bin/env bash
set -euo pipefail

SINCE="${1:-2 years ago}"
MAX_FILES="${2:-20}"   # commits touching more files than this are treated as sweeps/refactors
PATHSPEC="${3:-src/}"

git log --no-merges --since="$SINCE" \
    --invert-grep -i --grep='format' --grep='lint' --grep='rename' \
    --name-only --pretty=format:'@@commit' -- "$PATHSPEC" \
| awk -v max="$MAX_FILES" '
    # Emit every unordered pair of files from the commit just read.
    function flush(   i, j, a, b, key) {
      if (n >= 2 && n <= max)
        for (i = 1; i <= n; i++)
          for (j = i + 1; j <= n; j++) {
            a = f[i]; b = f[j]
            key = (a < b) ? a "\t" b : b "\t" a   # stable key regardless of order
            pairs[key]++
          }
      n = 0
    }
    /^@@commit$/ { flush(); next }   # marker line starts a new commit
    NF           { f[++n] = $0 }     # non-empty line is a changed file path
    END {
      flush()
      for (k in pairs) print pairs[k] "\t" k
    }
  ' \
| sort -t$'\t' -k1,1nr \
| head -n 30

A bash and awk script that mines git history for files that change together, skipping merge commits, oversized commits, and formatting or rename sweeps that would inflate apparent coupling.

What makes a good first seam, and which seams should you avoid?

The candidates that survive tend to share a shape: they sit at the edge of the dependency graph. A good first seam makes few outbound calls, so the new service does not need half the monolith reachable over the network. It owns its tables outright, with few or no other modules writing to them. It can tolerate eventual consistency, because a few seconds of lag will not corrupt anyone's view of the world. And it already has an interface you could describe in a sentence. Notifications, document rendering and search indexing fit this profile. Each consumes events or requests and produces output that nothing else transactionally depends on.

Trait Good first seam Poor first seam
Position in call graph Leaf, few outbound calls Hub that most modules call or join against
Data ownership Owns its tables, few outside writers Shared core entities such as users or orders
Transactions Standalone writes Part of a multi-table transaction
Consistency Tolerates lag Needs read-your-writes
Latency Off the request path On the hot path, where a network hop adds visible delay

The catch is that leaf-like seams are often low-value. Moving notifications out rarely changes what the business can ship, so stakeholders see weeks of effort and no visible payoff. Present the first extraction as building the routing, deployment and data-migration patterns that later, more valuable extractions will reuse.

Check team ownership too. A seam chosen purely on coupling scores can split code that one team owns, or merge code owned by two teams. Either way, you have swapped code coupling for coordination overhead between people.

How do you draw the seam inside the monolith before adding a network hop?

Once you have a candidate, make it a real module before it becomes a service. Moving code behind a network call does not reduce coupling. It only makes every existing dependency slower and more likely to fail. Fix the dependencies first, while a mistake still costs a recompile rather than an outage.

Start by giving the module one public entry point. For a billing seam, that might be a BillingApi interface with operations such as createInvoice(orderId, lineItems) and getInvoiceStatus(invoiceId). Those operations should return plain data objects, not ORM entities. Returning entities exposes lazy-loaded relationships and the database schema to callers. Everything else in the module becomes internal.

Then take the module's tables away from the rest of the codebase. Other code must stop joining against invoices or updating it directly. If a report needs invoice data, it goes through the interface or reads from a projection that billing publishes. This step is usually where the hidden coupling shows up.

Enforce the boundary with an automated check. A common approach is an architecture test or lint rule that fails the build when code outside billing imports anything except billing.api. A second rule can flag SQL or repository access to billing tables from other modules. If the boundary is kept only by convention, it erodes one deadline-driven shortcut at a time.

If you skip this step, you tend to end up with a distributed monolith: separate services that share schemas and assumptions and still have to deploy in lockstep.

Sometimes the work ends here. A monolith with enforced module boundaries gives you most of the maintainability benefit without network failures, distributed tracing, or separate deploy pipelines. Extract the module only when it needs independent scaling, a separate release cadence, or isolation from failures elsewhere.

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.noClasses;

// Runs with the normal unit test suite, so a boundary violation fails the build.
// Assumed layout:
//   com.example.billing.api       -> BillingApi interface plus plain data objects (InvoiceDto, ...)
//   com.example.billing.internal  -> implementation, ORM entities, repositories for the invoices tables
@AnalyzeClasses(packages = "com.example", importOptions = ImportOption.DoNotIncludeTests.class)
class BillingBoundaryTest {

    // Other modules may only call billing through billing.api.
    // Reaching into internal (services, entities, repositories) is a build failure.
    @ArchTest
    static final ArchRule onlyBillingApiIsPublic =
        noClasses()
            .that().resideOutsideOfPackage("com.example.billing..")
            .should().dependOnClassesThat().resideInAPackage("com.example.billing.internal..")
            .because("billing is a module; use com.example.billing.api");

    // The API must not expose ORM entities or other internal types.
    // Otherwise callers inherit lazy-loaded relations and the table schema.
    @ArchTest
    static final ArchRule apiDoesNotLeakInternals =
        noClasses()
            .that().resideInAPackage("com.example.billing.api..")
            .should().dependOnClassesThat().resideInAPackage("com.example.billing.internal..")
            .because("BillingApi returns plain data objects, not entities");
}

An ArchUnit test, run as part of the regular JUnit 5 suite, that fails the build when code outside billing reaches past billing.api or when the API exposes internal entities.

How does strangler-fig routing move traffic to the new service?

Once the module boundary holds inside the monolith, put a facade in front of it. This can be an interface in the monolith or a routing proxy at the edge, and it decides per request whether to call the in-process implementation or the new service. Callers can't tell which path ran, and that is what makes the cutover reversible.

For read paths, start with shadow traffic. Serve the response from the in-process code, send a copy of the request to the service asynchronously, and log any mismatches. The diffs expose serialization differences, timezone handling and missing data before a user sees them. Don't shadow writes unless the service writes to an isolated store. Otherwise every side effect runs twice.

Next, ramp traffic in small percentages. Keep routing sticky per user or tenant so behavior stays consistent, and check error rate and latency at each step. Keep the in-process implementation deployed, and put the routing decision behind a flag you can flip without a deploy. A rollback should take seconds.

The network adds failure modes that a function call never had:

  • Every call needs a timeout shorter than the caller's own deadline.
  • Retries need backoff and a budget. Without them, a slow service turns into a retry storm.
  • A timeout doesn't tell you whether a write happened, so mutating calls need idempotency keys that the service deduplicates on.

Also check how chatty the interface is. Code that fetched items one at a time in a loop was fine in-process, but over the network it makes N round trips. As an illustrative estimate, fifty calls at 2 ms each add 100 ms that the monolith never paid. Batch the calls or reshape the interface before you ramp.

import { createHash } from "node:crypto";

interface Inventory {
  // Batched on purpose: one round trip for N SKUs instead of N calls in a loop.
  getStock(skus: string[]): Promise<Record<string, number>>;
  // Caller supplies the key so a retried write is deduplicated by the service.
  reserve(sku: string, qty: number, idempotencyKey: string): Promise<void>;
}

// Sticky routing: a tenant always hashes to the same bucket (0-99).
const bucket = (tenantId: string) =>
  createHash("sha256").update(tenantId).digest().readUInt32BE(0) % 100;

class RemoteInventory implements Inventory {
  // e.g. new RemoteInventory("")
  constructor(private baseUrl: string, private timeoutMs = 300) {}

  private async post(path: string, body: unknown, headers: Record<string, string> = {}) {
    const res = await fetch(`${this.baseUrl}${path}`, {
      method: "POST",
      headers: { "content-type": "application/json", ...headers },
      body: JSON.stringify(body),
      // Keep this shorter than the caller's own deadline.
      signal: AbortSignal.timeout(this.timeoutMs),
    });
    if (!res.ok) throw new Error(`inventory ${path} failed: ${res.status}`);
    return res.status === 204 ? undefined : res.json();
  }

  getStock(skus: string[]) { return this.post("/stock/batch-get", { skus }); }

  async reserve(sku: string, qty: number, key: string) {
    await this.post("/reservations", { sku, qty }, { "Idempotency-Key": key });
  }
}

// The facade: callers get an Inventory and can't tell which path ran.
export function inventoryFor(tenantId: string, local: Inventory, remote: Inventory,
                             rolloutPercent: () => number): Inventory {
  // rolloutPercent reads a runtime flag; setting it to 0 is the rollback.
  return bucket(tenantId) < rolloutPercent() ? remote : local;
}

A TypeScript facade that routes each tenant to the in-process or remote implementation by a flag-controlled percentage, with a batched read, a per-call timeout and an idempotency key on writes. Retries with backoff are left out to keep the example short.

How do you migrate data ownership without dual-write bugs?

Move data in a fixed order, because each step depends on the previous one.

1. Transfer table ownership. Pick the tables the service will own and make it the only writer. Monolith code that still writes to them goes through the service's API instead. Until a table has exactly one writer, you can't reason about its invariants.

2. Replace foreign-key joins. Monolith queries that join against those tables have to stop. Either call the service's API, batched as discussed above, or keep a replicated read model in the monolith that is fed by events. A read model is faster but stale by design, so use it only where slightly old data is acceptable.

3. Use an outbox, not dual writes. During cutover it is tempting to write to both databases from application code. If one write succeeds and the other fails, the copies silently diverge. With an outbox, the service writes the row and an outbox record in the same local transaction, and a relay publishes that record afterward. Delivery becomes at-least-once, so consumers must be idempotent.

4. Accept the loss of cross-boundary ACID. A single transaction can no longer span both sides. Workflows that touch both become sagas: a sequence of local transactions, each with a compensating action that undoes it if a later step fails. Accept eventual consistency, and tell product owners which views may lag.

5. Reconcile continuously. While two sources of truth exist, run scheduled checks that compare row counts and per-key checksums between them. Alert on any drift. Don't retire the old copy until reconciliation has stayed clean for a full business cycle.

-- PostgreSQL. Outbox table lives in the service's own database.
CREATE TABLE outbox (
  id           uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  aggregate_id text        NOT NULL,
  event_type   text        NOT NULL,
  payload      jsonb       NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  published_at timestamptz
);

-- Write path: the business row and its event commit or roll back together.
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status)
VALUES ('ord-1042', 'cust-77', 4999, 'PLACED');
INSERT INTO outbox (aggregate_id, event_type, payload)
VALUES ('ord-1042', 'OrderPlaced',
        jsonb_build_object('id', 'ord-1042', 'customer_id', 'cust-77', 'total_cents', 4999));
COMMIT;

-- Relay: claim a batch without blocking other relay instances.
-- Publish each row to the broker, then mark it sent in the same transaction.
-- A crash after publish but before commit re-sends the event (at-least-once),
-- so consumers must dedupe on outbox.id.
BEGIN;
SELECT id, aggregate_id, event_type, payload
FROM outbox
WHERE published_at IS NULL
ORDER BY created_at
LIMIT 100
FOR UPDATE SKIP LOCKED;
-- ... application publishes the claimed rows here ...
UPDATE outbox SET published_at = now() WHERE id = ANY('{}'::uuid[]); -- claimed ids go here
COMMIT;

-- Reconciliation: run the same query against the service DB and the monolith's copy,
-- then diff the results by id. Any missing id or differing hash is drift.
SELECT id, md5(row(customer_id, total_cents, status)::text) AS row_hash
FROM orders
ORDER BY id;

A PostgreSQL outbox. The order row and its event commit in one local transaction, a relay claims unpublished events with SKIP LOCKED, and a per-key hash query run against both copies finds drift during the dual-source window.

What are the alternatives to extracting a service?

Extraction is one answer to a specific problem. Before committing to it, check whether a cheaper change addresses the pain you actually have:

Problem Alternative to extraction Trade-off
Tangled code, unclear ownership Modular monolith with enforced boundaries, as described above No independent deploys or failure isolation, but no network failure modes either
Slow or contended releases Faster test suites, trunk-based development, feature flags to decouple deploy from release Shared release remains, so one broken build still blocks everyone
One workload needs more capacity Run the same build in separate process groups by role, such as web handlers and background workers, and scale each group on its own Shared codebase and schema, but the workload no longer competes with request handling
Slow request paths Move work to background jobs or a queue inside the monolith Adds async behavior without a new deployable
Database read load Read replicas or caching Stale reads to manage, and write contention is unchanged
A non-core capability Replace it with an off-the-shelf third-party service instead of building your own Less control, and a vendor dependency to manage
The whole codebase seems wrong Full rewrite High risk: no reversible cutover, and the old system keeps changing while you rebuild it

The role-based process split is often overlooked. It gives you independent scaling and some failure isolation for a workload without a new codebase, API contract or database. If that solves the problem, extraction can wait.

Choose extraction when the requirement is specifically independent deployability or data ownership that none of these provide.

What does the first extraction cost, and when is it worth it?

The first extraction costs far more than the code you move, because it also builds the platform every later service depends on. Budget for that groundwork explicitly:

Groundwork First extraction Later extractions
Deployment pipeline Build from scratch Copy template
Service discovery / config Choose and wire up Register new entry
Tracing and correlated logs Propagate IDs end to end Already flowing
Service-to-service auth Design identity and policy Issue credentials
On-call ownership Define rotation and runbooks Add service to rotation

Illustrative estimate (assumed numbers, not a benchmark). Assume the platform work costs P = 8 engineer-weeks, and service-specific work costs S = 4 engineer-weeks per service.

  • Formula: total cost for N services = P + N × S.
  • For N = 1, the cost is 12 weeks, two-thirds of it overhead.
  • For N = 4, the cost is 24 weeks, an average of 6 weeks per service.

Ongoing operations add a fixed cost on top: rotations, pipeline upkeep, and dependency patching.

If one small team owns the whole monolith and deploys rarely conflict, extraction buys little and the fixed cost never amortizes. In that case, keep the in-process module boundary from earlier and stop there.

Set exit criteria before you start

  • The service deploys independently in practice, on its own schedule.
  • No schema change has needed coordinated releases across the boundary.
  • The new network call stays within an agreed error budget for errors and latency.
  • A dated review decides whether to keep the service or fold it back. A wrong boundary costs less to revert early than to maintain.

How can this approach save engineering time?

The time savings come from two places: avoiding wasted work during the extraction, and removing coordination overhead after it.

During the extraction, each step is ordered so that mistakes surface while they are still cheap:

  • Coupling analysis before code. The co-change script, dependency graph and data access map can rule out a bad candidate in an afternoon. Otherwise the team finds the same shared tables weeks into a half-built service.
  • Boundary inside the monolith first. Untangling dependencies in-process means a wrong call costs a failed build or a recompile, not a production incident or a cross-service debugging session.
  • Reversible routing. Shadow traffic finds mismatches before users do, and a flag-based rollback takes seconds. That replaces incident response and hotfix deploys with a config change.
  • Outbox and reconciliation. Avoiding dual writes removes a class of silent data divergence that is slow to detect and slow to repair by hand.
  • Reusable groundwork. The pipeline, tracing, auth and on-call setup built for the first service are reused by later ones, which is why per-service cost falls in the estimate above.

After the extraction, the service's team stops paying for the shared release. They no longer wait in a release queue for unrelated changes, run the full monolith test suite for every change, or negotiate schema changes with other teams.

Illustrative estimate (assumed numbers, not a measurement). Assume a team of 6 engineers each loses 2 hours per week to release coordination, blocked merges and waiting on unrelated failures in the shared pipeline, and assume extraction removes that loss for this team.

  • Recovered time: 6 × 2 = 12 engineer-hours per week, or 0.3 engineer-weeks per week at an assumed 40-hour week.
  • Against the assumed 12 engineer-weeks for the first extraction, payback takes 12 / 0.3 = 40 weeks, before ongoing operational costs.
  • A later extraction at the assumed 4 engineer-weeks of service-specific work pays back in about 13 weeks under the same assumptions.

Measure your own coordination overhead before relying on this estimate. If the assumed loss doesn't exist on your team, the time savings don't either, and the modular-monolith alternative is the better use of the effort.

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 extract microservice from 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.