What is a strangler fig pattern migration, and why does it depend on the routing layer?

A strangler fig pattern migration replaces a legacy monolith piece by piece. You do not rewrite it in one go. A routing facade sits in front of the monolith and receives every request. For each request, the facade decides whether the old code or a newly extracted service handles it. Over time, more routes point to new services. The monolith shrinks until it can be switched off or reduced to a small core. The name comes from a vine that grows around a host tree and eventually replaces it.

Teams choose this over a full rewrite for two reasons:

  • Value ships continuously. A rewrite usually freezes features for months while the new system catches up with a moving target. Incremental extraction lets you move one capability, such as invoicing or search, and put it into production while the rest of the business keeps running on the monolith.
  • Rollback stays cheap. Every extracted route can be pointed back at the monolith, as long as the legacy path still works. That makes each step a reversible change instead of one high-stakes cutover.

This guide focuses on the facade, because the facade decides which code serves each request. Treating it as a temporary hack, with hand-edited proxy rules and no tests, is a common way these migrations fail. Version the routing layer, review it, test it and deploy it like any other production service.

The approach suits backend and platform teams responsible for a live monolith that cannot be frozen, where the business needs both new features and a gradual, recoverable path off the old system.

Where should the routing facade live: edge proxy, API gateway, or in-monolith dispatch?

The facade can sit in three places, and each one changes who can break it and how far the damage spreads.

Placement Extra hops Config owner Blast radius on failure
Edge proxy One, often already present Platform team All traffic, old and new
API gateway One, plus any auth or rate-limit plugins Platform or API team All routed APIs
In-monolith dispatch Zero for monolith paths, one for extracted ones Monolith team Tied to monolith uptime

In-monolith dispatch avoids new infrastructure, but extracted services stay reachable only while the monolith is healthy. The goal is to retire the monolith, so this dependency defeats the purpose. It is useful for a first spike and should be moved out afterward.

An edge proxy or gateway decouples the two paths, but it becomes a single point of failure for old and new code together. If the proxy loses its config or runs out of connections, the monolith goes down even though nothing in it changed. Deploy the facade with at least the availability you expect from the monolith. That means multiple instances spread across failure domains, health-checked upstreams, and config reloads that do not drop in-flight connections. Measure the added latency of the hop on your own traffic rather than assuming it is negligible.

            ┌──────────┐
 client ──► │  facade  │
            └────┬─────┘
        ┌────────┴─────────┐
        ▼                  ▼
  ┌──────────┐      ┌────────────┐
  │ monolith │      │ extracted  │
  └────┬─────┘      │  service   │
       │            └─────┬──────┘
       ▼                  ▼
 [shared legacy DB]  [owned store]
       ▲                  │
       └── reads (temp) ──┘
                         ┌──────────┐
                         │  client  │
                         └────┬─────┘
                              │ all traffic, old and new
                              ▼
        ┌────────────────────────────────────────────┐
        │  facade: shared single point of failure    │
        │  ┌──────────┐ ┌──────────┐ ┌──────────┐    │
        │  │ instance │ │ instance │ │ instance │    │
        │  │  zone A  │ │  zone B  │ │  zone C  │    │
        │  └──────────┘ └──────────┘ └──────────┘    │
        │  health-checked upstreams, hitless reloads │
        └────────┬───────────────────────┬───────────┘
                 │ legacy routes         │ extracted routes
                 ▼                       ▼
           ┌────────────┐          ┌────────────┐
           │  monolith  │          │ extracted  │
           │            │          │  service   │
           └─────┬──────┘          └──┬─────┬───┘
                 │ read/write         │     │ read/write
                 ▼                    │     ▼
        ┌──────────────────┐          │ ┌─────────────┐
        │ shared legacy DB │◄─────────┘ │ owned store │
        └──────────────────┘ temp reads └─────────────┘

Every request, legacy or extracted, passes through the facade, so it must run as multiple health-checked instances across failure domains while the extracted service temporarily reads the shared legacy database alongside its own store.

