DEV Community

Gayatri Chakrabarty
Gayatri Chakrabarty

Posted on

The Strangler Fig Pattern in Practice: Routing, Data Sync and Rollback in Python

A working strangler fig example: a routing facade with gradual rollout and a kill switch, an anti-corruption layer, outbox-based data sync and reconciliation, in standard-library Python.

Disclosure: I work at Blue Copper Technologies, which helps companies modernize legacy business applications. This post was drafted with AI assistance and reviewed by me, and every code sample was run before publishing. Last updated 23 November 2026.

TL;DR

The strangler fig pattern replaces a legacy system piece by piece: a facade sits in front of the old system, and you move one capability at a time to new code while both run side by side. The idea is easy. The hard parts are the routing rules, keeping data in sync while two systems own it, and being able to roll back in seconds.

This post builds all three in about 120 lines of standard-library Python:

  • a routing facade with per-route ownership, gradual percentage rollout, automatic fallback and a kill switch;
  • an anti-corruption layer that stops legacy field names leaking into the new code;
  • outbox-based data sync from the legacy database to the new store, plus a **reconciliation **check that proves they match.

What is the strangler fig pattern?

The strangler fig pattern is a way to modernize a legacy system incrementally. You put an interception layer in front of it, build new capabilities next to it, and shift traffic from old to new one slice at a time until the old system can be switched off. Martin Fowler named it after strangler figs, which grow around a host tree. In his words, it "begins with small additions, often new features, that are built on top of, yet separate to the legacy code base."

Microsoft's architecture guidance describes the core mechanism: "A façade (proxy) intercepts requests that go to the back-end legacy system. The façade routes these requests either to the legacy application or to the new services."

Strangler fig pattern vs strangler pattern: they are the same thing. "Strangler application" was the earlier name. Fowler now uses "strangler fig" to make the metaphor clearer.

When should you use it, and when not?

Use it when the legacy system is too big or too risky to replace in one cutover, and you can intercept its traffic (HTTP, messages, or file drops).

Microsoft's guidance lists cases where it does not fit:

  • requests to the back end cannot be intercepted;
  • you cannot access the legacy source code and it has no other integration point you can change, such as its database;
  • the system is small enough that replacing it whole is simple;
  • you need to decommission the original quickly.

Fowler adds a cost people often skip: you will build "transitional architecture to allow the new and legacy system to coexist, code that will go away once the modernization is complete." The facade, the sync and the reconciliation below are exactly that code. Budget for them.

Step 1: a routing facade with rollout and a kill switch

The facade needs three things: a routing table that says who owns each path, a way to send only some users to the new code, and a way to send everyone back to legacy at once.
routing.py holds the decision logic, kept separate from HTTP so it is easy to test:

import hashlib

# Each rule: path prefix, which backend owns it, and what share of users go to "new".
ROUTES = [
    {"prefix": "/invoices", "owner": "new", "rollout": 100},
    {"prefix": "/customers", "owner": "new", "rollout": 10},
    {"prefix": "/", "owner": "legacy", "rollout": 0},
]

def bucket(user_id: str) -> int:
    """Stable 0-99 bucket, so a user always lands on the same side."""
    return int(hashlib.sha256(user_id.encode()).hexdigest(), 16) % 100

def choose_backend(path: str, user_id: str, routes=ROUTES, kill_switch=False) -> str:
    if kill_switch:
        return "legacy"
    for rule in routes:  # first match wins, so list specific prefixes first
        if path.startswith(rule["prefix"]):
            if rule["owner"] == "new" and bucket(user_id) < rule["rollout"]:
                return "new"
            return "legacy"
    return "legacy"
Enter fullscreen mode Exit fullscreen mode

Hashing the user ID gives each user a stable bucket. The same user always sees the same side during a rollout, which avoids a session flipping between two implementations on every request.

facade.py is a small reverse proxy that applies the decision. It also falls back to legacy if the new service fails, and labels every response so you can see who served it:

