Strangler Fig: Safe System Migration
"The alternative that my colleagues and I prefer, is to do a gradual process of modernization." — Martin Fowler, Strangler Fig, martinfowler.com bliki (22 August 2024)
Summary: A strangler fig migration replaces a running system one slice at a time: a facade in front of it routes each request to the legacy system or the new one, the new side grows while traffic and data move over, and the legacy side is switched off only when nothing depends on it. Focus: Seams and slicing, the facade (proxy, API gateway, NGINX, Envoy, Istio), routing by path, header, tenant and percentage, shadow traffic and response diffing, canary and progressive delivery, feature flags (Laravel Pennant), parallel run and reconciliation, dual write and its dangers, change data capture, database views, expand/contract, backfill, reads and writes during the migration, branch by abstraction, UI composition, anti-corruption layers, contract tests and traffic replay, kill switches and rollback plans, cutover and decommission, migration metrics, anti-patterns, and four public case examples. Learning goal: For any legacy system, pick the first seam, put a facade in front, move one slice through shadow, canary and cutover with written exit criteria, keep the data correct while two systems own it, prove each step with a diff and a number, and be able to undo every step in minutes.
This chapter closes the Distributed Systems Primitives group. It uses the routing and failure tools from Load Balancing, Forward vs Reverse Proxies, Circuit Breaker and API Idempotency; API Gateway, BFF & Service Mesh owns the gateway product detail, Change Data Capture owns log-based CDC, Zero-Downtime Schema Migrations owns expand/contract on one database, and Context Maps & Integration Patterns owns the anti-corruption layer as a domain pattern. This page owns the system-level decision: the order of the steps, the numbers that tell you to go on or go back, and the data rules while two systems own the same facts.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why not rewrite it all at once | Why it exists |
| Fowler, Newman, Hammant, Cartwright/Horn/Lewis | Where it comes from |
| The proxy that intercepts and redirects | The facade |
| Finding the first slice | Seams and slicing |
| Path, header, tenant, percentage rules | Routing rules |
| Shadow traffic, dark launch, diffing | Shadow traffic |
| Canary, progressive delivery, flags | Canary and flags |
| Old and new side by side | Parallel run and reconciliation |
| Dual write and why it hurts | Dual write |
| CDC, event interception, views, synonyms | Moving the data |
| Writes during the migration | Reads and writes |
| Replacing code inside one process | Branch by abstraction |
| Replacing the screens | UI composition |
| Keeping legacy concepts out of new code | Anti-corruption layer |
| Contract tests, replay | Testing |
| Switches and undo | Kill switch and rollback |
| The last two steps | Cutover and decommission |
| Teams, timeline, progress numbers | Organisation and metrics |
| What goes wrong | Anti-patterns |
| Shopify, Zalando, Monzo, Uber | Case examples |
| Exact knobs and error names | Mechanics |
| Code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| Which technique when | Choosing |
| Monolith to distributed system | In architecture |
| Runnable experiments | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The loop, per slice.
| Step | What you do | Evidence to move on | Undo |
|---|---|---|---|
| 1. Seam | Find a boundary where traffic can be cut: a URL prefix, a queue, a table owner | The seam has a test and an owner | Nothing changed yet |
| 2. Facade | Put a proxy in front; route everything to legacy | Latency and error rate unchanged | Remove the proxy, point DNS back |
| 3. Build | New code behind a flag, tested against the contract | Contract tests green | Delete the branch |
| 4. Shadow | Mirror safe requests to the new code, diff the answers | Diff rate below the goal for N days | Turn mirroring off |
| 5. Canary | Send 1%, 5%, 25%, 50% of live traffic | SLOs held at each step | Percentage to 0 |
| 6. Cutover | 100% to new, legacy warm | Soak period passes | Kill switch to legacy |
| 7. Decommission | Delete legacy code, routes, tables | Nothing calls legacy for a full cycle | Restore from archive only |
Routing dimensions at the facade.
| Dimension | Example rule | Typical use | Weakness |
|---|---|---|---|
| Path | /orders/* goes to new | Coarse slices | Whole endpoint moves at once |
| Header | X-Route: new | Staff, tests, canary testers | Not for real users |
| Tenant | acme is migrated | B2B, easy rollback per customer | Uneven load |
| Percentage | 5% of users by sticky hash | Canary | A bad 5% is still 5% of customers |
| Method | GET to new, POST to legacy | Read slice first | Reads and writes diverge |
Data patterns while two systems own the data.
| Pattern | Idea | Risk |
|---|---|---|
| Shared database | New service reads and writes legacy tables | Hidden coupling, schema freeze |
| Database view or synonym | New code reads through a view | Read only, performance |
| Dual write | Application writes both stores | Partial failure, drift, ordering |
| Change data capture | Read the legacy log and apply to new | Lag, schema coupling |
| Event interception | Facade publishes an event per call | Lost events if not transactional |
| Backfill then switch | Copy history, then catch up | Window of staleness |
Anti-patterns in one line each.
| Anti-pattern | Symptom |
|---|---|
| Big-bang rewrite | Two years of no releases, then a cliff |
| Strangler that never finishes | Two systems forever, double the cost |
| Legacy becomes a dependency of the new system | New service calls the old one for core data |
| Facade becomes a monolith | Business logic creeps into the proxy |
| Dual write without reconciliation | Silent drift between stores |
Why it exists
You inherit a system that earns money and nobody dares to touch. The tempting plan is to build a new one beside it and switch on a Friday. It fails for boring reasons: the old system does a thousand things nobody wrote down, users want features during the two years of the rewrite, and on switch day every undiscovered difference arrives at once.
| Big-bang rewrite | Strangler fig |
|---|---|
| One switch day, all risk at once | Many small switches, each with a way back |
| Value arrives after the whole rewrite | Value arrives per slice |
| Old behaviour must be specified up front | Old behaviour is discovered by diffing real traffic |
| Feature freeze on the old system | Old system keeps shipping while shrinking |
| Failure means a cancelled project | Failure means one slice rolled back |
| Cost is hidden until the end | Cost shows as transitional architecture, visible every week |
An everyday picture. Renovating a restaurant without closing it. You build one new kitchen station behind a screen, cook a few dishes on it while the old station cooks the same dishes (the waiters taste both), move one table's orders to the new station, then another, and remove the old stove only when no order ticket mentions it. The screen is the facade.
Three common misunderstandings, up front
- "The strangler fig is a microservices pattern." It is a replacement strategy. You can strangle a monolith into a modular monolith, a mainframe into a monolith, or one database into another. Microservices are one possible destination.
- "The facade is just a reverse proxy." The proxy is the mechanism; the pattern is the plan around it: seams, shadowing, ramp, data rules, exit criteria, deletion.
- "When the new system takes 100% of traffic, we are done." You are done when the legacy code, routes, tables, jobs, credentials and servers are gone. Until then you pay for two systems.
Where it comes from
| Year | Who | What |
|---|---|---|
| 2001 | Martin Fowler | Sees strangler figs on a holiday in the rain forests of Queensland (his own account on the bliki) |
| 2004 | Martin Fowler | Posts "Strangler Application" on his bliki: rewrite a critical system by growing the new one around the old |
| 2019 | Martin Fowler | Renames the post "Strangler Fig Application" to stress the botanical metaphor |
| 2016 | GitHub | Publishes Scientist, a library to run old and new code paths side by side and compare |
| 2019 | Shopify | Describes its componentization of a very large Rails monolith |
| 2020 | Uber | Describes Domain-Oriented Microservice Architecture, DOMA |
| 2021 | Zalando | Describes moving its web shop from Project Mosaic to an Interface Framework |
| 2024 | Martin Fowler | Updates the page: four activities for incremental modernisation, seams, transitional architecture |
Fowler's current page credits Ian Cartwright, Rob Horn and James Lewis with four high-level activities: understand the outcomes you want, decide how to break the problem into smaller parts, successfully deliver the parts, and change the organisation so this can happen continuously. The ordering does not imply a sequence. His original 2004 post (kept as "Original Strangler Fig Application") is explicit that rewrites of critical systems are "always much more complex than they seem". Sam Newman's book Monolith to Microservices turns the idea into a pattern catalogue; its table of contents (read on the author's site) lists Strangler Fig Application, UI Composition, Branch by Abstraction, Parallel Run, Decorating Collaborator and Change Data Capture for splitting code, and Shared Database, Database View, Database Wrapping Service, Database-as-a-Service Interface, Synchronize Data in Application, Tracer Write, Split Table and Move Foreign-Key Relationship to Code for splitting data. Fowler's Branch by Abstraction page says Paul Hammant introduced the name while arguing for trunk-based development, crediting Stacy Curl with the original idea.
The concept catalogue
The facade: intercept and redirect Must-know
In plain words: Put one thing in front of the old system that every request passes through. At first it forwards everything unchanged. Later it sends some requests to the new system instead.
Common misunderstanding: "We can add the proxy at the end, when the new system is ready." Without the proxy in place first you have no way to move traffic gradually and no place to measure the difference between old and new.
Definition: A facade is a reverse proxy, API gateway, edge worker, or in-process router that intercepts requests to the legacy system and redirects each one to legacy or new according to routing rules. It must be transparent when every rule says legacy.
1 client -> facade GET /orders/42
2 facade -> rules slice "orders": path match, percent 5, user bucket 63
3 facade -> legacy forward (63 is not below 5)
4 legacy -> facade 200 {"id":42,...}
5 facade -> client 200, X-Served-By: legacy
6 facade -> metrics requests{slice=orders,backend=legacy,reason=percent}++Real scenarios: an NGINX or HAProxy in front of an old PHP application; AWS Application Load Balancer listener rules splitting by path; Cloudflare Workers or Fastly VCL at the edge; Kong or Envoy in front of a SOAP monolith; Kubernetes Ingress with a second Ingress for the new service.
| Facade type | Product examples | Good at | Careful with |
|---|---|---|---|
| Reverse proxy | NGINX, HAProxy, Envoy | Path, header, weight rules; mirroring | Rules in config files need review and deploy discipline |
| API gateway | Kong, AWS API Gateway, Apigee | Auth, rate limits, per-route plugins | Another product to own; latency |
| Service mesh | Istio, Linkerd | Weighted routes and mirroring per service | Only between services inside the mesh |
| Edge | Cloudflare Workers, Fastly, CloudFront Functions | Global, cheap, fast to change | Limited compute, no private network |
| In-process router | A middleware in the old or new app | No new hop | Couples the facade to one app |
| Load balancer | AWS ALB weighted target groups | Simple percentage | No user stickiness by default, no diff |
Fix / how to use it:
-- The facade's rule table can itself be data: one row per migrated slice.
CREATE TABLE strangler_rules (
slice text PRIMARY KEY,
path_prefix text NOT NULL,
percent_new integer NOT NULL DEFAULT 0 CHECK (percent_new BETWEEN 0 AND 100),
shadow boolean NOT NULL DEFAULT false,
tenants_new text[] NOT NULL DEFAULT '{}',
updated_at timestamptz NOT NULL DEFAULT now()
);Go: the facade is facade.Facade, an http.Handler built on httputil.ReverseProxy. Laravel: the same job is done by the strangle middleware in Laravel.
Seams and slicing Must-know
In plain words: A seam is a place where you can cut the system in two without rewriting the inside: a URL prefix, a message queue, a module interface, a table with one writer.
Common misunderstanding: "Slice by technical layer: first the database, then the services, then the UI." A layer is never a business capability, so nothing can ship alone. Slice vertically: one capability from screen to table.
Definition: Fowler's current page says that identifying seams means finding insertion points that let the system be split, and that in a well-designed system they would already exist ("such systems are unicorns"). Choose the first slice by value, risk and coupling.
| Slice candidate | Value | Risk | Coupling | Verdict |
|---|---|---|---|---|
| Read-only catalogue pages | Medium | Low | Low | Good first slice |
| Reporting and exports | Medium | Low | Reads many tables | Good, if you can read a replica |
| Notifications (email, SMS) | Low | Low | Fire and forget | Good warm-up |
| Authentication | High | High | Everything depends on it | Late, or behind an adapter |
| Order checkout | High | High | Payments, stock, tax | After the team has practice |
| A new feature nobody has yet | High | Low | None | Build it new; the cheapest strangling |
seam hunting, in order of cheapness
1 the edge URL prefixes and hostnames (facade can route today)
2 the message edge queues and topics (consumer can move)
3 the code edge interfaces inside the monolith (branch by abstraction)
4 the data edge table owned by one module (view, CDC, tracer write)
5 the UI edge page fragments (UI composition)Real scenarios: a retailer moves /search first because it is read-only and has its own index; a bank moves statements (read) before payments (write); a SaaS moves the public API (a thin layer) before the admin UI.
Fix: write the slice down as a one-page contract: URLs, methods, request and response samples taken from real traffic, tables touched, jobs and events produced, owner, and the exit criterion. See Context Maps & Integration Patterns for where the lines belong.
Routing rules: path, header, tenant, percentage Must-know
In plain words: The facade has a small rule list. The first rule that matches decides which side answers.
Common misunderstanding: "Percentage rollout means each request has a 5% chance of hitting the new system." Per request random choice makes one user bounce between two systems with different data and different bugs. The bucket must come from a stable key such as the user id.
Definition: Path-based routing matches a prefix. Header-based routing matches a request header (an opt-in for staff). Tenant routing matches a tenant id. A percentage rollout maps a sticky key to 0..99 with a hash and compares it with the threshold. Raising the threshold from 5 to 10 only adds users.
1 user u-17 hash(u-17) mod 100 = 63 percent=5 63 >= 5 -> legacy
2 operator raises percent 5 -> 70
3 user u-17 hash(u-17) mod 100 = 63 percent=70 63 < 70 -> new (from now on)
4 operator sets the kill switch
5 user u-17 kill -> legacy| Product | How you express a percentage | Sticky? |
|---|---|---|
| NGINX | split_clients "${remote_addr}AAA" $variant { 5% new; * legacy; } | By the key you hash (client address here), stable while the key is |
| Envoy | runtime_fraction on a route match, or weighted clusters | Per request unless you hash a header |
| Istio | VirtualService route[].weight | Per request; use consistent hash on the DestinationRule for stickiness |
| AWS ALB | Weighted target groups in a forward action | Optional target group stickiness |
| Laravel Pennant | Lottery::odds(5, 100) inside a feature, stored per scope | Yes: the result is stored for the scope |
| This chapter's Go facade | Bucket(StickyKey(r)) < rule.Percent | Yes: FNV-1a of the user id |
Fix: keep rules in one reviewed place, log the decision reason (header, tenant, percent, kill-switch) on every request, and put the user's id or a stable cookie in the sticky key rather than the IP address.
Shadow traffic, dark launch and response diffing Must-know
In plain words: Send a copy of real requests to the new system, throw its answer away after comparing it with the old system's answer. Users never see the new system's output.
Common misunderstanding: "Shadow traffic is free testing." The shadow copy runs real code: it can send emails, charge cards, write rows and double the load. Shadow only safe (read) requests, or give the new system a no-side-effects mode and mark the copy with a header.
Definition: Shadow traffic (also called mirroring, a dark launch or a dark read) duplicates production requests to the new system. Response diffing compares status and body after removing noise. NGINX's ngx_http_mirror_module (since 1.13.4) creates background mirror subrequests and its documentation states that "Responses to mirror subrequests are ignored". Envoy has request_mirror_policies on routes and virtual hosts; Istio has mirror and mirrorPercentage.
1 client -> facade GET /orders/42
2 facade -> legacy forward, stream the answer to the client (primary)
3 facade -> client 200, 118 bytes
4 facade -> new GET /orders/42 X-Shadow: 1 (after the client has its answer)
5 new -> facade 200, 118 bytes
6 facade -> diff status equal, JSON equal after ignoring "updated_at" -> match++| Noise source | Example | Handling |
|---|---|---|
| Timestamps and ids | updated_at, request_id | Ignore list per slice |
| Ordering | Unordered arrays | Sort before comparing, or compare as sets |
| Floating point | 10.0 vs 10.00 | Normalise numbers, compare money as integers |
| Non-determinism | Random recommendations | Measure noise with a legacy-vs-legacy diff first |
| Time-dependent data | "5 minutes ago" | Freeze the clock in the shadow path |
| Side effects | Email, payment, webhooks | Shadow only GET, or X-Shadow makes the new side a dry run |
Diffy's README states the premise: "if two implementations of a service return “similar” responses for a sufficiently large and diverse set of requests, the newer implementation can be treated as regression-free", and it measures noise by comparing two instances of the known-good code with each other. GitHub's Scientist library applies the same idea inside one process: run the control (old) and the candidate (new) code, return the control's result, record any difference.
Fix: facade.Diff removes ignored keys at every depth, compares JSON structurally and names the first differing path; the Laravel terminate() hook does the same after the response has been sent.
Canary, progressive delivery and feature flags Must-know
In plain words: Move real users in small steps, look at the numbers after each step, and only go on when they are good.
Common misunderstanding: "A feature flag is the same as a deployment." A deployment puts code on servers; a flag decides who runs it. The two must be separable, otherwise rolling back means redeploying.
Definition: A canary release sends a small share of traffic to the new version and compares it against the baseline. Progressive delivery automates the ramp (1%, 5%, 25%, 50%, 100%) with analysis between steps; Argo Rollouts describes itself as adding "canary, canary analysis, experimentation, and progressive delivery features to Kubernetes". A feature flag is a runtime switch; Laravel Pennant resolves flags per scope (a user, a team) and can use Lottery::odds for a percentage.
| Stage | Share | Audience | Soak | Go on if |
|---|---|---|---|---|
| 0 | 0%, shadow only | Nobody | 3 to 7 days | Diff rate below target |
| 1 | Header opt-in | Staff and testers | 1 day | No blocking bugs |
| 2 | 1% | Random users, sticky | 1 day | Errors and p99 within the SLO |
| 3 | 5% | Random, sticky | 1 to 3 days | Business KPI (conversion, orders per minute) flat |
| 4 | 25% | Random | 2 days | Same, plus database load fine |
| 5 | 50% | Random | 3 days | Same |
| 6 | 100% | Everybody | 1 to 4 weeks | Soak ends, legacy kept warm |
| Flag system | Where flags live | Notes |
|---|---|---|
| Laravel Pennant | Array or database driver, per scope | Feature::for($user)->active(NewOrders::class) |
| LaunchDarkly, Unleash, Flagsmith | Hosted or self-hosted service | Rules and targeting UI, audit log |
| Environment variable | Process start | Needs a restart: not a kill switch |
| Config table or cache key | Your database or Redis | Fast to read, easy to build, you own the audit trail |
Fix: set the stage thresholds before starting. The rollout decision diagram below shows the loop: raise, soak, measure, hold or go on, kill on a severe breach.
Parallel run and reconciliation Important
In plain words: Run old and new on the same inputs for a while, and make a machine check that their outputs agree.
Common misunderstanding: "Shadow traffic and parallel run are the same." Shadow compares responses to reads. Parallel run (Newman's pattern) executes both implementations for real work, including writes into separate stores, and reconciles the results afterwards, so it is the tool for money, stock and tax.
Definition: In a parallel run both systems process the same business events; one is authoritative, the other's results are stored and compared by a reconciliation job. Reconciliation is an automated comparison of two datasets by count, checksum and row diff.
1 17:00:00 facade order 9001 -> legacy (authoritative), copy -> new (dry run)
2 17:00:01 legacy writes legacy.orders(9001, total 120.00)
3 17:00:01 new writes new.orders(9001, total 120.00)
4 18:00:00 reconcile hour 17: 4,812 legacy rows, 4,812 new rows, checksum equal
5 18:00:03 reconcile hour 17: diff 0 -> green
6 next day reconcile order 9317: legacy 99.00, new 98.99 -> ticket: rounding rule| Check | Query shape | Catches |
|---|---|---|
| Count per bucket | count(*) GROUP BY day on both | Lost writes |
| Checksum per bucket | md5(string_agg(...ORDER BY id)) | Any value drift, cheaply |
| Missing rows | Left anti-join | Lost second write, backfill gap |
| Different rows | IS DISTINCT FROM on a tuple | Rounding, mapping bugs |
| Lag | Compare max(updated_at) | CDC or queue delay |
-- Drill into one bucket: values that differ between legacy and new.
SELECT l.id, l.total_cents AS legacy, n.total_cents AS new
FROM legacy_orders l JOIN new_orders n USING (id)
WHERE (l.status, l.total_cents) IS DISTINCT FROM (n.status, n.total_cents)
AND l.updated_at < now() - interval '5 minutes' -- ignore rows still in flight
ORDER BY l.id LIMIT 100;Full queries: reconcile.sql. Go and Laravel versions: the Go demo prints a match counter; the Laravel strangler:reconcile command exits non-zero above --max-diff.
Dual write and why it hurts Must-know
In plain words: Dual write means the application saves the same fact to two databases, one after the other. They can disagree whenever the process dies in between.
Common misunderstanding: "Wrap both writes in a transaction." Two databases do not share a transaction unless you run two-phase commit, which most stacks do not have and which ties the new system to the old one's availability.
Definition: Dual write is an application-level write to two stores without atomic commit across them. Failure modes: second write fails, second write succeeds and the first is rolled back, writes arrive in a different order on each side (last-writer-wins differs), a retry duplicates.
1 T1 app BEGIN legacy; UPDATE orders SET status='paid' WHERE id=7; COMMIT
2 T1 app UPDATE new.orders SET status='paid' WHERE id=7 -> timeout (committed? unknown)
3 T2 app retry the request: legacy UPDATE is idempotent, new UPDATE applies
4 T3 other second request sets status='shipped' on legacy, then new
5 T3 delay the retry from step 3 lands on new AFTER step 4 -> new says 'paid', legacy says 'shipped'| Danger | Why it happens | Mitigation |
|---|---|---|
| Partial failure | No shared transaction | Source of truth first; repair queue; reconcile |
| Ordering | Two writers, no common clock | Version column, WHERE updated_at <= new.updated_at guard |
| Duplicates | Retries | Idempotent upsert by key |
| Latency | Two round trips in the request path | Async second write via outbox |
| Hidden coupling | Request fails if the new side is down | Never fail the user because of the new side |
| Permanent | Dual write "just for now" | Exit criterion and date |
Fix: keep legacy as the source of truth, make the second write an idempotent upsert, record failures in a repair table (migration_write_failures), and prefer Transactional Outbox or CDC when you can: they turn "two writes" into "one write plus a log". Code: DualWriteOrderRepository.
Moving the data: CDC, event interception, views, synonyms Important
In plain words: There are several ways to make the new system see the old data, from "just read the old tables" to "stream every change".
Common misunderstanding: "Pick one pattern and use it for everything." Newman's chapter on decomposing the database lists many; slices differ in whether they are read-heavy, write-heavy, or consistency-critical.
| Pattern | How it works | Direction | Consistency | Best for |
|---|---|---|---|---|
| Shared database | New service queries legacy tables | Read and write | Immediate | First days only: it is a coupling, not a migration |
| Database view | CREATE VIEW orders_read AS SELECT ... | Read | Immediate | Hide the table behind a seam; swap the view at cutover |
| Synonym (SQL Server, Oracle) | Alias to a table or view in another schema or database | Read | Immediate | Same idea where the engine has synonyms; PostgreSQL uses views or foreign tables |
| Database wrapping service | A small service owns the table, others call it | Read and write | Immediate | Legacy schema you cannot move yet |
| Change data capture | Debezium reads the PostgreSQL WAL or MySQL binlog and publishes row changes | Legacy to new | Eventual (lag) | Keeping a copy current without touching legacy code |
| Event interception | Facade publishes an event per call it routes | Either | Eventual | When the legacy log is not accessible |
| Synchronize data in application | Application writes both | Either | Depends | Short transitions only |
| Tracer write | Pick one entity, make the new store authoritative for it, sync back | Both | Per entity | Proving the path before the big move |
| Repository per bounded context | Each context hides its store behind a repository interface | In code | n/a | Lets the store change without callers changing |
| Product | Seam tool | Note |
|---|---|---|
| PostgreSQL | Views, postgres_fdw, logical decoding, publications | No synonyms |
| MySQL | Views, binlog (row format) | Cross-database views work inside one server |
| SQL Server | Synonyms, views, CDC, Change Tracking | Synonym can point across databases |
| Oracle | Synonyms, database links, GoldenGate | Public synonyms are global |
| MongoDB | Change streams | Needs a replica set |
| Kafka | Debezium via Kafka Connect | Ordered per key |
-- Database view as the seam: new code reads orders_read and never learns the table name.
CREATE VIEW orders_read AS
SELECT id, customer_id, status, total_cents, currency FROM legacy_orders;
-- At cutover, one statement swaps the source with no new deploy:
CREATE OR REPLACE VIEW orders_read AS
SELECT id, customer_id, status, total_cents, currency FROM new_orders;Fix: pick per slice and write it down. For schema evolution on one database use expand/contract; for two databases, combine backfill, CDC or dual write, and reconciliation.
Reads and writes during the migration Must-know
In plain words: Decide, per slice, which side is the source of truth, move reads first, move writes last.
Common misunderstanding: "Switch reads and writes together." Reads are safe to move and easy to move back; writes change history. Keep them apart.
Definition: The safest order for one entity: backfill history, keep new in sync (CDC or dual write), reconcile to zero, read from new write to both, then write to new only and retire the legacy write path.
| Phase | Reads from | Writes to | Truth | Rollback |
|---|---|---|---|---|
| 0 Facade only | Legacy | Legacy | Legacy | n/a |
| 1 Backfill | Legacy | Legacy | Legacy | Delete new copy |
| 2 Catch-up (CDC or dual write) | Legacy | Legacy and new | Legacy | Stop the sync |
| 3 Reconcile to zero | Legacy | Legacy and new | Legacy | Stop the sync |
| 4 Read from new write to both | New | Legacy and new | Legacy (still) | Flip reads back |
| 5 Write to new, sync back | New | New, legacy via sync | New | Flip writes back (needs sync) |
| 6 Retire legacy write | New | New | New | Restore from archive |
1 Phase 4 GET /orders/7 facade -> new (read from new)
2 Phase 4 POST /orders app -> legacy INSERT ... (truth)
3 Phase 4 POST /orders app -> new upsert by id (idempotent, may fail)
4 Phase 4 failure record migration_write_failures(order, 7, new)
5 repair worker replays row 7 to new, marks repaired_at
6 gate reconcile diff = 0 for 7 days -> allowed to enter phase 5Fix: backfill in keyset batches with an idempotent upsert that never overwrites a newer row (backfill.sql); use API idempotency keys so a retried request cannot write twice; time-box each phase.
Branch by abstraction Important
In plain words: When the thing you replace is inside the program (a library, an ORM, a payment module) there is no network seam. Create an interface first, then swap the implementation behind it.
Common misunderstanding: "Use a long-lived source control branch for the rewrite." The point of the technique is to avoid it: the system builds and runs correctly at all times, and you keep shipping.
Definition: Fowler's page describes steps: create an abstraction layer for the interaction between the client code and the current supplier, move clients onto it, build the new supplier behind the same abstraction, switch clients over, delete the old supplier (and perhaps the abstraction). His summary of the theme: "Use an abstraction layer to allow multiple implementations to co-exist in the software system." Feature flags select the implementation, and Steve Smith's variation (linked from that page) verifies that both implementations return the same results.
1 extract interface OrderStore { Find(id) ; Save(order) }
2 adapt LegacyOrderStore implements OrderStore (wraps old code)
3 migrate callers use OrderStore only (behind tests)
4 build NewOrderStore implements OrderStore
5 verify VerifyingStore calls both, returns legacy result, logs differences
6 switch flag picks NewOrderStore per tenant
7 delete LegacyOrderStore, then the interface if nobody needs itThe Laravel OrderRepository interface with DualWriteOrderRepository is branch by abstraction at the repository level; in Go the same shape is a small interface with two implementations.
UI composition and micro-frontends Important
In plain words: The screens migrate too. One page can be assembled from pieces, some old and some new.
Common misunderstanding: "Migrate the backend first and the UI later in one go." A UI that is rebuilt last holds the whole migration hostage; compose it from fragments instead.
Definition: UI composition combines fragments from several services into one page, by page (route-level), by fragment (server-side include, edge-side include), or by component (micro-frontend loaded in the browser). Newman lists UI Composition as a pattern next to the Strangler Fig. Zalando's engineering blog describes its Mosaic project (micro-services for the frontend, introduced in 2015) and, years later, the Interface Framework to which it moved, noting that "we serve around 90% of traffic via Interface Framework" while teams migrate page by page.
| Approach | Where composed | Example | Cost |
|---|---|---|---|
| Page level | Facade routes by URL | /checkout/* to new app | Visible seams between pages |
| Fragment, server side | Gateway or SSR assembles pieces | Edge-side includes, Mosaic fragments | Latency of slowest fragment |
| Component, client side | Browser loads remote modules | Module federation, web components | Bundle size, shared state |
| Reverse proxy per route | NGINX location blocks | /new/ prefix first | Duplicate navigation |
The anti-corruption layer Important
In plain words: A translator between old and new, so the new code never has to speak the old model.
Common misunderstanding: "Reuse the legacy data model in the new code to save time." The legacy names, nullable columns and magic status codes then become the new system's vocabulary, and the old system cannot ever be removed.
Definition: An anti-corruption layer maps legacy concepts to the new domain model at the boundary, and nowhere else. Where the legacy side is a database, the layer is an adapter or the database view; where it is a service, a translating client. See Context Maps & Integration Patterns.
| Legacy | New | Translation rule |
|---|---|---|
ord_st = 3 | Order.status = PAID | Lookup table, unknown code fails loudly |
cust_nm (single string) | FirstName, LastName | Split rule documented, tested with real samples |
Money as DECIMAL(10,2) | Integer minor units plus currency | Round once, at the boundary |
| Dates without zone | UTC instants | Zone stated per source system |
| Soft-deleted rows | Absent from the new model | Filter in the adapter |
Testing: contract tests and traffic replay Important
In plain words: Prove the new system behaves like the old one using the old system's real behaviour, not a spec nobody trusts.
Common misunderstanding: "Unit tests of the new code are enough." They test what you thought of. The old system's quirks are what you did not.
| Technique | What it checks | Tooling examples |
|---|---|---|
| Contract tests | Request and response shapes of the slice | OpenAPI schema validation, Pact |
| Consumer-driven contracts | Each consumer states what it uses; the provider must satisfy all | Pact broker |
| Characterization tests | Record the legacy's output for inputs, assert the new one matches | Golden files |
| Traffic replay | Re-send recorded production requests to new (offline) | GoReplay, k6 from HAR logs, mirrored logs |
| Shadow traffic | Same requests, live, to new | NGINX mirror, Envoy, Istio mirror, this chapter's facade |
| Parallel run | Both run real work, results reconciled | Scientist, batch jobs |
| Load test | New system at 2x the slice's peak | k6, Gatling, wrk |
1 record facade logs 1M GET requests for /orders/* (path, query, selected headers)
2 scrub remove tokens, personal data, replace ids with synthetic ones
3 replay replay at 2x speed against new in a test environment
4 compare diff the answers with the recorded legacy answers
5 triage bucket diffs: noise, bug in new, bug in legacy (yes, this happens)Kill switch and rollback plan Must-know
In plain words: A button that sends everyone back to the old system in seconds, which you have pressed in a rehearsal.
Common misunderstanding: "Rollback means redeploying the previous version." A deploy takes minutes and can fail. A kill switch is a runtime value that every facade instance reads.
Definition: A kill switch is a flag the facade checks on every request that forces legacy and disables shadowing. A rollback plan lists, per stage, the trigger, the action, who may act and what happens to data written meanwhile.
| Stage | Trigger examples | Action | Data consequence |
|---|---|---|---|
| Shadow | Shadow load hurts the new system | Turn mirroring off | None |
| Canary | Error rate above SLO for 5 minutes | Percent to 0 or kill switch | Rows written to new need reconcile |
| Cutover | Business KPI drops | Kill switch | Writes to new must sync back to legacy |
| Soak | Wrong totals found | Kill switch plus freeze | Repair job from the diff |
| After decommission | n/a | Restore from archive | Hours to days |
Fix: put the kill switch in a store every instance reads in under a second (a cache key, a feature flag service), test it in every environment, and write the runbook with the exact command.
Cutover and decommission Must-know
In plain words: Cutover is the day legacy stops answering. Decommission is the day it stops existing.
Common misunderstanding: "Cutover is the last step." Between them lies a soak period during which legacy is warm, and after it, the real work: delete code, routes, tables, jobs, secrets, dashboards, licences and servers.
1 T-14d shadow diff below 0.1% for 7 days; reconcile diff = 0
2 T-7d canary at 50%, SLOs held
3 T-0 percent -> 100, legacy kept warm, kill switch armed, on-call briefed
4 T+7d no kill switch use, no legacy traffic except health checks
5 T+30d write path retired: legacy becomes read-only
6 T+45d final export to archive storage, legacy hostnames return 410
7 T+60d delete code, tables, queues, credentials; update the diagrams| Decommission item | Check |
|---|---|
| Routes and hostnames | Facade rule removed; 410 Gone or redirect for a period |
| Scheduled jobs and queues | Nothing consumes or produces |
| Database | Final dump archived, retention rules met, then dropped |
| Credentials and network paths | Revoked, firewall rules closed |
| Monitoring and alerts | Dashboards and alerts for legacy deleted |
| Documentation | Diagrams and runbooks updated |
| Contracts and licences | Cancelled |
Organisation and migration metrics Important
In plain words: A migration that nobody measures turns into a permanent state.
Common misunderstanding: "% of traffic on the new system is the progress number." A system can serve 100% of traffic and still depend on legacy tables, jobs and people.
| Metric | Measures | Source | Trap |
|---|---|---|---|
| % of traffic | Requests answered by new | Facade counters | Cheap to move, hides data |
| % of endpoints | Slices fully on new | Rule table | Endpoints differ in size |
| % of data | Tables or rows owned by new | Row counts, ownership list | Dual-owned data counts as half |
| Shadow diff rate | Mismatches over compared requests | Facade counters | Noise must be subtracted |
| Reconcile diff | Rows differing | Reconcile job | Must be zero before cutover |
| Legacy code deleted | Lines, files, jobs removed | Repository | The only real progress |
| Cost of two systems | Servers, licences, people | Finance | The reason to finish |
| Lead time per slice | Seam to decommission | Tracker | Should fall with practice |
Shopify's engineering post shows a concrete metric tool: its in-house Wedge "tracks the progress of each component towards its goal of isolation" and lists boundary violations. Team ownership matters as much: Fowler points to Conway's Law and to reorganising the development organisation. Name one owner per slice, who owns both the new service and the legacy code being deleted.
Anti-patterns Important
| Anti-pattern | How it shows | Remedy |
|---|---|---|
| Big-bang rewrite | Parallel project, no releases, a switch weekend | Slice and ship per seam |
| Strangler that never finishes | 80% done for three years | A decommission date per slice, executive-visible deletion metric |
| Legacy becomes a dependency of the new system | New service reads legacy tables for core data, calls legacy APIs | Anti-corruption layer, data ownership transfer, a dependency budget |
| Facade grows business logic | Rules about discounts live in the proxy | The facade routes only; logic belongs in a service |
| Facade is a single point of failure | One instance, no health checks | At least two instances, health checks, fail-open to legacy |
| Dual write without reconciliation | Drift found by customers | Reconcile job as a gate |
| Shadowing writes | Duplicate emails or charges | Safe methods only or dry-run mode |
| No sticky routing | One user sees two behaviours | Hash a stable user key |
| Migrating the worst slice first | Months without a win | Start with a low-risk, valuable slice |
| Kill switch never exercised | Switch fails when needed | Rehearse on a schedule |
| Copying every legacy bug | New system as bad as old | Characterise first; decide per bug |
Case examples Good to know
| Company | What the source says | Lesson | Source |
|---|---|---|---|
| Shopify | One of the largest Rails codebases, worked on by over a thousand developers over a decade; it chose to "evolve Shopify into a modular monolith" with enforced boundaries, tracked by the Wedge tool | A strangler can end in a modular monolith, not only in microservices | Shopify Engineering, 21 Feb 2019 |
| Zalando | Wanted to "move away from a monolithic shop system" in 2015; Project Mosaic let many teams work on the website independently; later the Interface Framework serves around 90% of traffic while teams migrate pages | Percent of traffic is a valid progress metric when stated with its scope | Zalando Engineering, 11 Mar 2021 |
| Monzo | Built the backend "as a collection of distributed microservices" from the start, rather than migrating a monolith | A counter-example: no migration needed because the system was born distributed; the trade-off is the platform work described in the post | Monzo blog, 19 Sep 2016 |
| Uber | Introduced Domain-Oriented Microservice Architecture (DOMA): domains, layers, gateways and extension points to reduce the complexity of a large microservice estate | Strangling may continue after microservices: regrouping services into domains | Uber Engineering, 23 Jul 2020 |
Everything in this table is what the cited page says; the lessons in the third column are this chapter's inference, not claims by the companies.
Mechanics
Facade knobs, in one place
| Product | Setting | What it does |
|---|---|---|
| NGINX | mirror /mirror; and mirror_request_body on; (default on) | Creates a background subrequest per request; responses to mirror subrequests are ignored |
| NGINX | split_clients "${remote_addr}AAA" $variant { 5% new; * legacy; } | Hashes the string to pick a variant by percentage |
| NGINX | proxy_next_upstream error timeout http_502 http_503; | Retry the other upstream on failure (only idempotent requests) |
| Envoy | request_mirror_policies on a route or virtual host | Mirrors to a cluster, with an optional runtime_fraction |
| Envoy | runtime_fraction in a route match | Matches only the given percentage |
| Istio | VirtualService http.route[].weight | Splits traffic between destinations |
| Istio | mirror and mirrorPercentage | Mirrors a percentage; absent means 100% |
| Argo Rollouts | strategy.canary.steps with setWeight and pause | Progressive canary with analysis |
| Laravel Pennant | Feature::define, Lottery::odds, Feature::for($scope) | Per-scope flags with percentage |
| Laravel HTTP client | Http::timeout(2), Http::pool(...) | Bounded shadow calls, concurrent calls |
| This chapter's facade | Percent, Shadow, FallbackToLegacy, IgnoreFields, SetKillSwitch | The same ideas in 200 lines of Go |
Status codes and errors you will see
| Where | Code or message | Meaning | Action |
|---|---|---|---|
| Facade to legacy | 502 Bad Gateway | Upstream closed the connection or sent garbage | Circuit breaker, alert |
| Facade to new | 503 Service Unavailable | New side is down or overloaded | Fallback to legacy for safe methods |
| Facade to either | 504 Gateway Timeout | Upstream too slow | Tune the proxy timeout under the client's |
| Decommissioned route | 410 Gone | Resource intentionally removed | Update clients |
| Shadow request | X-Shadow: 1 (convention, not a standard) | New side must not cause side effects | Check it on every write path |
| PostgreSQL | SQLSTATE 23505 unique_violation | Second write inserted a key that exists | Use ON CONFLICT DO UPDATE |
| PostgreSQL | SQLSTATE 40001 serialization_failure | Concurrent transaction conflict | Retry the whole transaction |
| PostgreSQL | SQLSTATE 40P01 deadlock_detected | Backfill and live writes locked each other | Smaller batches, consistent order |
| Laravel HTTP client | ConnectionException | Timeout or DNS failure on a shadow call | Count as shadow error, never fail the user |
| Laravel HTTP client | RequestException (after ->throw()) | 4xx or 5xx response | Compare status in the diff |
Time budget of a shadowed request
| Segment | Typical value | Note |
|---|---|---|
| Facade hop | 0.3 to 2 ms | One extra proxy on the same network (estimate, measure yours) |
| Legacy handling | Whatever it was | Unchanged by design |
| Shadow call | In parallel or after the response | Never on the user's critical path |
| Diff | Microseconds to a millisecond | JSON compare of a small body |
| Shadow load on new | Equal to the mirrored share | 100% mirror doubles the new side's read load |
Arithmetic for the first ramp: with 2,000 requests per second on /orders and 5% canary, the new service takes 100 requests per second; at 100% mirroring with 0% live it takes 2,000 requests per second of read load and no user risk, so size it for that before turning mirroring on.
Go
Before
One constant flips all traffic. No shadow, no per-slice rule, no way back without a deploy.
// Before: a hard-coded cutover switch. One boolean flips 100% of traffic,
// there is no shadow comparison, no per-slice routing and no way back that
// does not need a deploy.
package main
import (
"log"
"net/http"
"net/http/httputil"
"net/url"
)
const useNewSystem = true // changing this means rebuilding and redeploying
func main() {
legacy, _ := url.Parse("http://legacy.internal.example:8080")
modern, _ := url.Parse("http://orders.internal.example:8080")
target := legacy
if useNewSystem {
target = modern
}
log.Fatal(http.ListenAndServe(":8080", httputil.NewSingleHostReverseProxy(target)))
}After
A facade with ordered rules (path prefix, header, tenant, sticky percentage), shadow comparison, fallback and a runtime kill switch.
// Package facade is the strangler facade: a reverse proxy that decides, per
// request, whether the legacy system or the new system answers, and that can
// mirror ("shadow") a request to the other side and compare the answers.
package facade
import (
"hash/fnv"
"net/http"
"strings"
)
// Backend names a side of the migration.
type Backend string
const (
Legacy Backend = "legacy"
Modern Backend = "new"
)
// Rule describes one migrated slice of functionality.
// Rules are evaluated in order; the first PathPrefix match wins.
type Rule struct {
Name string
PathPrefix string
// ForceHeader/ForceValue: requests carrying this header value always
// go to the new system (staff, synthetic checks, canary testers).
ForceHeader string
ForceValue string
// Tenants (value of the X-Tenant header) that are fully migrated.
Tenants map[string]bool
// Percent of the remaining traffic sent to the new system, 0..100.
// The bucket is derived from a stable key, so a user never flaps.
Percent int
// Shadow mirrors safe requests (GET/HEAD) to the new system while the
// legacy answer is returned, then diffs the two answers.
Shadow bool
// FallbackToLegacy retries a safe request on legacy when the new
// system returns 5xx or cannot be reached.
FallbackToLegacy bool
// IgnoreFields are JSON object keys excluded from the diff
// (timestamps, request ids, anything legitimately different).
IgnoreFields []string
}
// Decision is the outcome of routing one request.
type Decision struct {
Backend Backend
Rule *Rule
Reason string
}
// Bucket maps a key to 0..99 with FNV-1a. The same key always lands in the
// same bucket, so raising Percent from 5 to 10 only adds users.
func Bucket(key string) int {
h := fnv.New32a()
_, _ = h.Write([]byte(key))
return int(h.Sum32() % 100)
}
// StickyKey picks the identity used for percentage routing.
func StickyKey(r *http.Request) string {
if v := r.Header.Get("X-User-Id"); v != "" {
return v
}
if v := r.Header.Get("X-Tenant"); v != "" {
return v
}
return r.RemoteAddr
}
func match(rules []Rule, path string) *Rule {
for i := range rules {
if strings.HasPrefix(path, rules[i].PathPrefix) {
return &rules[i]
}
}
return nil
}
func decide(rules []Rule, r *http.Request) Decision {
rule := match(rules, r.URL.Path)
if rule == nil {
return Decision{Backend: Legacy, Reason: "no-rule"}
}
if rule.ForceHeader != "" && r.Header.Get(rule.ForceHeader) == rule.ForceValue {
return Decision{Backend: Modern, Rule: rule, Reason: "header"}
}
if rule.Tenants[r.Header.Get("X-Tenant")] {
return Decision{Backend: Modern, Rule: rule, Reason: "tenant"}
}
if Bucket(StickyKey(r)) < rule.Percent {
return Decision{Backend: Modern, Rule: rule, Reason: "percent"}
}
return Decision{Backend: Legacy, Rule: rule, Reason: "percent"}
}
func isSafe(method string) bool {
return method == http.MethodGet || method == http.MethodHead
}package facade
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"sync"
"sync/atomic"
"time"
)
const maxCapture = 1 << 20 // 1 MiB: larger bodies are never shadow-compared
// Facade is an http.Handler placed in front of the legacy system.
type Facade struct {
rules []Rule
legacy *httputil.ReverseProxy
modern *httputil.ReverseProxy
legacyU *url.URL
modernU *url.URL
kill atomic.Bool
client *http.Client
shadowWG sync.WaitGroup
Metrics *Metrics
}
// New builds a facade. Both URLs are the roots of the two systems.
func New(legacyURL, newURL *url.URL, rules []Rule) *Facade {
return &Facade{
rules: rules,
legacy: httputil.NewSingleHostReverseProxy(legacyURL),
modern: httputil.NewSingleHostReverseProxy(newURL),
legacyU: legacyURL,
modernU: newURL,
client: &http.Client{Timeout: 2 * time.Second},
Metrics: NewMetrics(),
}
}
// SetKillSwitch forces every request to legacy and disables shadowing.
// It is a runtime switch: no deploy, no restart.
func (f *Facade) SetKillSwitch(on bool) { f.kill.Store(on) }
// Wait blocks until all in-flight shadow comparisons finish (tests, shutdown).
func (f *Facade) Wait() { f.shadowWG.Wait() }
func (f *Facade) ServeHTTP(w http.ResponseWriter, r *http.Request) {
d := decide(f.rules, r)
if f.kill.Load() {
d = Decision{Backend: Legacy, Rule: d.Rule, Reason: "kill-switch"}
}
name := "none"
if d.Rule != nil {
name = d.Rule.Name
}
f.Metrics.Inc("requests", name, string(d.Backend), d.Reason)
wantShadow := d.Rule != nil && d.Rule.Shadow && d.Backend == Legacy &&
!f.kill.Load() && isSafe(r.Method)
wantFallback := d.Rule != nil && d.Rule.FallbackToLegacy && d.Backend == Modern && isSafe(r.Method)
switch {
case wantFallback:
rec := httptest.NewRecorder()
f.modern.ServeHTTP(rec, r)
if rec.Code >= 500 {
f.Metrics.Inc("fallback", name, "new->legacy", "")
f.legacy.ServeHTTP(w, r)
return
}
copyRecorded(w, rec)
case wantShadow:
cw := newCapture(w)
f.legacy.ServeHTTP(cw, r)
primary := Captured{Status: cw.status(), Body: cw.body.Bytes()}
if cw.truncated {
f.Metrics.Inc("shadow", name, "skipped-large", "")
return
}
f.shadow(r, *d.Rule, primary)
case d.Backend == Modern:
f.modern.ServeHTTP(w, r)
default:
f.legacy.ServeHTTP(w, r)
}
}
// shadow replays the request against the new system after the client has its
// answer, so a slow or broken new system cannot hurt the user.
func (f *Facade) shadow(r *http.Request, rule Rule, primary Captured) {
ctx := context.WithoutCancel(r.Context())
req := r.Clone(ctx)
f.shadowWG.Add(1)
go func() {
defer f.shadowWG.Done()
u := *f.modernU
u.Path, u.RawQuery = r.URL.Path, r.URL.RawQuery
out, err := http.NewRequestWithContext(ctx, req.Method, u.String(), nil)
if err != nil {
f.Metrics.Inc("shadow", rule.Name, "error", "")
return
}
out.Header = req.Header.Clone()
out.Header.Set("X-Shadow", "1") // the new system must not send emails or charge cards
resp, err := f.client.Do(out)
if err != nil {
f.Metrics.Inc("shadow", rule.Name, "error", "")
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxCapture))
if d := Diff(primary, Captured{Status: resp.StatusCode, Body: body}, rule.IgnoreFields); d != "" {
f.Metrics.Inc("shadow", rule.Name, "mismatch", "")
f.Metrics.Record(rule.Name + " " + r.URL.Path + ": " + d)
return
}
f.Metrics.Inc("shadow", rule.Name, "match", "")
}()
}
func copyRecorded(w http.ResponseWriter, rec *httptest.ResponseRecorder) {
for k, v := range rec.Header() {
w.Header()[k] = v
}
w.WriteHeader(rec.Code)
_, _ = w.Write(rec.Body.Bytes())
}The diff ignores noisy fields at every depth and names the first differing path:
package facade
import (
"bytes"
"encoding/json"
"fmt"
"sort"
)
// Captured is one recorded response.
type Captured struct {
Status int
Body []byte
}
// Diff returns an empty string when the two responses are equivalent and a
// short human-readable reason when they are not. JSON bodies are compared
// structurally with ignored keys removed at every depth; other bodies are
// compared byte for byte.
func Diff(a, b Captured, ignore []string) string {
if a.Status != b.Status {
return fmt.Sprintf("status legacy=%d new=%d", a.Status, b.Status)
}
var va, vb any
errA := json.Unmarshal(a.Body, &va)
errB := json.Unmarshal(b.Body, &vb)
if errA != nil || errB != nil {
if bytes.Equal(a.Body, b.Body) {
return ""
}
return "body bytes differ"
}
skip := make(map[string]bool, len(ignore))
for _, k := range ignore {
skip[k] = true
}
ja, _ := json.Marshal(strip(va, skip)) // map keys are marshalled sorted
jb, _ := json.Marshal(strip(vb, skip))
if bytes.Equal(ja, jb) {
return ""
}
return "json differs: " + firstDifference(strip(va, skip), strip(vb, skip), "$")
}
func strip(v any, skip map[string]bool) any {
switch t := v.(type) {
case map[string]any:
out := make(map[string]any, len(t))
for k, x := range t {
if !skip[k] {
out[k] = strip(x, skip)
}
}
return out
case []any:
out := make([]any, len(t))
for i, x := range t {
out[i] = strip(x, skip)
}
return out
default:
return v
}
}
func firstDifference(a, b any, path string) string {
ma, okA := a.(map[string]any)
mb, okB := b.(map[string]any)
if okA && okB {
keys := make([]string, 0, len(ma)+len(mb))
seen := map[string]bool{}
for k := range ma {
keys, seen[k] = append(keys, k), true
}
for k := range mb {
if !seen[k] {
keys = append(keys, k)
}
}
sort.Strings(keys)
for _, k := range keys {
if d := firstDifference(ma[k], mb[k], path+"."+k); d != "" {
return d
}
}
return ""
}
ja, _ := json.Marshal(a)
jb, _ := json.Marshal(b)
if bytes.Equal(ja, jb) {
return ""
}
return fmt.Sprintf("%s legacy=%s new=%s", path, ja, jb)
}Tests for path routing, header and tenant rules, sticky percentage, the kill switch, shadow match and mismatch, unsafe methods and fallback:
package facade
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func backend(t *testing.T, name string, status int, body string) *httptest.Server {
t.Helper()
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Served-By", name)
w.WriteHeader(status)
_, _ = io.WriteString(w, body)
}))
t.Cleanup(s.Close)
return s
}
func build(t *testing.T, l, n *httptest.Server, rules []Rule) (*Facade, *httptest.Server) {
t.Helper()
lu, _ := url.Parse(l.URL)
nu, _ := url.Parse(n.URL)
f := New(lu, nu, rules)
srv := httptest.NewServer(f)
t.Cleanup(srv.Close)
return f, srv
}
func get(t *testing.T, base, path string, hdr map[string]string) (string, int, string) {
t.Helper()
req, _ := http.NewRequest(http.MethodGet, base+path, nil)
for k, v := range hdr {
req.Header.Set(k, v)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.Header.Get("X-Served-By"), resp.StatusCode, string(b)
}
func TestPathRouting(t *testing.T) {
l, n := backend(t, "legacy", 200, `{}`), backend(t, "new", 200, `{}`)
_, srv := build(t, l, n, []Rule{{Name: "orders", PathPrefix: "/orders", Percent: 100}})
if who, _, _ := get(t, srv.URL, "/orders/1", nil); who != "new" {
t.Fatalf("/orders served by %s", who)
}
if who, _, _ := get(t, srv.URL, "/users/1", nil); who != "legacy" {
t.Fatalf("/users served by %s", who)
}
}
func TestHeaderAndTenantRouting(t *testing.T) {
l, n := backend(t, "legacy", 200, `{}`), backend(t, "new", 200, `{}`)
_, srv := build(t, l, n, []Rule{{
Name: "orders", PathPrefix: "/orders", Percent: 0,
ForceHeader: "X-Route", ForceValue: "new",
Tenants: map[string]bool{"acme": true},
}})
if who, _, _ := get(t, srv.URL, "/orders", map[string]string{"X-Route": "new"}); who != "new" {
t.Fatalf("header: %s", who)
}
if who, _, _ := get(t, srv.URL, "/orders", map[string]string{"X-Tenant": "acme"}); who != "new" {
t.Fatalf("tenant: %s", who)
}
if who, _, _ := get(t, srv.URL, "/orders", map[string]string{"X-Tenant": "other"}); who != "legacy" {
t.Fatalf("other tenant: %s", who)
}
}
func TestPercentIsStickyAndRoughlyRight(t *testing.T) {
rules := []Rule{{Name: "orders", PathPrefix: "/orders", Percent: 20}}
toNew := 0
for i := 0; i < 2000; i++ {
r, _ := http.NewRequest(http.MethodGet, "/orders", nil)
r.Header.Set("X-User-Id", fmt.Sprintf("user-%d", i))
first := decide(rules, r).Backend
if again := decide(rules, r).Backend; again != first {
t.Fatalf("user-%d flapped", i)
}
if first == Modern {
toNew++
}
}
if toNew < 300 || toNew > 500 { // 20% of 2000 = 400, generous band
t.Fatalf("expected about 400 to new, got %d", toNew)
}
}
func TestRaisingPercentOnlyAddsUsers(t *testing.T) {
low := []Rule{{PathPrefix: "/", Percent: 5}}
high := []Rule{{PathPrefix: "/", Percent: 10}}
for i := 0; i < 2000; i++ {
r, _ := http.NewRequest(http.MethodGet, "/x", nil)
r.Header.Set("X-User-Id", fmt.Sprintf("u%d", i))
if decide(low, r).Backend == Modern && decide(high, r).Backend != Modern {
t.Fatalf("u%d left the new system when percent grew", i)
}
}
}
func TestKillSwitchForcesLegacy(t *testing.T) {
l, n := backend(t, "legacy", 200, `{}`), backend(t, "new", 200, `{}`)
f, srv := build(t, l, n, []Rule{{Name: "orders", PathPrefix: "/orders", Percent: 100}})
if who, _, _ := get(t, srv.URL, "/orders", nil); who != "new" {
t.Fatalf("before kill: %s", who)
}
f.SetKillSwitch(true)
if who, _, _ := get(t, srv.URL, "/orders", nil); who != "legacy" {
t.Fatalf("after kill: %s", who)
}
if f.Metrics.Get("requests|orders|legacy|kill-switch") != 1 {
t.Fatal("kill-switch decision not counted")
}
}
func TestShadowMatchAndMismatch(t *testing.T) {
l := backend(t, "legacy", 200, `{"id":1,"total":"10.00","at":"2026-01-01"}`)
n := backend(t, "new", 200, `{"at":"2026-01-02","total":"10.00","id":1}`)
f, srv := build(t, l, n, []Rule{{
Name: "orders", PathPrefix: "/orders", Percent: 0, Shadow: true, IgnoreFields: []string{"at"},
}})
who, _, body := get(t, srv.URL, "/orders/1", nil)
f.Wait()
if who != "legacy" || !strings.Contains(body, "2026-01-01") {
t.Fatalf("client must get the legacy answer, got %s %s", who, body)
}
if f.Metrics.Get("shadow|orders|match") != 1 {
t.Fatalf("expected a match, mismatches: %v", f.Metrics.Mismatches())
}
n2 := backend(t, "new", 200, `{"id":1,"total":"10.50"}`)
f2, srv2 := build(t, l, n2, []Rule{{
Name: "orders", PathPrefix: "/orders", Percent: 0, Shadow: true, IgnoreFields: []string{"at"},
}})
get(t, srv2.URL, "/orders/1", nil)
f2.Wait()
if f2.Metrics.Get("shadow|orders|mismatch") != 1 {
t.Fatal("expected a mismatch")
}
if m := f2.Metrics.Mismatches(); len(m) != 1 || !strings.Contains(m[0], "$.total") {
t.Fatalf("mismatch should name the field, got %v", m)
}
}
func TestShadowSkipsUnsafeMethods(t *testing.T) {
l, n := backend(t, "legacy", 200, `{}`), backend(t, "new", 200, `{}`)
f, srv := build(t, l, n, []Rule{{Name: "orders", PathPrefix: "/orders", Shadow: true}})
resp, err := http.Post(srv.URL+"/orders", "application/json", strings.NewReader(`{}`))
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
f.Wait()
if f.Metrics.Get("shadow|orders|match")+f.Metrics.Get("shadow|orders|mismatch")+f.Metrics.Get("shadow|orders|error") != 0 {
t.Fatal("a POST must never be mirrored")
}
}
func TestFallbackToLegacyOnNew5xx(t *testing.T) {
l, n := backend(t, "legacy", 200, `ok`), backend(t, "new", 503, `boom`)
f, srv := build(t, l, n, []Rule{{Name: "orders", PathPrefix: "/orders", Percent: 100, FallbackToLegacy: true}})
who, code, _ := get(t, srv.URL, "/orders", nil)
if who != "legacy" || code != 200 {
t.Fatalf("expected legacy fallback, got %s %d", who, code)
}
if f.Metrics.Get("fallback|orders|new->legacy") != 1 {
t.Fatal("fallback not counted")
}
}
func TestDiffStatusAndIgnoredNestedField(t *testing.T) {
if d := Diff(Captured{200, []byte(`{}`)}, Captured{404, []byte(`{}`)}, nil); !strings.Contains(d, "status") {
t.Fatalf("got %q", d)
}
a := Captured{200, []byte(`{"items":[{"id":1,"ts":5}]}`)}
b := Captured{200, []byte(`{"items":[{"id":1,"ts":9}]}`)}
if d := Diff(a, b, []string{"ts"}); d != "" {
t.Fatalf("ignored nested field still reported: %q", d)
}
}A runnable demo (stage 1 shadow only, stage 2 at 10%, stage 3 at 100%, then the kill switch):
// Demo: two fake systems, a facade, three rollout stages and a kill switch.
// Run with: go run ./cmd/demo
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"academy/strangler-fig-migration/facade"
)
func fake(name, body string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Served-By", name)
_, _ = io.WriteString(w, body)
}))
}
func main() {
legacy := fake("legacy", `{"id":1,"total":"10.00"}`)
modern := fake("new", `{"id":1,"total":"10.00"}`)
defer legacy.Close()
defer modern.Close()
lu, _ := url.Parse(legacy.URL)
nu, _ := url.Parse(modern.URL)
stages := []struct {
label string
percent int
shadow bool
}{
{"stage 1: shadow only, 0% live", 0, true},
{"stage 2: canary, 10% live", 10, false},
{"stage 3: 100% live", 100, false},
}
for _, st := range stages {
f := facade.New(lu, nu, []facade.Rule{{
Name: "orders", PathPrefix: "/orders", Percent: st.percent, Shadow: st.shadow,
}})
front := httptest.NewServer(f)
counts := map[string]int{}
for i := 0; i < 1000; i++ {
req, _ := http.NewRequest(http.MethodGet, front.URL+"/orders/1", nil)
req.Header.Set("X-User-Id", fmt.Sprintf("user-%d", i))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
counts[resp.Header.Get("X-Served-By")]++
}
f.Wait()
fmt.Printf("%-32s legacy=%4d new=%4d shadow_match=%d\n", st.label,
counts["legacy"], counts["new"], f.Metrics.Get("shadow|orders|match"))
if st.percent == 100 {
f.SetKillSwitch(true)
resp, _ := http.Get(front.URL + "/orders/1")
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
fmt.Printf("%-32s served by %s\n", "kill switch on:", resp.Header.Get("X-Served-By"))
}
front.Close()
}
}The Go angle
net/http/httputil.ReverseProxy does the forwarding, so the facade is a few hundred lines. Stable hashing uses hash/fnv; the kill switch is an atomic.Bool; shadow work runs in a goroutine with context.WithoutCancel so the client's cancellation does not abort the comparison, and a sync.WaitGroup makes it testable. Three limits to know: the shadow body is capped at 1 MiB (larger answers are skipped, not compared), only GET and HEAD are mirrored, and the counters live in memory (export them to Prometheus in production). In a real facade add timeouts on both ReverseProxy transports and wrap each backend in a circuit breaker.
Laravel
Before
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
// Before: every route is hard-wired to one side. Moving /orders means editing
// this file, deploying, and hoping. There is no percentage, no shadow, no way
// back that does not need another deploy.
final class OrderController
{
public function show(Request $request, int $id)
{
$useNew = true; // flipped by hand for everybody at once
$base = $useNew ? 'http://orders.internal.example' : 'http://legacy.internal.example';
return Http::get("{$base}/orders/{$id}")->json();
}
}After
Config, a class-based Pennant feature, the routing middleware (with a terminable shadow comparison), routes with a kill-switch endpoint and a test:
<?php
// config/strangler.php
return [
'legacy_url' => env('STRANGLER_LEGACY_URL', 'http://legacy.internal.example'),
'shadow_url' => env('STRANGLER_SHADOW_URL', 'http://orders.internal.example'),
// Runtime kill switch lives in the cache so every instance sees it at once.
'kill_switch_key' => 'strangler:kill',
// Which fields are legitimately different between the two systems.
'ignore_fields' => ['updated_at', 'request_id', 'served_by'],
// Reads come from here during the migration: 'legacy' or 'new'.
'read_from' => env('STRANGLER_READ_FROM', 'legacy'),
];<?php
namespace App\Features;
use App\Models\User;
use Illuminate\Support\Lottery;
// Class-based Laravel Pennant feature: who gets the new orders system.
final class NewOrders
{
public function resolve(User $user): mixed
{
return match (true) {
$user->isInternalTeamMember() => true, // staff first
$user->isHighTrafficCustomer() => false, // keep the big ones on legacy for now
default => Lottery::odds(5, 100), // then 5% of everybody else
};
}
}<?php
namespace App\Http\Middleware;
use App\Features\NewOrders;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Laravel\Pennant\Feature;
use Symfony\Component\HttpFoundation\Response;
// Route a request to the new code (this application) or to the legacy system.
// Register an alias in bootstrap/app.php: 'strangle' => StranglerRoute::class
final class StranglerRoute
{
public function handle(Request $request, Closure $next): Response
{
$killed = (bool) Cache::get(config('strangler.kill_switch_key'), false);
$user = $request->user();
$useNew = ! $killed
&& $user !== null
&& Feature::for($user)->active(NewOrders::class);
if ($useNew) {
return $next($request); // the new controller answers
}
$response = $this->forwardToLegacy($request);
$response->headers->set('X-Served-By', 'legacy');
$request->attributes->set('strangler.legacy', true); // terminate() runs on a fresh instance
return $response;
}
// Terminable middleware: runs after the response has been sent, so a slow
// new system can never delay the user. Laravel resolves a fresh instance for
// terminate(), so state travels on the request, not on $this.
public function terminate(Request $request, Response $response): void
{
if (! $request->attributes->get('strangler.legacy', false)
|| ! $request->isMethodSafe()
|| Cache::get(config('strangler.kill_switch_key'), false)) {
return;
}
try {
$shadow = Http::timeout(2)
->withHeaders(['X-Shadow' => '1'])
->get(config('strangler.shadow_url').$request->getRequestUri());
} catch (\Throwable $e) {
Log::warning('strangler.shadow.error', ['path' => $request->path(), 'error' => $e::class]);
return;
}
$ignore = array_flip(config('strangler.ignore_fields'));
$a = $this->normalise(json_decode($response->getContent(), true), $ignore);
$b = $this->normalise($shadow->json(), $ignore);
if ($response->getStatusCode() !== $shadow->status() || $a !== $b) {
Log::warning('strangler.shadow.mismatch', [
'path' => $request->path(),
'legacy_status' => $response->getStatusCode(),
'new_status' => $shadow->status(),
]);
}
}
private function forwardToLegacy(Request $request): Response
{
$upstream = Http::timeout(5)
->withHeaders(['X-Request-Id' => (string) $request->header('X-Request-Id', '')])
->send($request->method(), config('strangler.legacy_url').$request->getRequestUri(), [
'body' => $request->getContent(),
]);
return response($upstream->body(), $upstream->status())
->header('Content-Type', $upstream->header('Content-Type'));
}
private function normalise(mixed $value, array $ignore): mixed
{
if (! is_array($value)) {
return $value;
}
$out = [];
foreach ($value as $k => $v) {
if (! isset($ignore[$k])) {
$out[$k] = $this->normalise($v, $ignore);
}
}
ksort($out);
return $out;
}
}<?php
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
// routes/web.php: one middleware alias per migrated slice.
Route::middleware(['auth', 'strangle'])->group(function () {
Route::get('/orders/{id}', [OrderController::class, 'show']);
Route::post('/orders', [OrderController::class, 'store']);
});
// An operator endpoint behind your admin auth: flip the kill switch at runtime.
Route::middleware(['auth', 'can:operate'])->post('/ops/strangler/kill', function () {
Cache::forever(config('strangler.kill_switch_key'), true);
return response()->noContent();
});<?php
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
final class StranglerRouteTest extends TestCase
{
public function test_kill_switch_sends_everyone_to_legacy(): void
{
Http::fake(['legacy.internal.example/*' => Http::response(['id' => 1], 200)]);
Cache::forever(config('strangler.kill_switch_key'), true);
$response = $this->actingAs(User::factory()->create())->get('/orders/1');
$response->assertOk()->assertHeader('X-Served-By', 'legacy');
Http::assertSentCount(1); // no shadow call while the switch is on
}
}Read from one side, write to both, with a repair table, and the reconciliation command with its schedule:
<?php
namespace App\Repositories;
interface OrderRepository
{
/** @return array<string, mixed>|null */
public function find(int $id): ?array;
/** @param array<string, mixed> $order */
public function save(array $order): void;
}<?php
namespace App\Repositories;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
// Read from one side (config), write to both. Legacy stays the source of truth
// until cutover, so a failed write to the new side never fails the request: it
// is recorded and repaired by the reconcile command instead.
final class DualWriteOrderRepository implements OrderRepository
{
public function find(int $id): ?array
{
$connection = config('strangler.read_from') === 'new' ? 'new' : 'legacy';
$row = DB::connection($connection)->table('orders')->where('id', $id)->first();
return $row === null ? null : (array) $row;
}
public function save(array $order): void
{
// 1. Source of truth first. If this throws, nothing was written anywhere.
DB::connection('legacy')->table('orders')->updateOrInsert(['id' => $order['id']], $order);
// 2. Second write is idempotent (keyed by id), so a retry is harmless.
try {
DB::connection('new')->table('orders')->updateOrInsert(['id' => $order['id']], $order);
} catch (\Throwable $e) {
Log::error('strangler.dualwrite.failed', ['id' => $order['id'], 'error' => $e::class]);
DB::connection('legacy')->table('migration_write_failures')->insert([
'entity' => 'order',
'entity_id' => $order['id'],
'target' => 'new',
'error' => mb_substr($e->getMessage(), 0, 500),
]);
}
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Repair queue for dual writes whose second write failed.
return new class extends Migration
{
public function up(): void
{
Schema::create('migration_write_failures', function (Blueprint $table) {
$table->id();
$table->string('entity', 64);
$table->unsignedBigInteger('entity_id');
$table->string('target', 16); // which side failed: 'new'
$table->text('error');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('repaired_at')->nullable();
$table->index(['entity', 'entity_id']);
});
}
public function down(): void
{
Schema::dropIfExists('migration_write_failures');
}
};<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
// php artisan strangler:reconcile --max-diff=0
// Compares legacy and new row by row in key order and exits non-zero when the
// number of differences is above the threshold, so a pipeline can gate on it.
final class ReconcileOrders extends Command
{
protected $signature = 'strangler:reconcile {--max-diff=0} {--chunk=1000}';
protected $description = 'Compare orders in the legacy and new databases';
private const COLUMNS = ['id', 'customer_id', 'status', 'total_cents', 'currency'];
public function handle(): int
{
$missing = $different = $checked = 0;
DB::connection('legacy')->table('orders')
->select(self::COLUMNS)
->chunkById((int) $this->option('chunk'), function ($rows) use (&$missing, &$different, &$checked) {
$ids = $rows->pluck('id')->all();
$other = DB::connection('new')->table('orders')
->select(self::COLUMNS)->whereIn('id', $ids)->get()->keyBy('id');
foreach ($rows as $row) {
$checked++;
$twin = $other->get($row->id);
if ($twin === null) {
$missing++;
} elseif ((array) $twin !== (array) $row) {
$different++;
$this->warn("id {$row->id} differs");
}
}
});
$this->info("checked={$checked} missing_in_new={$missing} different={$different}");
return ($missing + $different) > (int) $this->option('max-diff') ? self::FAILURE : self::SUCCESS;
}
}<?php
use Illuminate\Support\Facades\Schedule;
// routes/console.php: reconcile every hour, one run at a time, on one server.
Schedule::command('strangler:reconcile --max-diff=0')
->hourly()
->withoutOverlapping()
->onOneServer();The Laravel angle
Laravel Pennant stores each scope's resolved value, so a user stays in or out of the feature while Lottery::odds(5, 100) is evaluated only once per scope; Feature::activateForEveryone and Feature::deactivateForEveryone are the bulk switches. Middleware can be registered with an alias in bootstrap/app.php. For work after the response, the documentation's terminable middleware calls terminate once the response has been sent; Laravel resolves a fresh middleware instance for it unless you register the middleware as a singleton, which is why the snippet carries state on the request attributes, not on $this. Http::pool runs requests concurrently (the pool accepts a concurrency argument) and a pooled request that fails at the connection level appears in the responses array as a ConnectionException instead of a Response, so it fits a reconciliation job that checks many endpoints at once, for example comparing 20 order ids against both systems per iteration. The scheduler runs strangler:reconcile with withoutOverlapping and onOneServer. The documentation of Laravel's HTTP client does not describe an Http::async helper, so this chapter does not use one; for fire-and-forget work use terminable middleware or a queued job. Laravel's Octane keeps the application in memory between requests, so never store per-request shadow state in static properties.
Solving the classic problems
A shadow diff that never reaches zero
| Cause | How to see it | Fix |
|---|---|---|
| Timestamps and ids | Diff names updated_at or a uuid | Add to IgnoreFields |
| Unordered lists | Same elements, different order | Sort by a key before comparing |
| Data not yet synced | Diff only on rows younger than the lag | Skip rows newer than the lag |
| Real bug in new | Diff is stable and reproducible | Fix and re-shadow |
| Real bug in legacy | Legacy is wrong, new is right | Decide explicitly; document the behaviour change |
| Non-deterministic endpoint | Legacy differs from itself | Diff legacy against legacy to measure the noise floor, subtract it |
Dual-write drift
| Step | Action | Result |
|---|---|---|
| 1 | Make legacy the source of truth, write it first | One truth |
| 2 | Idempotent upsert on the new side | Retries are safe |
| 3 | Record second-write failures in a repair table | No silent loss |
| 4 | Reconcile hourly; page on a non-zero diff above the threshold | Drift found by machines |
| 5 | Prefer outbox or CDC for the new side | Removes the second write from the request |
-- Backfill batch and catch-up guard (full file below).
INSERT INTO new_orders (id, customer_id, status, total_cents, currency, created_at, updated_at)
SELECT id, customer_id, status, total_cents, currency, created_at, updated_at
FROM legacy_orders WHERE id > :last_id ORDER BY id LIMIT 1000
ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, total_cents = EXCLUDED.total_cents,
updated_at = EXCLUDED.updated_at
WHERE new_orders.updated_at <= EXCLUDED.updated_at;Backfill and the view swap:
-- Backfill in small keyset batches, then let dual writes (or CDC) keep up.
-- Run in a loop from a worker; remember the last id between iterations.
-- Idempotent copy of one batch: safe to re-run after a crash.
INSERT INTO new_orders (id, customer_id, status, total_cents, currency, created_at, updated_at)
SELECT id, customer_id, status, total_cents, currency, created_at, updated_at
FROM legacy_orders
WHERE id > :last_id
ORDER BY id
LIMIT 1000
ON CONFLICT (id) DO UPDATE
SET customer_id = EXCLUDED.customer_id,
status = EXCLUDED.status,
total_cents = EXCLUDED.total_cents,
currency = EXCLUDED.currency,
updated_at = EXCLUDED.updated_at
-- never overwrite a newer row written by the dual-write path
WHERE new_orders.updated_at <= EXCLUDED.updated_at;
-- Expand / contract on the new schema (see the schema-migrations chapter):
-- expand : add nullable columns, create the new table, keep both readable
-- migrate : dual write + backfill + reconcile until the diff is zero
-- contract : stop writing legacy, drop old columns/tables after the soak period
-- Database view as a seam: new code reads a view that hides which table is behind it.
CREATE VIEW orders_read AS
SELECT id, customer_id, status, total_cents, currency FROM legacy_orders;
-- At cutover: CREATE OR REPLACE VIEW orders_read AS SELECT ... FROM new_orders;Reconciliation queries (counts and checksums by day, missing rows, extra rows, different rows):
-- Dual-write reconciliation. Run against a snapshot or a replica, never the hot primary.
-- Assumes both tables are reachable from one session (postgres_fdw, or two exported copies).
-- legacy_orders = rows from the legacy database
-- new_orders = rows from the new system's database
-- 1. Cheap first pass: counts and a checksum per day. Mismatching days are drilled into.
SELECT d.day,
l.n AS legacy_rows, n.n AS new_rows,
l.chk AS legacy_checksum, n.chk AS new_checksum
FROM (SELECT generate_series(date '2026-11-01', date '2026-11-26', interval '1 day')::date AS day) d
LEFT JOIN (
SELECT created_at::date AS day, count(*) AS n,
md5(string_agg(id::text || ':' || status || ':' || total_cents::text, ',' ORDER BY id)) AS chk
FROM legacy_orders GROUP BY 1
) l USING (day)
LEFT JOIN (
SELECT created_at::date AS day, count(*) AS n,
md5(string_agg(id::text || ':' || status || ':' || total_cents::text, ',' ORDER BY id)) AS chk
FROM new_orders GROUP BY 1
) n USING (day)
WHERE l.n IS DISTINCT FROM n.n OR l.chk IS DISTINCT FROM n.chk
ORDER BY d.day;
-- 2. Rows present in legacy but missing in new (lost second write, backfill gap).
SELECT l.id
FROM legacy_orders l
LEFT JOIN new_orders n ON n.id = l.id
WHERE n.id IS NULL
ORDER BY l.id
LIMIT 1000;
-- 3. Rows present in new but not in legacy (should be zero until cutover).
SELECT n.id
FROM new_orders n
LEFT JOIN legacy_orders l ON l.id = n.id
WHERE l.id IS NULL
ORDER BY n.id
LIMIT 1000;
-- 4. Rows in both, with different values. IS DISTINCT FROM treats NULL = NULL as equal.
SELECT l.id,
l.status AS legacy_status, n.status AS new_status,
l.total_cents AS legacy_total_cents, n.total_cents AS new_total_cents
FROM legacy_orders l
JOIN new_orders n USING (id)
WHERE (l.customer_id, l.status, l.total_cents, l.currency)
IS DISTINCT FROM
(n.customer_id, n.status, n.total_cents, n.currency)
ORDER BY l.id
LIMIT 1000;
-- 5. Ignore rows still in flight: only compare rows older than the replication/backfill lag.
-- Add to every query above: AND l.updated_at < now() - interval '5 minutes'The new system quietly depends on legacy
| Symptom | Fix |
|---|---|
| New service queries legacy tables directly | Replace with a view, then with CDC into its own store |
| New service calls a legacy endpoint for core data | Move the data and the endpoint's logic; keep an anti-corruption layer for the rest |
| Shared libraries pull legacy classes in | Extract a contract package; forbid imports from the legacy namespace in CI |
| Deploy of new requires deploy of legacy | Contract tests and versioned interfaces (API versioning) |
The strangler stalls at 80%
| Cause | Fix |
|---|---|
| The hard 20% is the oldest, most coupled code | Do the hard slice early, with the strongest team, rather than last |
| No deadline | Date per slice, tied to a visible cost (licence, hardware renewal) |
| Team moved on | Fund a dedicated deletion team; count deleted lines as output |
| New features keep landing on legacy | Rule: new features only on the new side |
Writes during canary
A user routed to the new system creates an order. Legacy reports must still see it. Options: new writes through to legacy (dual write toward the old store), CDC from new back to legacy, or keep canary slices read-only until the data path is proven. Choose one per slice and test the reverse path before ramping.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Read-only slice, easy to mirror | Shadow first, then canary by percentage | Response diffing | Zero user risk during shadow |
| Slice with writes and money | Parallel run plus reconciliation | Idempotency keys, ledger-style rows | Diffs are expected and must be explained |
| B2B product with few large tenants | Tenant-based routing | Per-tenant rollback | Easy to communicate and revert |
| Consumer product, millions of users | Sticky percentage canary | Staff first, then 1%, 5%, 25% | Statistical power, gradual |
| Inside one codebase | Branch by abstraction | Verifying wrapper, flag per tenant | No network seam exists |
| Legacy is a database only | View or CDC, then move writers | Tracer write | Data seam before code seam |
| Legacy log is accessible | CDC (Debezium) | Outbox for new events | Removes dual write from requests |
| Legacy log is not accessible | Event interception at the facade | Reconcile hourly | Next best |
| New and old share a UI | UI composition | Edge includes or micro-frontends | Screens migrate with the backend |
| Small system, one team, few users | Maybe a rewrite is fine | Feature freeze for weeks, not years | The pattern has overhead; do not use it for 5,000 lines |
| Deadline is a licence expiry | Strangle with a hard date; consider a lift-and-shift first | Reduce scope | The date decides the order |
| Facade placement | When | Trade-off |
|---|---|---|
| Existing load balancer or ingress | Fast start | Limited diff, rules in infra config |
| API gateway | You already run one | Another place for logic to creep in |
| Dedicated facade service | Need shadow, diff, custom rules | You own and operate it |
| Service mesh | Service-to-service slices | Only inside the mesh |
| In the legacy app | Cannot place anything in front | Couples facade to the thing you are removing |
In architecture: from a single process to a distributed system
Monolith: one process, one database
You cannot put a network proxy in front of a function call, so the seam is in code. Use branch by abstraction: wrap the part to replace (the payment module, the search library, the ORM) in an interface, add a verifying implementation that calls old and new, returns the old result and logs differences, switch by flag per tenant, then delete. The data seam is a view or a schema built with expand/contract. Example: replace a home-grown tax calculator inside a PHP monolith: TaxCalculator interface, LegacyTaxCalculator, ServiceTaxCalculator; run both for a month; the diff report shows 14 rounding differences to decide on.
Modular monolith: boundaries without the network
The strangler's destination may be a modular monolith: move a slice into a module with its own tables and a public interface, enforce boundaries in CI, and keep one deployment. Shopify's post describes exactly this destination and a tool to track violations. Decide here whether microservices are needed at all: Monolith vs Microservices vs Modular Monolith.
Microservices: every arrow is a decision
Moving a slice into its own service adds a network hop and a data boundary. Example flow for orders:
1 client -> facade POST /orders rule: orders, percent 25, user in bucket
2 facade -> orders-service POST /orders (new side)
3 orders-service -> own DB INSERT order 9001
4 orders-service -> outbox INSERT event OrderPlaced (same transaction)
5 relay -> broker OrderPlaced 9001
6 legacy adapter <- broker consumes OrderPlaced, writes legacy.orders (keeps reports alive)
7 reconcile job compares orders-service DB with legacy.orders hourlyUse the outbox pattern for step 4 and CDC where the legacy side needs a feed; keep idempotency keys on every write. Data ownership rules: Data Ownership in Microservices.
Distributed data: replicas, caches, regions
Reconcile on a replica, not the primary, and ignore rows newer than the replication lag, otherwise you report phantom diffs. A cache in front of legacy can hide a migration bug for the TTL; flush or version cache keys at each cutover step. Multi-region: migrate one region first (a natural canary), and remember that CDC lag across regions widens the window where reads from new see old data; see Consistency Models for read-your-writes options such as routing a user to one side for the session.
Scaling path: 1x, 10x, 100x
| Scale | Facade | Shadow | Data | Team |
|---|---|---|---|---|
| 1x: one team, thousands of requests per day | An NGINX location block | Replay a day of logs offline | Dual write with an hourly reconcile | One owner per slice |
| 10x: millions of requests per day | Envoy or an API gateway with weights | Live mirror at 10% | CDC (Debezium) plus backfill | Migration squad |
| 100x: tens of thousands of requests per second | Edge routing plus regional canaries, automated analysis (Argo Rollouts or Flagger) | Sampled mirroring, diff in a stream job | CDC with schema registry, per-tenant cutover | Platform team and product teams, deletion metric reviewed monthly |
Lab: from facade to cutover, with numbers
Experiment 1: run the Go demo (run)
cd docs/snippets/system-design/strangler-fig-migration/go
go run ./cmd/demo
# output (run on 2026-11-26):
# stage 1: shadow only, 0% live legacy=1000 new= 0 shadow_match=1000
# stage 2: canary, 10% live legacy= 898 new= 102 shadow_match=0
# stage 3: 100% live legacy= 0 new=1000 shadow_match=0
# kill switch on: served by legacyThe 102 of 1000 at "10%" is a hash distribution, not an error: FNV-1a over 1,000 distinct user ids puts about 10% below the threshold with a few points of spread.
Experiment 2: the tests with the race detector (run)
go vet ./... && go test -race ./...
# ok academy/strangler-fig-migration/facadeExperiment 3: shadow a real route with NGINX (expected, not run)
# nginx.conf (excerpt)
# location /orders/ { mirror /mirror; mirror_request_body off; proxy_pass http://legacy; }
# location = /mirror { internal; proxy_pass http://new$request_uri; }
# expected: clients get legacy answers; new receives a copy; its answers are ignoredExperiment 4: Laravel canary with Pennant (expected, not run)
php artisan pennant:purge new-orders # clear stored results
php artisan tinker
>>> Laravel\Pennant\Feature::for($user)->active(App\Features\NewOrders::class)
# expected: the same value on repeated calls for the same user (stored by Pennant)Experiment 5: reconcile to zero (expected, not run)
php artisan strangler:reconcile --max-diff=0
# expected first run : checked=48210 missing_in_new=12 different=3 (exit code 1)
# after repair worker: checked=48210 missing_in_new=0 different=0 (exit code 0)Experiment 6: rehearse the kill switch (expected, not run)
Raise the canary to 25% in staging, run a load generator, press the kill switch, and measure the seconds until the new service's request rate reaches zero. Target: under 5 seconds. A result above that means the switch is read from a slow store.
Common misconceptions
| Belief | Reality |
|---|---|
| "Strangler fig means microservices." | It is a replacement strategy; Shopify's destination was a modular monolith |
| "The facade is a temporary hack." | It is the control point of the migration; remove it deliberately at the end, or keep it as the gateway |
| "5% canary means each request has a 5% chance." | The bucket must be sticky per user, or one user sees two systems |
| "Shadow traffic is risk free." | Shadowed writes duplicate emails and charges; shadow reads only |
| "Dual write in a transaction is fine." | Two databases share no transaction; use source of truth plus repair plus reconcile, or CDC |
| "100% traffic on new means done." | Done is when legacy code and data are deleted |
| "We will write the rollback plan if needed." | A rollback not rehearsed before cutover is a hope |
| "Feature flag equals deployment." | A flag decides who runs the code; a deployment puts the code on servers |
| "A diff rate of zero proves correctness." | It proves the sampled requests agree; diverse traffic and reconcile jobs extend the proof |
| "Reads and writes should move together." | Move reads first, writes last: reads are reversible |
| "A rewrite is always worse." | For a tiny or well-specified system a rewrite can be cheaper than the transitional architecture |
Cheat sheet
| Topic | What to remember |
|---|---|
| Pattern | Facade in front, move slices, grow new, retire old |
| First step | Put the facade in with all rules saying legacy |
| Seam | A place to cut without rewriting the inside: URL, queue, interface, table |
| Routing | Path, header, tenant, sticky percentage; log the reason |
| Percentage | Hash a stable key; raising the percent only adds users |
| Shadow | Mirror GET only; diff status and body; ignore noise; never sleep the user |
| Canary ramp | Staff, 1%, 5%, 25%, 50%, 100% with written exit criteria |
| Parallel run | For money: run both, reconcile, explain every diff |
| Dual write | Truth first, idempotent upsert second, repair queue, reconcile |
| CDC | Prefer to dual write when the legacy log is readable |
| Data order | Backfill, sync, reconcile to zero, read from new write to both, write new, retire |
| Branch by abstraction | Interface, two implementations, flag, delete |
| Rollback | Kill switch read at runtime, rehearsed, with a data plan |
| Done | Legacy code, routes, tables, jobs, credentials deleted |
| Metrics | % traffic, % endpoints, % data, diff rate, lines deleted |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why must the facade be in place before the new code is ready? Must-know
Answer
Answer: It is the only way to move traffic gradually, measure old versus new, and undo in seconds. It is also transparent while every rule says legacy, so it can be proven safe first.
2 — Why must a percentage rollout hash a stable key? Must-know
Answer
Answer: Per-request randomness makes one user bounce between systems with different data and behaviour. A hash of the user id keeps each user in one bucket, and raising the threshold only adds users.
3 — Which requests may be shadowed, and why? Important
Answer
Answer: Safe requests (GET, HEAD). A shadow copy runs real code, so a mirrored write can charge cards or send emails twice. Writes need a dry-run mode signalled by a header.
4 — Name two reasons a shadow diff is not zero that are not bugs. Good to know
Answer
Answer: Timestamps and request ids; unordered collections; data not yet synced; non-deterministic endpoints. Measure the noise floor by diffing legacy against legacy.
5 — What goes wrong with dual write and what are the three mitigations? Must-know
Answer
Answer: Partial failure, ordering and duplicates, because two stores share no transaction. Make legacy the source of truth, make the second write an idempotent upsert with a version guard, and reconcile with a repair queue; better, use outbox or CDC.
6 — In what order should reads and writes move for one entity? Important
Answer
Answer: Backfill, sync, reconcile to zero, read from new while writing to both, then write to new and sync back, then retire the legacy write.
7 — When do you use branch by abstraction instead of a facade? Important
Answer
Answer: When the thing being replaced is inside the process (a library, ORM, module) and there is no network seam.
8 — What is the difference between a canary and a feature flag? Must-know
Answer
Answer: A canary is a release strategy that sends a small share of traffic to the new version; a flag is the runtime switch used to implement it (and many other things).
9 — List four things that must be deleted at decommission. Important
Answer
Answer: Code and routes, tables and jobs, credentials and network paths, dashboards and alerts (also documentation and licences).
10 — Why is "100% of traffic on the new system" not a finished migration? Must-know
Answer
Answer: Legacy may still own data, jobs and people, and you still pay for it. Progress is measured by what has been deleted.
11 — Name an organisation that ended in a modular monolith, and one that started distributed. Good to know
Answer
Answer: Shopify (componentization into a modular monolith); Monzo (built as distributed microservices from the start).
Glossary
| Term | Meaning |
|---|---|
| Strangler fig | Gradual replacement of a system by growing a new one around it |
| Facade | The front layer that intercepts and redirects requests |
| Seam | A place where the system can be split without rewriting its inside |
| Intercept / redirect | Catch a request and send it to another implementation |
| Branch by abstraction | Swap an implementation behind an interface, in one codebase |
| Routing rule | A match (path, header, tenant, percent) and a target |
| Path-based routing | Rule on the URL prefix |
| Header-based routing | Rule on a request header, for opt-in |
| Percentage rollout | Sending a stable share of users to the new side |
| Canary | A small first share of real traffic to the new version |
| Progressive delivery | Automated stepwise ramp with analysis between steps |
| Feature flag | A runtime switch controlling who runs which code |
| Kill switch | A flag that forces everything to legacy at once |
| Shadow traffic | Mirrored copies of requests whose answers are dropped after comparison |
| Dark launch | Running new code on real traffic without users seeing its output |
| Response diffing | Comparing status and body of old and new answers |
| Parallel run | Running both for real work and reconciling results |
| Reconciliation | Automated comparison of two datasets |
| Cutover | The moment the new system takes 100% |
| Decommission | Deleting the legacy system completely |
| Dual write | Application writes the same fact to two stores |
| Change data capture | Reading a database's change log and applying it elsewhere |
| Event interception | Publishing an event for each routed call |
| Database view | A named query that can hide which table is behind it |
| Synonym | An alias to a table or view in another schema or database (SQL Server, Oracle) |
| Expand/contract | Add new schema, migrate, remove old schema in separate steps |
| Backfill | Copying historical data to the new store |
| Read from new write to both | The phase where reads switch while writes still go to both |
| Anti-corruption layer | A translator that keeps legacy concepts out of the new model |
| Micro-frontend | A separately deployed piece of a web page |
| UI composition | Assembling a page from fragments of different systems |
| Contract test | A test that the interface shape is honoured |
| Traffic replay | Re-sending recorded requests to a test system |
| Rollback plan | Written triggers and actions to undo each step |
| Big-bang rewrite | Replacing everything at once |
| Legacy dependency | The new system relying on legacy data or code |
| Migration metrics | % traffic, % endpoints, % data, diff rate, code deleted |
| Pennant | Laravel's feature flag package |
| Http::pool | Laravel HTTP client method for concurrent requests |
| Monolith to Microservices | Sam Newman's book of migration patterns |
| Uber DOMA | Domain-Oriented Microservice Architecture |
References
- Martin Fowler, Strangler Fig (22 August 2024) and Original Strangler Fig Application (29 June 2004)
- Martin Fowler, Branch By Abstraction
- Sam Newman, Monolith to Microservices (table of contents of the pattern catalogue)
- Shopify Engineering, Deconstructing the Monolith (21 February 2019)
- Zalando Engineering, Micro Frontends, part 1 (11 March 2021)
- Monzo, Building a Modern Bank Backend (19 September 2016)
- Uber Engineering, Introducing Domain-Oriented Microservice Architecture (23 July 2020; archived copy, the original URL refuses automated clients)
- GitHub Engineering, Scientist: Measure Twice, Cut Once
- Diffy (response comparison)
- NGINX, ngx_http_mirror_module and ngx_http_split_clients_module
- Envoy, Route components
- Istio, VirtualService
- Argo Rollouts
- Debezium documentation
- Laravel 13: Middleware, Pennant, HTTP client, Task scheduling, Artisan console