How do you choose routing keys for incremental extraction?

A routing key is whatever the facade inspects to decide where a request goes. Choose the narrowest key that cleanly separates the behavior you are extracting from the behavior you are not.

Path plus method is the default. GET /invoices/{id} can move while POST /invoices stays put, so reads can migrate before writes. Path alone breaks when one URL serves several domain concepts. A generic POST /documents?type=invoice|quote|credit_note looks like one route, but it is three behaviors. If you route on the path, you extract all three at once or none.

To split traffic below the path, use the other keys:

  • Header: an explicit header such as X-Route-Target, or a content type that varies per concept. This is useful for internal callers you control.
  • Query or body discriminator: match on type=invoice. Prefer query parameters, because body inspection forces the proxy to buffer requests.
  • Tenant: send whole tenants across so their data stays consistent within one system.
  • User cohort: hash a stable user ID into buckets for a percentage rollout. Hashing keeps each user on the same backend across requests.

Express the rules declaratively and evaluate them in a fixed order, first match wins:

  1. POST /documents with type=invoice and tenant in the pilot list goes to the invoice service.
  2. GET /invoices/* for cohort buckets 0–9 goes to the invoice service.
  3. Everything else goes to the monolith.

The final rule matters. An unmatched request must never fail, so the monolith stays the fallback.

# http context. Upstreams: the monolith is always the fallback.
upstream monolith    { server monolith.internal:8080; }
upstream invoice_svc { server invoice-svc.internal:8080; }

# Tenant key: pilot tenants (from a trusted, gateway-set header).
map $http_x_tenant_id $tenant_pilot {
    default  0;
    acme-eu  1;
    globex   1;
}

# Cohort key: hash a stable user ID so each user stays on one backend.
# 10% of the hash space approximates buckets 0-9 out of 100.
split_clients "${http_x_user_id}" $cohort {
    10%  pilot;
    *    rest;
}

# Composite routing key: METHOD:PATH:type:tenant_pilot:cohort.
# Regex variants are checked in order of appearance, so first match wins.
map "$request_method:$uri:$arg_type:$tenant_pilot:$cohort" $backend {
    # 1. Invoice creation through the generic endpoint, pilot tenants only.
    #    Path alone cannot do this: quote and credit_note share the URL.
    "~^POST:/documents:invoice:1:"                    invoice_svc;
    # 2. Invoice reads for the hashed user cohort.
    "~^GET:/invoices/[^:]+:[^:]*:[^:]*:pilot$"        invoice_svc;
    # 3. Everything else, including unmatched requests, goes to the monolith.
    default                                            monolith;
}

server {
    listen 80;
    location / {
        # $backend resolves to an upstream name; the original URI is passed through.
        proxy_pass
        proxy_set_header Host $host;
    }
}

An nginx facade combines path plus method, a query discriminator, a tenant allow-list and a hashed user cohort into one ordered routing key, and falls back to the monolith when no rule matches.

How does a reversible cutover work in practice?

Shifting traffic happens in one of two ways. Percentage-based shifting sends a fraction of all requests to the new service. Cohort-based shifting sends specific users or tenants, such as internal staff or one low-risk customer. Cohorts limit the blast radius. Percentages give a statistically representative sample sooner.

Both need sticky assignment. Hash a stable identifier such as the user or tenant ID, take the result modulo 100, and compare the bucket against the configured threshold. The same ID always lands in the same bucket, so a user never alternates between backends mid-session and sees inconsistent state. Raising the threshold from 10 to 20 adds users without moving anyone who is already migrated. Avoid hashing session IDs or request IDs, because they change too often to keep assignment stable.

Every route also needs one kill switch that sends all traffic back to the monolith. It must be a single flag that on-call engineers can flip without a deploy, not a set of per-rule edits made during an incident.

Before you shift real traffic, shadow it. The proxy mirrors read requests to the new service and discards those responses. A harness compares them offline against the monolith's responses, ignoring fields such as timestamps. Mirrored writes are more dangerous. They need idempotency keys, and their side effects (email, payments, third-party API calls) must be stubbed or isolated. Otherwise a customer could be charged twice.

There are two costs to plan for:

  • Shadowing roughly doubles load on shared downstream dependencies, so check their capacity first.
  • Cohort routing makes bugs harder to reproduce. Log the bucket and the backend that served each request, so a support ticket can be traced to the code path that handled it.
import hashlib
import json

IGNORED_FIELDS = {"timestamp", "request_id", "generated_at"}  # expected to differ

def bucket(tenant_id: str, route: str) -> int:
    # Stable ID in, stable bucket out. Salting with the route name gives each
    # route an independent split. Never hash session or request IDs.
    digest = hashlib.sha256(f"{route}:{tenant_id}".encode()).digest()
    return int.from_bytes(digest[:8], "big") % 100

def choose_backend(tenant_id: str, route: str, threshold: int, kill_switch: bool):
    # One flag overrides every rule and sends all traffic back to the monolith.
    if kill_switch:
        return "monolith", None
    b = bucket(tenant_id, route)
    # Raising threshold from 10 to 20 adds buckets 10-19. Nobody already migrated moves.
    backend = "new-service" if b < threshold else "monolith"
    # Log the bucket and backend so a support ticket maps to a code path.
    print(json.dumps({"tenant": tenant_id, "route": route, "bucket": b, "backend": backend}))
    return backend, b

def strip(obj):
    # Recursively drop fields that legitimately differ between backends.
    if isinstance(obj, dict):
        return {k: strip(v) for k, v in obj.items() if k not in IGNORED_FIELDS}
    if isinstance(obj, list):
        return [strip(v) for v in obj]
    return obj

def diff_shadow_log(path: str) -> int:
    # Offline diff of mirrored reads. Each line has the form:
    # {"request": ..., "monolith": {...}, "shadow": {...}}
    mismatches = 0
    with open(path) as f:
        for line in f:
            rec = json.loads(line)
            if strip(rec["monolith"]) != strip(rec["shadow"]):
                mismatches += 1
                print("MISMATCH", json.dumps(rec["request"]))
    return mismatches

Deterministic tenant bucketing with a single kill switch and per-request logging of bucket and backend, plus an offline harness that diffs mirrored read responses while ignoring volatile fields.

Who owns the data, sessions and auth during extraction?

Routing decides which code handles a request. It does not decide which code owns the row that request changes. Plan the data move as separate phases, and record for each one where the truth lives and whether you can still route back.

Phase Source of truth Rollback
Shared database: new service reads and writes the monolith's tables Monolith schema Clean: both paths see the same rows
CDC or dual writes into a new store Monolith, with the new store as a replica Clean if the monolith stays authoritative and you reconcile drift
New service owns its store New service Not clean without a backfill

Rollback breaks in the third phase because the new service starts accepting writes the monolith never sees. These include new orders, changed fields and records that exist only in the new schema. If you flip the route back, the monolith serves stale or missing data. Before you take that step, build a reverse sync, or accept that rollback now means a data migration rather than a config change.

Sessions and auth

Users should not notice which backend served them. Terminate authentication at the proxy, or have every service validate the same token format and signing keys. Otherwise each route change can force a re-login. Authorization is easier to get wrong. If permission checks are copied into the new service, they will drift from the monolith's rules. Pick one policy source and have both sides call it or load it.

Watch for an extracted service that calls back into the monolith synchronously for every request. That adds latency and couples the two services' availability. It also means the extraction is not finished.

How do you operate routing config as code, with observability and cleanup?

Keep routing rules in the same repository and review process as application code. A route change shifts production traffic, so it should go through pull requests, required reviewers from both the owning team and the platform team, and an automated pipeline. Never apply it as a hand edit on a proxy console.

Test precedence, not just syntax

Most routing bugs come from ordering, not typos. A broad prefix such as /orders/ placed above a narrower /orders/export will silently send traffic to the wrong backend. Write table-driven tests that load the real config and assert, for each sample request, which backend wins. For example, a test can assert that GET /orders/123 resolves to orders-service while GET /orders/export still resolves to monolith. It can also assert that an unmatched path falls through to monolith as the default. Run these tests in CI so a reordering that breaks precedence fails the build.

Tag every request with its backend

Have the facade attach the serving backend to every request. Use a structured log field such as served_by=orders-service and a response header such as X-Served-By. With that field, you can group error rate and p99 latency by route and backend. You can also alert when the extracted path diverges from the legacy baseline beyond a threshold you have agreed on in advance. Without it, a regression after cutover looks like general noise.

Retire dead routes

After a cutover has held long enough to rule out rollback, delete the monolith fallback rule and the dead handler code in the same change. Track route count over time. If rules only ever accumulate, the facade becomes the next legacy system.

import json
import pytest

# In the real repo, load this from the same routes file the facade deploys.
ROUTES = [
    ("/orders/export", "monolith"),  # narrow rule must stay above the broad prefix
    ("/orders/", "orders-service"),
]
DEFAULT_BACKEND = "monolith"  # anything unmatched still goes to the legacy app

def resolve(path):
    """First match wins, mirroring the facade's evaluation order."""
    for prefix, backend in ROUTES:
        if path.startswith(prefix):
            return backend
    return DEFAULT_BACKEND

@pytest.mark.parametrize("path, expected", [
    ("/orders/123", "orders-service"),
    ("/orders/export", "monolith"),  # fails if someone moves /orders/ above it
    ("/invoices/9", "monolith"),      # unmatched path falls through to default
])
def test_route_precedence(path, expected):
    assert resolve(path) == expected

def access_log(method, path, status, duration_ms):
    """Structured log line plus response header naming the serving backend."""
    backend = resolve(path)
    line = json.dumps({"method": method, "path": path, "status": status,
                       "duration_ms": duration_ms, "served_by": backend})
    return line, {"X-Served-By": backend}

def test_every_request_is_tagged():
    line, headers = access_log("GET", "/orders/123", 200, 42)
    # Dashboards group error rate and p99 latency by this field.
    assert json.loads(line)["served_by"] == "orders-service"
    assert headers["X-Served-By"] == "orders-service"

A table-driven pytest suite that fails the build if route ordering breaks precedence or the default fallback, and checks that every request is tagged with its serving backend in a structured log field and an X-Served-By header.

When should you avoid a strangler fig migration, and what are the alternatives?

The pattern pays off only when the monolith is large enough, and its seams clean enough, to support many independent extractions. It fits poorly in four cases:

  • Small monoliths. If one team understands the whole codebase, a proxy and a second deployment pipeline add more surface than they remove.
  • Tightly coupled cores. When every request touches the same shared tables and in-process transactions, no route can be moved without introducing distributed writes.
  • Teams that cannot run two systems. The main cost is dual on-call, dual deploys and dual monitoring, not the proxy.
  • Stalled migrations. If you extract the easy edges, such as static content or read-only reports, and then stop, you keep both systems and the hard core remains untouched.
Approach Rollback unit Upfront cost Fits when
Strangler fig Route rule in the facade Proxy plus dual operations Seams exist at the request boundary
Modular monolith refactor Commit Low, one deployable The problem is code structure, not deployment
Branch by abstraction In-code toggle Moderate, abstraction layer Seams exist inside the code, not over HTTP
Full rewrite None until launch Highest, often a feature freeze The system is small or the domain has changed

Illustrative estimate, using assumed inputs. Building the facade takes 3 engineer-weeks. Running two systems adds half an engineer-day per week. The migration lasts 40 weeks. That gives about 7 engineer-weeks of overhead. Now assume the facade prevents four coordinated cross-team releases, each costing 2 engineer-weeks in scheduling and incident cleanup. The two sides roughly break even. If you expect fewer extractions than that, refactor inside the monolith instead.

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 strangler fig pattern 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.