import os
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from routing import choose_backend

BACKENDS = {
    "legacy": os.environ.get("LEGACY_URL", "http://127.0.0.1:8001"),
    "new": os.environ.get("NEW_URL", "http://127.0.0.1:8002"),
}

class Facade(BaseHTTPRequestHandler):
    def do_GET(self):
        user_id = self.headers.get("X-User-Id", "anonymous")
        kill = os.environ.get("STRANGLER_KILL_SWITCH") == "1"
        target = choose_backend(self.path, user_id, kill_switch=kill)
        req = urllib.request.Request(BACKENDS[target] + self.path,
                                     headers={"X-User-Id": user_id})
        try:
            with urllib.request.urlopen(req, timeout=5) as resp:
                body, status = resp.read(), resp.status
        except Exception:
            if target == "new":  # fall back instead of failing the user
                with urllib.request.urlopen(BACKENDS["legacy"] + self.path, timeout=5) as resp:
                    body, status, target = resp.read(), resp.status, "legacy"
            else:
                raise
        self.send_response(status)
        self.send_header("X-Served-By", target)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass

if __name__ == "__main__":
    ThreadingHTTPServer(("127.0.0.1", 8000), Facade).serve_forever()
Enter fullscreen mode Exit fullscreen mode

In production you would put this logic in the proxy or gateway you already run (NGINX, Envoy, YARP, an API gateway or a service mesh) rather than a Python server. The rules stay the same: ownership per route, a stable rollout bucket, fallback, a kill switch and a response header for tracing.

Microsoft's guidance warns: "Make sure that the façade doesn't become a single point of failure or a performance bottleneck." Run it with the same redundancy as the system behind it.

Step 2: an anti-corruption layer

Legacy schemas carry decades of naming conventions. If the new code reads CUST_NM and STATUS_CD directly, the old model leaks into the new one and you rebuild the monolith with new technology.
An anti-corruption layer translates at the boundary. Microsoft describes it as "an adapter that translates requests between the two systems." Here it is one function:

from datetime import datetime

def legacy_to_customer(row: dict) -> dict:
    """Anti-corruption layer: legacy field names and formats stop here."""
    return {
        "id": f"cus_{int(row['CUST_NO'])}",
        "name": row["CUST_NM"].strip().title(),
        "email": (row.get("EMAIL_ADDR") or "").strip().lower() or None,
        "active": row["STATUS_CD"] == "A",
        "created_at": datetime.strptime(row["CRT_DT"], "%d%m%Y").date().isoformat(),
    }
Enter fullscreen mode Exit fullscreen mode

Every legacy quirk (padded names, upper case, DDMMYYYY dates, single-letter status codes) is handled here and nowhere else. When the legacy system goes away, this file goes with it.

Step 3: keeping data in sync with an outbox

While a capability is half migrated, both systems need the same data. Writing to both from application code (dual writes) breaks the first time one write succeeds and the other fails.

A safer approach is an outbox: the legacy database records every change in an outbox table, inside the same transaction as the change. A sync worker reads the outbox in order and applies each change to the new store. Here the outbox is filled by database triggers, so the legacy application code does not change at all.

import json
import sqlite3
from acl import legacy_to_customer

LEGACY_SCHEMA = """
CREATE TABLE CUST_MST (CUST_NO INTEGER PRIMARY KEY, CUST_NM TEXT, EMAIL_ADDR TEXT,
                       STATUS_CD TEXT, CRT_DT TEXT);
CREATE TABLE outbox (seq INTEGER PRIMARY KEY AUTOINCREMENT, cust_no INTEGER);
CREATE TRIGGER cust_ins AFTER INSERT ON CUST_MST
  BEGIN INSERT INTO outbox (cust_no) VALUES (NEW.CUST_NO); END;
CREATE TRIGGER cust_upd AFTER UPDATE ON CUST_MST
  BEGIN INSERT INTO outbox (cust_no) VALUES (NEW.CUST_NO); END;
"""

