Skip to content

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 forGo to
The whole page in four tablesEverything in one minute
Why not rewrite it all at onceWhy it exists
Fowler, Newman, Hammant, Cartwright/Horn/LewisWhere it comes from
The proxy that intercepts and redirectsThe facade
Finding the first sliceSeams and slicing
Path, header, tenant, percentage rulesRouting rules
Shadow traffic, dark launch, diffingShadow traffic
Canary, progressive delivery, flagsCanary and flags
Old and new side by sideParallel run and reconciliation
Dual write and why it hurtsDual write
CDC, event interception, views, synonymsMoving the data
Writes during the migrationReads and writes
Replacing code inside one processBranch by abstraction
Replacing the screensUI composition
Keeping legacy concepts out of new codeAnti-corruption layer
Contract tests, replayTesting
Switches and undoKill switch and rollback
The last two stepsCutover and decommission
Teams, timeline, progress numbersOrganisation and metrics
What goes wrongAnti-patterns
Shopify, Zalando, Monzo, UberCase examples
Exact knobs and error namesMechanics
CodeGo, Laravel
Classic failures and fixesSolving the classic problems
Which technique whenChoosing
Monolith to distributed systemIn architecture
Runnable experimentsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The loop, per slice.

StepWhat you doEvidence to move onUndo
1. SeamFind a boundary where traffic can be cut: a URL prefix, a queue, a table ownerThe seam has a test and an ownerNothing changed yet
2. FacadePut a proxy in front; route everything to legacyLatency and error rate unchangedRemove the proxy, point DNS back
3. BuildNew code behind a flag, tested against the contractContract tests greenDelete the branch
4. ShadowMirror safe requests to the new code, diff the answersDiff rate below the goal for N daysTurn mirroring off
5. CanarySend 1%, 5%, 25%, 50% of live trafficSLOs held at each stepPercentage to 0
6. Cutover100% to new, legacy warmSoak period passesKill switch to legacy
7. DecommissionDelete legacy code, routes, tablesNothing calls legacy for a full cycleRestore from archive only

Routing dimensions at the facade.

DimensionExample ruleTypical useWeakness
Path/orders/* goes to newCoarse slicesWhole endpoint moves at once
HeaderX-Route: newStaff, tests, canary testersNot for real users
Tenantacme is migratedB2B, easy rollback per customerUneven load
Percentage5% of users by sticky hashCanaryA bad 5% is still 5% of customers
MethodGET to new, POST to legacyRead slice firstReads and writes diverge

Data patterns while two systems own the data.

PatternIdeaRisk
Shared databaseNew service reads and writes legacy tablesHidden coupling, schema freeze
Database view or synonymNew code reads through a viewRead only, performance
Dual writeApplication writes both storesPartial failure, drift, ordering
Change data captureRead the legacy log and apply to newLag, schema coupling
Event interceptionFacade publishes an event per callLost events if not transactional
Backfill then switchCopy history, then catch upWindow of staleness
1 Seamfind the sliceroute in front0% to new2 Buildnew code behindflag, contracttests green3 Shadowmirror GET, diffparallel runusers see legacy4 Canary1%, 5%, 25%staff + tenantswatch SLOs5 Cutover100% to newlegacy warm,kill switch armed6 Decommissionsoak period overdelete legacy codedrop tables, routesexit: seam testedexit: contract okexit: diff below goalexit: SLO heldexit: soak N weeksno way back (archive)Rollback at stages 3 to 5: set percent to 0 or flip the kill switch; data stays reconciled.Progress metrics per slice: % traffic, % endpoints, % data, legacy code deletedA slice is done only at stage 6, not at stage 5.

Anti-patterns in one line each.

Anti-patternSymptom
Big-bang rewriteTwo years of no releases, then a cliff
Strangler that never finishesTwo systems forever, double the cost
Legacy becomes a dependency of the new systemNew service calls the old one for core data
Facade becomes a monolithBusiness logic creeps into the proxy
Dual write without reconciliationSilent 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 rewriteStrangler fig
One switch day, all risk at onceMany small switches, each with a way back
Value arrives after the whole rewriteValue arrives per slice
Old behaviour must be specified up frontOld behaviour is discovered by diffing real traffic
Feature freeze on the old systemOld system keeps shipping while shrinking
Failure means a cancelled projectFailure means one slice rolled back
Cost is hidden until the endCost 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 ​

  1. "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.
  2. "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.
  3. "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 ​

YearWhoWhat
2001Martin FowlerSees strangler figs on a holiday in the rain forests of Queensland (his own account on the bliki)
2004Martin FowlerPosts "Strangler Application" on his bliki: rewrite a critical system by growing the new one around the old
2019Martin FowlerRenames the post "Strangler Fig Application" to stress the botanical metaphor
2016GitHubPublishes Scientist, a library to run old and new code paths side by side and compare
2019ShopifyDescribes its componentization of a very large Rails monolith
2020UberDescribes Domain-Oriented Microservice Architecture, DOMA
2021ZalandoDescribes moving its web shop from Project Mosaic to an Interface Framework
2024Martin FowlerUpdates 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 typeProduct examplesGood atCareful with
Reverse proxyNGINX, HAProxy, EnvoyPath, header, weight rules; mirroringRules in config files need review and deploy discipline
API gatewayKong, AWS API Gateway, ApigeeAuth, rate limits, per-route pluginsAnother product to own; latency
Service meshIstio, LinkerdWeighted routes and mirroring per serviceOnly between services inside the mesh
EdgeCloudflare Workers, Fastly, CloudFront FunctionsGlobal, cheap, fast to changeLimited compute, no private network
In-process routerA middleware in the old or new appNo new hopCouples the facade to one app
Load balancerAWS ALB weighted target groupsSimple percentageNo user stickiness by default, no diff

Fix / how to use it:

sql
-- 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.

Clientsweb, mobile, APIFacade / API gateway1. kill switch on? yes: legacy2. path prefix matches a slice?3. header: X-Route: new4. tenant in migrated list?5. sticky hash(user) < percent6. metrics: requests by backendkill switch: no deploy, no restartNew serviceowns the migrated sliceanswers N% of live trafficLegacy systemanswers everything elsestill the source of truthliveliveshadow copy (GET only), diffShadow responses are compared and dropped; the client only ever sees the primary answer.

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 candidateValueRiskCouplingVerdict
Read-only catalogue pagesMediumLowLowGood first slice
Reporting and exportsMediumLowReads many tablesGood, if you can read a replica
Notifications (email, SMS)LowLowFire and forgetGood warm-up
AuthenticationHighHighEverything depends on itLate, or behind an adapter
Order checkoutHighHighPayments, stock, taxAfter the team has practice
A new feature nobody has yetHighLowNoneBuild 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
ProductHow you express a percentageSticky?
NGINXsplit_clients "${remote_addr}AAA" $variant { 5% new; * legacy; }By the key you hash (client address here), stable while the key is
Envoyruntime_fraction on a route match, or weighted clustersPer request unless you hash a header
IstioVirtualService route[].weightPer request; use consistent hash on the DestinationRule for stickiness
AWS ALBWeighted target groups in a forward actionOptional target group stickiness
Laravel PennantLottery::odds(5, 100) inside a feature, stored per scopeYes: the result is stored for the scope
This chapter's Go facadeBucket(StickyKey(r)) < rule.PercentYes: 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 sourceExampleHandling
Timestamps and idsupdated_at, request_idIgnore list per slice
OrderingUnordered arraysSort before comparing, or compare as sets
Floating point10.0 vs 10.00Normalise numbers, compare money as integers
Non-determinismRandom recommendationsMeasure noise with a legacy-vs-legacy diff first
Time-dependent data"5 minutes ago"Freeze the clock in the shadow path
Side effectsEmail, payment, webhooksShadow 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.

StageShareAudienceSoakGo on if
00%, shadow onlyNobody3 to 7 daysDiff rate below target
1Header opt-inStaff and testers1 dayNo blocking bugs
21%Random users, sticky1 dayErrors and p99 within the SLO
35%Random, sticky1 to 3 daysBusiness KPI (conversion, orders per minute) flat
425%Random2 daysSame, plus database load fine
550%Random3 daysSame
6100%Everybody1 to 4 weeksSoak ends, legacy kept warm
Flag systemWhere flags liveNotes
Laravel PennantArray or database driver, per scopeFeature::for($user)->active(NewOrders::class)
LaunchDarkly, Unleash, FlagsmithHosted or self-hosted serviceRules and targeting UI, audit log
Environment variableProcess startNeeds a restart: not a kill switch
Config table or cache keyYour database or RedisFast 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.

Raise percent1, 5, 25, 50, 100Soak and measureper backend: errors, p99,shadow diff, business KPISoft breachhold or step back one levelAll checks passfor the soak windowSevere breachkill switch: 0% at onceNext stepor cutover at 100%fix, then retryThresholds are written down before the rollout: no one negotiates them at 2 a.m.

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
CheckQuery shapeCatches
Count per bucketcount(*) GROUP BY day on bothLost writes
Checksum per bucketmd5(string_agg(...ORDER BY id))Any value drift, cheaply
Missing rowsLeft anti-joinLost second write, backfill gap
Different rowsIS DISTINCT FROM on a tupleRounding, mapping bugs
LagCompare max(updated_at)CDC or queue delay
sql
-- 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'
DangerWhy it happensMitigation
Partial failureNo shared transactionSource of truth first; repair queue; reconcile
OrderingTwo writers, no common clockVersion column, WHERE updated_at <= new.updated_at guard
DuplicatesRetriesIdempotent upsert by key
LatencyTwo round trips in the request pathAsync second write via outbox
Hidden couplingRequest fails if the new side is downNever fail the user because of the new side
PermanentDual 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.

PatternHow it worksDirectionConsistencyBest for
Shared databaseNew service queries legacy tablesRead and writeImmediateFirst days only: it is a coupling, not a migration
Database viewCREATE VIEW orders_read AS SELECT ...ReadImmediateHide the table behind a seam; swap the view at cutover
Synonym (SQL Server, Oracle)Alias to a table or view in another schema or databaseReadImmediateSame idea where the engine has synonyms; PostgreSQL uses views or foreign tables
Database wrapping serviceA small service owns the table, others call itRead and writeImmediateLegacy schema you cannot move yet
Change data captureDebezium reads the PostgreSQL WAL or MySQL binlog and publishes row changesLegacy to newEventual (lag)Keeping a copy current without touching legacy code
Event interceptionFacade publishes an event per call it routesEitherEventualWhen the legacy log is not accessible
Synchronize data in applicationApplication writes bothEitherDependsShort transitions only
Tracer writePick one entity, make the new store authoritative for it, sync backBothPer entityProving the path before the big move
Repository per bounded contextEach context hides its store behind a repository interfaceIn coden/aLets the store change without callers changing
ProductSeam toolNote
PostgreSQLViews, postgres_fdw, logical decoding, publicationsNo synonyms
MySQLViews, binlog (row format)Cross-database views work inside one server
SQL ServerSynonyms, views, CDC, Change TrackingSynonym can point across databases
OracleSynonyms, database links, GoldenGatePublic synonyms are global
MongoDBChange streamsNeeds a replica set
KafkaDebezium via Kafka ConnectOrdered per key
sql
-- 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.

PhaseReads fromWrites toTruthRollback
0 Facade onlyLegacyLegacyLegacyn/a
1 BackfillLegacyLegacyLegacyDelete new copy
2 Catch-up (CDC or dual write)LegacyLegacy and newLegacyStop the sync
3 Reconcile to zeroLegacyLegacy and newLegacyStop the sync
4 Read from new write to bothNewLegacy and newLegacy (still)Flip reads back
5 Write to new, sync backNewNew, legacy via syncNewFlip writes back (needs sync)
6 Retire legacy writeNewNewNewRestore 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 5

Fix: 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.

Applicationwrites via facadeLegacy databasesource of truth until cutoverwrites always land here firstNew databasefed by backfill + CDC / dual writeidempotent upserts by keyReconcilecounts, checksums, row diffgoal: zero diff, then switchReads: legacyphase 1 to 3Reads: newphase 4, still dual write1 write (truth)2 copy (best effort)Phases: backfill, dual write or CDC, reconcile to zero, read from new, write to new only, retire legacy.Never switch reads while the diff is non-zero; never remove the legacy write before the soak ends.

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 it

The 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.

ApproachWhere composedExampleCost
Page levelFacade routes by URL/checkout/* to new appVisible seams between pages
Fragment, server sideGateway or SSR assembles piecesEdge-side includes, Mosaic fragmentsLatency of slowest fragment
Component, client sideBrowser loads remote modulesModule federation, web componentsBundle size, shared state
Reverse proxy per routeNGINX location blocks/new/ prefix firstDuplicate 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.

LegacyNewTranslation rule
ord_st = 3Order.status = PAIDLookup table, unknown code fails loudly
cust_nm (single string)FirstName, LastNameSplit rule documented, tested with real samples
Money as DECIMAL(10,2)Integer minor units plus currencyRound once, at the boundary
Dates without zoneUTC instantsZone stated per source system
Soft-deleted rowsAbsent from the new modelFilter 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.

TechniqueWhat it checksTooling examples
Contract testsRequest and response shapes of the sliceOpenAPI schema validation, Pact
Consumer-driven contractsEach consumer states what it uses; the provider must satisfy allPact broker
Characterization testsRecord the legacy's output for inputs, assert the new one matchesGolden files
Traffic replayRe-send recorded production requests to new (offline)GoReplay, k6 from HAR logs, mirrored logs
Shadow trafficSame requests, live, to newNGINX mirror, Envoy, Istio mirror, this chapter's facade
Parallel runBoth run real work, results reconciledScientist, batch jobs
Load testNew system at 2x the slice's peakk6, 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.

StageTrigger examplesActionData consequence
ShadowShadow load hurts the new systemTurn mirroring offNone
CanaryError rate above SLO for 5 minutesPercent to 0 or kill switchRows written to new need reconcile
CutoverBusiness KPI dropsKill switchWrites to new must sync back to legacy
SoakWrong totals foundKill switch plus freezeRepair job from the diff
After decommissionn/aRestore from archiveHours 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 itemCheck
Routes and hostnamesFacade rule removed; 410 Gone or redirect for a period
Scheduled jobs and queuesNothing consumes or produces
DatabaseFinal dump archived, retention rules met, then dropped
Credentials and network pathsRevoked, firewall rules closed
Monitoring and alertsDashboards and alerts for legacy deleted
DocumentationDiagrams and runbooks updated
Contracts and licencesCancelled

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.

MetricMeasuresSourceTrap
% of trafficRequests answered by newFacade countersCheap to move, hides data
% of endpointsSlices fully on newRule tableEndpoints differ in size
% of dataTables or rows owned by newRow counts, ownership listDual-owned data counts as half
Shadow diff rateMismatches over compared requestsFacade countersNoise must be subtracted
Reconcile diffRows differingReconcile jobMust be zero before cutover
Legacy code deletedLines, files, jobs removedRepositoryThe only real progress
Cost of two systemsServers, licences, peopleFinanceThe reason to finish
Lead time per sliceSeam to decommissionTrackerShould 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-patternHow it showsRemedy
Big-bang rewriteParallel project, no releases, a switch weekendSlice and ship per seam
Strangler that never finishes80% done for three yearsA decommission date per slice, executive-visible deletion metric
Legacy becomes a dependency of the new systemNew service reads legacy tables for core data, calls legacy APIsAnti-corruption layer, data ownership transfer, a dependency budget
Facade grows business logicRules about discounts live in the proxyThe facade routes only; logic belongs in a service
Facade is a single point of failureOne instance, no health checksAt least two instances, health checks, fail-open to legacy
Dual write without reconciliationDrift found by customersReconcile job as a gate
Shadowing writesDuplicate emails or chargesSafe methods only or dry-run mode
No sticky routingOne user sees two behavioursHash a stable user key
Migrating the worst slice firstMonths without a winStart with a low-risk, valuable slice
Kill switch never exercisedSwitch fails when neededRehearse on a schedule
Copying every legacy bugNew system as bad as oldCharacterise first; decide per bug

Case examples Good to know ​

CompanyWhat the source saysLessonSource
ShopifyOne 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 toolA strangler can end in a modular monolith, not only in microservicesShopify Engineering, 21 Feb 2019
ZalandoWanted 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 pagesPercent of traffic is a valid progress metric when stated with its scopeZalando Engineering, 11 Mar 2021
MonzoBuilt the backend "as a collection of distributed microservices" from the start, rather than migrating a monolithA counter-example: no migration needed because the system was born distributed; the trade-off is the platform work described in the postMonzo blog, 19 Sep 2016
UberIntroduced Domain-Oriented Microservice Architecture (DOMA): domains, layers, gateways and extension points to reduce the complexity of a large microservice estateStrangling may continue after microservices: regrouping services into domainsUber 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 ​

ProductSettingWhat it does
NGINXmirror /mirror; and mirror_request_body on; (default on)Creates a background subrequest per request; responses to mirror subrequests are ignored
NGINXsplit_clients "${remote_addr}AAA" $variant { 5% new; * legacy; }Hashes the string to pick a variant by percentage
NGINXproxy_next_upstream error timeout http_502 http_503;Retry the other upstream on failure (only idempotent requests)
Envoyrequest_mirror_policies on a route or virtual hostMirrors to a cluster, with an optional runtime_fraction
Envoyruntime_fraction in a route matchMatches only the given percentage
IstioVirtualService http.route[].weightSplits traffic between destinations
Istiomirror and mirrorPercentageMirrors a percentage; absent means 100%
Argo Rolloutsstrategy.canary.steps with setWeight and pauseProgressive canary with analysis
Laravel PennantFeature::define, Lottery::odds, Feature::for($scope)Per-scope flags with percentage
Laravel HTTP clientHttp::timeout(2), Http::pool(...)Bounded shadow calls, concurrent calls
This chapter's facadePercent, Shadow, FallbackToLegacy, IgnoreFields, SetKillSwitchThe same ideas in 200 lines of Go

Status codes and errors you will see ​

WhereCode or messageMeaningAction
Facade to legacy502 Bad GatewayUpstream closed the connection or sent garbageCircuit breaker, alert
Facade to new503 Service UnavailableNew side is down or overloadedFallback to legacy for safe methods
Facade to either504 Gateway TimeoutUpstream too slowTune the proxy timeout under the client's
Decommissioned route410 GoneResource intentionally removedUpdate clients
Shadow requestX-Shadow: 1 (convention, not a standard)New side must not cause side effectsCheck it on every write path
PostgreSQLSQLSTATE 23505 unique_violationSecond write inserted a key that existsUse ON CONFLICT DO UPDATE
PostgreSQLSQLSTATE 40001 serialization_failureConcurrent transaction conflictRetry the whole transaction
PostgreSQLSQLSTATE 40P01 deadlock_detectedBackfill and live writes locked each otherSmaller batches, consistent order
Laravel HTTP clientConnectionExceptionTimeout or DNS failure on a shadow callCount as shadow error, never fail the user
Laravel HTTP clientRequestException (after ->throw())4xx or 5xx responseCompare status in the diff

Time budget of a shadowed request ​

SegmentTypical valueNote
Facade hop0.3 to 2 msOne extra proxy on the same network (estimate, measure yours)
Legacy handlingWhatever it wasUnchanged by design
Shadow callIn parallel or after the responseNever on the user's critical path
DiffMicroseconds to a millisecondJSON compare of a small body
Shadow load on newEqual to the mirrored share100% 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.

go
// 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.

go
// 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
}
go
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:

go
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:

go
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):

go
// 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 ​

CauseHow to see itFix
Timestamps and idsDiff names updated_at or a uuidAdd to IgnoreFields
Unordered listsSame elements, different orderSort by a key before comparing
Data not yet syncedDiff only on rows younger than the lagSkip rows newer than the lag
Real bug in newDiff is stable and reproducibleFix and re-shadow
Real bug in legacyLegacy is wrong, new is rightDecide explicitly; document the behaviour change
Non-deterministic endpointLegacy differs from itselfDiff legacy against legacy to measure the noise floor, subtract it

Dual-write drift ​

StepActionResult
1Make legacy the source of truth, write it firstOne truth
2Idempotent upsert on the new sideRetries are safe
3Record second-write failures in a repair tableNo silent loss
4Reconcile hourly; page on a non-zero diff above the thresholdDrift found by machines
5Prefer outbox or CDC for the new sideRemoves the second write from the request
sql
-- 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:

sql
-- 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):

sql
-- 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 ​

SymptomFix
New service queries legacy tables directlyReplace with a view, then with CDC into its own store
New service calls a legacy endpoint for core dataMove the data and the endpoint's logic; keep an anti-corruption layer for the rest
Shared libraries pull legacy classes inExtract a contract package; forbid imports from the legacy namespace in CI
Deploy of new requires deploy of legacyContract tests and versioned interfaces (API versioning)

The strangler stalls at 80% ​

CauseFix
The hard 20% is the oldest, most coupled codeDo the hard slice early, with the strongest team, rather than last
No deadlineDate per slice, tied to a visible cost (licence, hardware renewal)
Team moved onFund a dedicated deletion team; count deleted lines as output
New features keep landing on legacyRule: 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 ​

SituationRecommendationExtra techniqueReason
Read-only slice, easy to mirrorShadow first, then canary by percentageResponse diffingZero user risk during shadow
Slice with writes and moneyParallel run plus reconciliationIdempotency keys, ledger-style rowsDiffs are expected and must be explained
B2B product with few large tenantsTenant-based routingPer-tenant rollbackEasy to communicate and revert
Consumer product, millions of usersSticky percentage canaryStaff first, then 1%, 5%, 25%Statistical power, gradual
Inside one codebaseBranch by abstractionVerifying wrapper, flag per tenantNo network seam exists
Legacy is a database onlyView or CDC, then move writersTracer writeData seam before code seam
Legacy log is accessibleCDC (Debezium)Outbox for new eventsRemoves dual write from requests
Legacy log is not accessibleEvent interception at the facadeReconcile hourlyNext best
New and old share a UIUI compositionEdge includes or micro-frontendsScreens migrate with the backend
Small system, one team, few usersMaybe a rewrite is fineFeature freeze for weeks, not yearsThe pattern has overhead; do not use it for 5,000 lines
Deadline is a licence expiryStrangle with a hard date; consider a lift-and-shift firstReduce scopeThe date decides the order
Facade placementWhenTrade-off
Existing load balancer or ingressFast startLimited diff, rules in infra config
API gatewayYou already run oneAnother place for logic to creep in
Dedicated facade serviceNeed shadow, diff, custom rulesYou own and operate it
Service meshService-to-service slicesOnly inside the mesh
In the legacy appCannot place anything in frontCouples 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 hourly

Use 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 ​

ScaleFacadeShadowDataTeam
1x: one team, thousands of requests per dayAn NGINX location blockReplay a day of logs offlineDual write with an hourly reconcileOne owner per slice
10x: millions of requests per dayEnvoy or an API gateway with weightsLive mirror at 10%CDC (Debezium) plus backfillMigration squad
100x: tens of thousands of requests per secondEdge routing plus regional canaries, automated analysis (Argo Rollouts or Flagger)Sampled mirroring, diff in a stream jobCDC with schema registry, per-tenant cutoverPlatform 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 legacy

The 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/facade

Experiment 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 ignored

Experiment 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 ​

BeliefReality
"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 ​

TopicWhat to remember
PatternFacade in front, move slices, grow new, retire old
First stepPut the facade in with all rules saying legacy
SeamA place to cut without rewriting the inside: URL, queue, interface, table
RoutingPath, header, tenant, sticky percentage; log the reason
PercentageHash a stable key; raising the percent only adds users
ShadowMirror GET only; diff status and body; ignore noise; never sleep the user
Canary rampStaff, 1%, 5%, 25%, 50%, 100% with written exit criteria
Parallel runFor money: run both, reconcile, explain every diff
Dual writeTruth first, idempotent upsert second, repair queue, reconcile
CDCPrefer to dual write when the legacy log is readable
Data orderBackfill, sync, reconcile to zero, read from new write to both, write new, retire
Branch by abstractionInterface, two implementations, flag, delete
RollbackKill switch read at runtime, rehearsed, with a data plan
DoneLegacy code, routes, tables, jobs, credentials deleted
Metrics% traffic, % endpoints, % data, diff rate, lines deleted

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Strangler figGradual replacement of a system by growing a new one around it
FacadeThe front layer that intercepts and redirects requests
SeamA place where the system can be split without rewriting its inside
Intercept / redirectCatch a request and send it to another implementation
Branch by abstractionSwap an implementation behind an interface, in one codebase
Routing ruleA match (path, header, tenant, percent) and a target
Path-based routingRule on the URL prefix
Header-based routingRule on a request header, for opt-in
Percentage rolloutSending a stable share of users to the new side
CanaryA small first share of real traffic to the new version
Progressive deliveryAutomated stepwise ramp with analysis between steps
Feature flagA runtime switch controlling who runs which code
Kill switchA flag that forces everything to legacy at once
Shadow trafficMirrored copies of requests whose answers are dropped after comparison
Dark launchRunning new code on real traffic without users seeing its output
Response diffingComparing status and body of old and new answers
Parallel runRunning both for real work and reconciling results
ReconciliationAutomated comparison of two datasets
CutoverThe moment the new system takes 100%
DecommissionDeleting the legacy system completely
Dual writeApplication writes the same fact to two stores
Change data captureReading a database's change log and applying it elsewhere
Event interceptionPublishing an event for each routed call
Database viewA named query that can hide which table is behind it
SynonymAn alias to a table or view in another schema or database (SQL Server, Oracle)
Expand/contractAdd new schema, migrate, remove old schema in separate steps
BackfillCopying historical data to the new store
Read from new write to bothThe phase where reads switch while writes still go to both
Anti-corruption layerA translator that keeps legacy concepts out of the new model
Micro-frontendA separately deployed piece of a web page
UI compositionAssembling a page from fragments of different systems
Contract testA test that the interface shape is honoured
Traffic replayRe-sending recorded requests to a test system
Rollback planWritten triggers and actions to undo each step
Big-bang rewriteReplacing everything at once
Legacy dependencyThe new system relying on legacy data or code
Migration metrics% traffic, % endpoints, % data, diff rate, code deleted
PennantLaravel's feature flag package
Http::poolLaravel HTTP client method for concurrent requests
Monolith to MicroservicesSam Newman's book of migration patterns
Uber DOMADomain-Oriented Microservice Architecture

References ​

Built by Morteza Negahi