NEW_SCHEMA = """
CREATE TABLE customers (id TEXT PRIMARY KEY, doc TEXT);
CREATE TABLE sync_state (k TEXT PRIMARY KEY, v INTEGER);
"""

def sync_once(legacy: sqlite3.Connection, new: sqlite3.Connection, batch=500) -> int:
    row = new.execute("SELECT v FROM sync_state WHERE k='last_seq'").fetchone()
    last_seq = row[0] if row else 0
    legacy.row_factory = sqlite3.Row
    events = legacy.execute(
        "SELECT o.seq, c.* FROM outbox o JOIN CUST_MST c ON c.CUST_NO = o.cust_no "
        "WHERE o.seq > ? ORDER BY o.seq LIMIT ?", (last_seq, batch)).fetchall()
    for ev in events:
        doc = legacy_to_customer(dict(ev))
        # Upsert keeps the worker idempotent: replaying an event is harmless.
        new.execute("INSERT INTO customers (id, doc) VALUES (?, ?) "
                    "ON CONFLICT(id) DO UPDATE SET doc = excluded.doc",
                    (doc["id"], json.dumps(doc, sort_keys=True)))
        last_seq = ev["seq"]
    new.execute("INSERT INTO sync_state (k, v) VALUES ('last_seq', ?) "
                "ON CONFLICT(k) DO UPDATE SET v = excluded.v", (last_seq,))
    new.commit()
    return len(events)

def reconcile(legacy: sqlite3.Connection, new: sqlite3.Connection) -> list:
    """Return ids whose translated legacy record differs from the new store."""
    legacy.row_factory = sqlite3.Row
    mismatches = []
    for r in legacy.execute("SELECT * FROM CUST_MST"):
        expected = legacy_to_customer(dict(r))
        got = new.execute("SELECT doc FROM customers WHERE id = ?", (expected["id"],)).fetchone()
        if got is None or json.loads(got[0]) != expected:
            mismatches.append(expected["id"])
    return mismatches
Enter fullscreen mode Exit fullscreen mode

Three details matter:

  • The worker is idempotent. It upserts, so replaying an event does no harm. If it crashes, it restarts from last_seq.
  • It reads the current row from the legacy table. The event only says which customer changed. If a customer changed three times, the worker writes the latest state each time and ends up correct.
  • Reconciliation is separate from sync. reconcile() translates every legacy row and compares it with the new store. Run it on a schedule and alert on any mismatch. It is your proof that the new system can take over reads.

In production, change data capture tools such as Debezium do the outbox reading from the database log. The pattern is the same.

Step 4: Run it

This test wires everything together: routing rules, a 10% rollout, sync of an insert and an update, a deliberately corrupted record caught by reconciliation, and the facade serving real HTTP with fallback and the kill switch.

import json, os, sqlite3, threading, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from routing import choose_backend, bucket
from sync import LEGACY_SCHEMA, NEW_SCHEMA, sync_once, reconcile

# routing
assert choose_backend("/invoices/42", "u1") == "new"
assert choose_backend("/orders/1", "u1") == "legacy"
assert choose_backend("/invoices/42", "u1", kill_switch=True) == "legacy"
share = sum(choose_backend("/customers/1", f"user{i}") == "new" for i in range(10000)) / 100
print("share of users on new /customers:", share, "%")
assert 8 < share < 12
assert all(choose_backend("/customers/1", "u7") == choose_backend("/customers/9", "u7") for _ in range(5))

# sync
legacy, new = sqlite3.connect(":memory:"), sqlite3.connect(":memory:")
legacy.executescript(LEGACY_SCHEMA); new.executescript(NEW_SCHEMA)
legacy.execute("INSERT INTO CUST_MST VALUES (1001,'  ACME TRADING ','Ops@Acme.example','A','05032019')")
legacy.execute("INSERT INTO CUST_MST VALUES (1002,'BETA LTD',NULL,'I','17112021')")
legacy.commit()
print("synced", sync_once(legacy, new))
legacy.execute("UPDATE CUST_MST SET STATUS_CD='A' WHERE CUST_NO=1002"); legacy.commit()
print("synced", sync_once(legacy, new))
print("synced", sync_once(legacy, new))
print("mismatches:", reconcile(legacy, new))
assert reconcile(legacy, new) == []
new.execute("UPDATE customers SET doc='{}' WHERE id='cus_1001'")
print("after tampering:", reconcile(legacy, new))
print(new.execute("SELECT doc FROM customers WHERE id='cus_1002'").fetchone()[0])

# facade end to end
def make(name):
    class H(BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200); self.end_headers()
            self.wfile.write(json.dumps({"from": name}).encode())
        def log_message(self, *a): pass
    return H
servers = [ThreadingHTTPServer(("127.0.0.1", p), make(n)) for p, n in [(8001, "legacy"), (8002, "new")]]
import facade
servers.append(ThreadingHTTPServer(("127.0.0.1", 8000), facade.Facade))
for s in servers: threading.Thread(target=s.serve_forever, daemon=True).start()
def get(path, uid="u1"):
    r = urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:8000" + path, headers={"X-User-Id": uid}))
    return r.headers["X-Served-By"], r.read().decode()
print(get("/invoices/42")); print(get("/orders/7"))
servers[1].shutdown(); servers[1].server_close()
print("new down ->", get("/invoices/42"))
os.environ["STRANGLER_KILL_SWITCH"] = "1"; print("kill switch ->", get("/invoices/42"))
print("ALL OK")
Output:
share of users on new /customers: 9.91 %
synced 2
synced 1
synced 0
mismatches: []
after tampering: ['cus_1001']
{"active": true, "created_at": "2021-11-17", "email": null, "id": "cus_1002", "name": "Beta Ltd"}
('new', '{"from": "new"}')
('legacy', '{"from": "legacy"}')
new down -> ('legacy', '{"from": "legacy"}')
kill switch -> ('legacy', '{"from": "legacy"}')
ALL OK
Enter fullscreen mode Exit fullscreen mode

Put the four files in one folder and run python3 test_all.py. No packages are needed.

How to roll out one slice

For each capability you move, this sequence keeps every step reversible:

  • Pick a boundary that matches a business capability such as invoicing, customer profile or pricing.
  • Build the anti-corruption layer for the data that capability reads.
  • Start sync and reconciliation. Do not route any traffic until reconciliation has shown zero mismatches for a period you trust.
  • Shadow read (optional): call both sides, return the legacy answer, and log any difference.
  • Roll out by percentage: 1%, 10%, 50%, 100%, watching error rates and X-Served-By in your logs at each step.
  • Move writes last. Once the new side owns writes for that capability, reverse the sync direction if legacy screens still need the data.
  • Delete the legacy path and its route rule. Until you do, the migration is not finished.

Common mistakes

  • Slicing by technical layer. Moving "the database" or "the UI" first leaves both systems half dependent on each other.
  • Dual writes from application code. They drift silently. Use an outbox or change data capture.
  • No reconciliation. Without a regular comparison, you find drift when a customer does.
  • A facade that becomes permanent. Microsoft notes you can keep it as an adapter for legacy clients, but every rule left in it is legacy you still run.
  • No end date. Fowler's point about transitional architecture cuts both ways: plan to remove it, or it becomes the next legacy system.

References

Which capability would you move out of your monolith first, and what is stopping you? Tell me in the comments.

Gayatri Chakrabarty works at Blue Copper Technologies, a technology company in Kolkata, India, that modernizes legacy business applications for enterprise, mid-market and SME companies. Read how the team approaches platform modernization and legacy migration, or get in touch.

Top comments (0)