Strangler Fig Migration: Incremental Legacy Replacement
Replace a legacy system incrementally via the strangler fig pattern: routing, shadow traffic, feature flags, data sync, rollback, and a migration playbook.
Introduction
Martin Fowler named the pattern after the strangler fig, a vine that germinates in the canopy of a host tree, grows downward, and eventually replaces the tree entirely. The migration strategy works the same way: you build the new system around the legacy one, divert traffic piece by piece through a routing layer, and decommission the old system only when nothing depends on it.
It exists because big-bang rewrites keep failing in predictable ways. The rewrite takes twice the estimated time, the legacy system keeps accumulating features the rewrite must chase, and cutover day becomes an all-or-nothing bet on untested code. The strangler fig trades that single enormous risk for a long series of small, reversible ones.
This guide covers the production mechanics: the routing layer, shadow traffic, feature-flag-driven rollout, data synchronization between old and new, automatic rollback, and a phase-by-phase playbook with exit criteria. If you’re still deciding whether to decompose and which strategy to pick, start with the monolith to microservices migration guide and come back here for the implementation detail.
When to Use — and When Not To
The strangler fig is the default answer for replacing a system you can’t afford to stop, but it isn’t free. You pay for coexistence: two systems running in parallel, a routing layer to maintain, and data kept in sync for months.
Use it when:
- The legacy system is large enough that a rewrite would take more than a few months — anything longer and the “big-bang” plan is a bet you will lose.
- You can’t freeze feature development. Strangling lets product work continue in the new system while migration proceeds.
- The legacy system must stay available throughout — there’s no maintenance window for a cutover.
- You need real production traffic to validate the new system, not just test suites.
Don’t use it when:
- The legacy system is small. A focused rewrite of a few thousand lines is faster than building a routing layer and running two systems for a year.
- You can’t put anything in front of the monolith. If requests reach the legacy system through paths you can’t intercept (direct socket connections, embedded clients, batch jobs), there’s no seam to route through.
- The two systems can’t share or synchronize data. If the new system needs state the legacy system can’t emit, strangler turns into a data-migration project with extra steps.
- You want a modular monolith, not services. If the goal is internal structure rather than independent deployment, the modular monolith approach gets there with far less machinery.
| Approach | Risk profile | Cost | Best for |
|---|---|---|---|
| Big-bang rewrite | Single huge cutover risk | One system at a time | Small apps, greenfield-era code |
| Strangler fig | Many small reversible risks | Two systems + routing layer | Large monoliths, no freeze possible |
| Modular monolith first | Low — no distribution | Refactoring only | When services aren’t the goal |
How It Works
A routing layer sits in front of both systems. Every request hits the router, which consults migration rules — path, method, feature flag, traffic percentage — and forwards to legacy or new. The client never knows the difference.
Migration is a ramp, not a switch:
- Shadow: new system receives copied traffic; its responses are compared but never returned to clients.
- Canary: a small percentage (1–5%) gets real responses from the new system.
- Ramp: 10% → 25% → 50% → 90%, with monitoring gates between steps.
- Cutover: 100% to new; legacy stays warm for rollback.
- Decommission: after a stability window, the legacy path is removed.
Choosing the First Extraction
The first slice sets the pattern for everything after it. Pick wrong and you either migrate a trivial leaf nobody cares about — or you drown in the most entangled domain first.
Good first candidates share four traits:
- Read-heavy over write-heavy. Reads have no side effects, can be shadow-tested safely, and rollback is free. Save write paths for later phases when synchronization is proven.
- Loosely coupled. Look for domains with few foreign keys into the rest of the monolith and few other modules calling into them. An endpoint the rest of the monolith calls internally is a bad first choice — you can’t intercept calls that never cross the routing layer.
- Visible but not critical. Enough traffic to produce meaningful comparison data, not so critical that an early mistake ruins the quarter. Authentication and payments wait; profile pages and search are good starters.
- Independently deployable data. The extracted slice needs its own data store (or a clean synchronized view of the shared one). If its tables are JOINed with everything, extract read models first and deal with ownership later.
The Routing Layer
Two places to route: the edge (API gateway, load balancer, reverse proxy) or inside the application (a router module in front of both systems).
Edge routing is simpler to reason about — no code to maintain, rules live in config — but coarser: you route by path and method, nothing more. It fits when extraction boundaries map cleanly to URL prefixes.
# Kong / NGINX / API Gateway configuration
# Route specific endpoints to the new system
routes:
- name: user-service-new
paths:
- /api/v2/users
upstream: new-user-service:3000
strip_path: false
- name: legacy-system
paths:
- /api
upstream: legacy-monolith:8080
strip_path: false
More gateway options and resilience patterns are covered in the API gateway design guide.
Application-level routing costs a module you own, but it can route on anything: headers, user IDs, tenant, A/B cohort — which is what makes percentage-based and per-user rollout possible. This is the version most teams end up needing:
// router/StranglerRouter.ts — Route requests between legacy and new systems
interface SystemAdapter {
handle(request: HttpRequest): Promise<HttpResponse>;
}
class StranglerRouter {
constructor(
private readonly legacySystem: SystemAdapter,
private readonly newSystem: SystemAdapter,
private readonly routingRules: RoutingRule[],
private readonly featureFlags: FeatureFlagService,
) {}
async route(request: HttpRequest): Promise<HttpResponse> {
const rule = this.matchRule(request);
if (!rule) {
// No matching rule — route to legacy
return this.legacySystem.handle(request);
}
// Check feature flag for gradual rollout
const useNewSystem = await this.featureFlags.isEnabled(
rule.flagName,
{ userId: request.headers['x-user-id'] },
);
if (useNewSystem) {
try {
return await this.newSystem.handle(request);
} catch (error) {
// Fallback to legacy on new system failure
console.error('New system failed, falling back to legacy:', error);
return this.legacySystem.handle(request);
}
}
return this.legacySystem.handle(request);
}
private matchRule(request: HttpRequest): RoutingRule | null {
for (const rule of this.routingRules) {
if (this.matches(request, rule)) {
return rule;
}
}
return null;
}
private matches(request: HttpRequest, rule: RoutingRule): boolean {
if (rule.path && !request.path.match(rule.path)) return false;
if (rule.method && request.method !== rule.method) return false;
return true;
}
}
interface RoutingRule {
path?: RegExp;
method?: string;
flagName: string;
}
Two details here save real incidents. First, isEnabled is async — forgetting the await leaves you comparing a Promise, which is always truthy, which silently routes 100% of matching traffic to the new system. Second, the try/catch fallback means a new-system outage degrades to legacy instead of erroring — but log every fallback, because silent fallback also hides regressions during canary.
Shadow Traffic (Dark Launch)
Before the new system serves anyone, it should prove it could. Shadow traffic sends each request to both systems; the legacy response goes to the client, and the new system’s response is logged and compared. Users see zero risk; you get production-grade comparison data.
// router/ShadowTraffic.ts — Send traffic to both systems, compare results
class ShadowTraffic {
constructor(
private readonly legacySystem: SystemAdapter,
private readonly newSystem: SystemAdapter,
private readonly comparisonLogger: ComparisonLogger,
) {}
async route(request: HttpRequest): Promise<HttpResponse> {
// Send to both systems in parallel
const [legacyResponse, newResponse] = await Promise.allSettled([
this.legacySystem.handle(request),
this.newSystem.handle(request),
]);
// Return legacy response to client
if (legacyResponse.status === 'fulfilled') {
// Log comparison for analysis
this.comparisonLogger.log({
path: request.path,
method: request.method,
legacyStatus: legacyResponse.value.status,
newStatus: newResponse.status === 'fulfilled'
? newResponse.value.status
: 'error',
legacyTime: legacyResponse.value.responseTime,
newTime: newResponse.status === 'fulfilled'
? newResponse.value.responseTime
: null,
match: this.responsesMatch(
legacyResponse.value,
newResponse.status === 'fulfilled' ? newResponse.value : null,
),
});
return legacyResponse.value;
}
throw new Error('Legacy system failed');
}
private responsesMatch(legacy: HttpResponse, newResp: HttpResponse | null): boolean {
if (!newResp) return false;
if (legacy.status !== newResp.status) return false;
// Compare normalized key fields — full-body equality fails on
// timestamps, generated IDs, and field ordering.
const legacyKey = { id: legacy.body.id, total: legacy.body.total, status: legacy.body.status };
const newKey = { id: newResp.body.id, total: newResp.body.total, status: newResp.body.status };
return JSON.stringify(legacyKey) === JSON.stringify(newKey);
}
}
Shadow traffic doubles the load on the compared path, so enable it per-route during off-peak first. And don’t compare raw bodies — timestamps and generated IDs guarantee false mismatches that drown the real ones. Compare the fields the client contract actually promises.
Feature Flags for Rollout
Flags turn the migration into a dial instead of a switch: percentage rollouts, per-user targeting (internal users first, then beta opt-ins, then everyone), and instant off when something breaks.
// flags/FeatureFlagService.ts — Control migration rollout
class FeatureFlagService {
constructor(private readonly flagStore: FlagStore) {}
async isEnabled(flagName: string, context: FlagContext): Promise<boolean> {
const flag = await this.flagStore.get(flagName);
if (!flag) return false;
switch (flag.rolloutStrategy) {
case 'percentage':
return this.percentageRollout(flag, context);
case 'user-list':
return flag.userIds?.includes(context.userId) ?? false;
case 'environment':
return flag.environments?.includes(context.environment) ?? false;
case 'boolean':
return flag.enabled ?? false;
default:
return false;
}
}
private percentageRollout(flag: Flag, context: FlagContext): boolean {
const hash = this.hashString(context.userId || flag.name);
const bucket = hash % 100;
return bucket < flag.percentage;
}
private hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return Math.abs(hash);
}
}
// Migration rollout config
const migrationFlags = {
'use-new-user-service': {
enabled: true,
rolloutStrategy: 'percentage',
percentage: 5, // Start with 5% of users
},
'use-new-order-service': {
enabled: true,
rolloutStrategy: 'user-list',
userIds: ['test-user-1', 'test-user-2'],
},
'use-new-billing-service': {
enabled: false,
rolloutStrategy: 'boolean',
},
};
The ?. guards matter: a flag configured for percentage doesn’t carry userIds, and evaluating the wrong field crashes the router at request time. The bucketing hash is deliberately stable — the same user must land in the same bucket on every request, or a single user sees inconsistent behavior across a session.
For anything beyond a handful of flags, use a managed service (LaunchDarkly, Unleash, Flagsmith) — you get dashboards, audit logs, and kill switches without maintaining flag infrastructure mid-migration. The feature flags guide covers provider trade-offs in depth.
Data Synchronization
This is the part teams underestimate. Routing traffic is easy; keeping two data stores consistent for months isn’t. Two patterns dominate, and the right choice depends on whether you can touch the legacy write path.
| CDC (Change Data Capture) | Dual-write | |
|---|---|---|
| How | Read the legacy DB’s transaction log (Debezium, AWS DMS), replay changes into the new store | Application writes to both systems on every mutation |
| Legacy changes needed | None | Modify every write path |
| Failure mode | Replication lag — new system reads stale data | Partial failure — one write succeeds, one doesn’t |
| Best for | Black-box legacy, many writers, can’t modify code | You own the app and can wrap its repositories |
CDC is non-invasive: the legacy application never knows it’s being mirrored. Tools like Debezium stream insert/update/delete events you transform into the new schema:
# sync/cdc_sync.py — Sync data between legacy and new system databases
import json
from kafka import KafkaConsumer
def sync_user_to_new_system(user_data):
"""Transform legacy user schema to new system schema."""
new_user = {
'id': user_data['user_id'],
'email': user_data['email_address'],
'firstName': user_data['fname'],
'lastName': user_data['lname'],
'createdAt': user_data['created_timestamp'],
'status': 'active' if user_data['is_active'] == 1 else 'inactive',
}
new_system_client.upsert_user(new_user)
def delete_user_from_new_system(user_id):
new_system_client.delete_user(user_id)
consumer = KafkaConsumer(
'legacy-db-changes',
bootstrap_servers=['kafka:9092'],
value_deserializer=lambda m: json.loads(m.decode('utf-8')),
)
# new_system_client is your new store's client — initialized at startup.
for message in consumer:
change = message.value
table = change['table']
operation = change['op'] # insert, update, delete
if table == 'users':
if operation in ('insert', 'update'):
sync_user_to_new_system(change['after'])
elif operation == 'delete':
delete_user_from_new_system(change['before']['id'])
Function definitions come before the consume loop — calling sync_user_to_new_system before its def executes raises NameError, which is exactly what happens when this ordering is inverted.
Dual-write is immediate — no replication lag — but requires modifying the application, and partial failure is the default hazard: if the second write fails, the systems drift. Write to the new system first (it’s the future source of truth) and treat legacy-write failure as retryable, not fatal:
// sync/DualWriter.ts — Write to both systems during migration
class DualWriter {
constructor(
private readonly legacyRepo: LegacyRepository,
private readonly newRepo: NewRepository,
private readonly syncMode: 'dual-write' | 'new-only' | 'legacy-only',
) {}
async saveUser(userData: UserData): Promise<void> {
switch (this.syncMode) {
case 'dual-write':
// Write to both — new system is source of truth eventually
await this.newRepo.saveUser(userData);
try {
await this.legacyRepo.saveUser(userData);
} catch (error) {
// Non-blocking — but queue it for reconciliation, don't just log it
console.error('Legacy write failed (non-blocking):', error);
await this.retryQueue.enqueue('legacy-write', userData);
}
break;
case 'new-only':
await this.newRepo.saveUser(userData);
break;
case 'legacy-only':
await this.legacyRepo.saveUser(userData);
break;
}
}
}
// Migration phases:
// Phase 1: legacy-only (before migration starts)
// Phase 2: dual-write (both systems receive writes)
// Phase 3: new-only (legacy is read-only, then decommissioned)
Whichever you choose, run a nightly reconciliation job that samples rows from both stores and diffs them. Drift isn’t a question of if but of how much — the job tells you how much, and whether it’s growing. See the CDC pattern reference for the full event-pipeline variant.
Rollback Strategy
Rollback in a strangler migration should be boring: flip the flag, traffic returns to legacy, done. The hard part is deciding when to pull it — which is why you automate the threshold instead of debating it at 3 a.m.
// router/RollbackManager.ts — Instant rollback to legacy
class RollbackManager {
constructor(
private readonly flagStore: FlagStore,
private readonly alerting: AlertingService,
) {}
async rollback(flagName: string, reason: string): Promise<void> {
await this.flagStore.update(flagName, {
enabled: false,
percentage: 0,
});
await this.alerting.notify({
severity: 'critical',
message: `Rolled back ${flagName}: ${reason}`,
channel: '#migration-alerts',
});
}
// Automatic rollback based on error rate
async monitor(flagName: string, metrics: MetricsCollector): Promise<void> {
const window = { windowSeconds: 60 };
const errorRate = await metrics.getErrorRate(flagName, window);
const p99Latency = await metrics.getP99Latency(flagName, window);
if (errorRate > 0.05) { // 5% error rate threshold
await this.rollback(flagName, `Error rate ${errorRate} exceeded 5%`);
} else if (p99Latency > 2000) { // 2s p99 latency threshold
await this.rollback(flagName, `P99 latency ${p99Latency}ms exceeded 2000ms`);
}
}
}
Two rules keep rollback honest. Thresholds before launch: pick error-rate and latency numbers while you’re calm — 5% errors or 2s p99 are sane defaults, tuned per endpoint. Rollback must be tested: run a deliberate rollback during shadow phase, because a rollback path you’ve never exercised is a hypothesis, not a mechanism. One caveat — rollback works while legacy still owns the data; once dual-write flips to new-only and legacy is decommissioned, there’s no legacy to roll back to. That’s why the checklist keeps legacy warm for weeks after cutover.
A Worked Example
Extracting a users domain from a monolith, end to end:
- Week 1–2 — Prep: inventory the monolith’s
/api/users/*endpoints and tables. Stand up the new user service with its own database. Deploy the gateway rule (still routing 100% to legacy) and the shadow-traffic path. - Week 3 — Shadow: enable shadow on
GET /api/users/:id. Comparison logs show a 2% mismatch — the new service serializesnullavatars as"". Fix, re-shadow, mismatches drop to noise level. - Week 4 — CDC: enable Debezium on the
userstable; the new store replays ~18 hours of history, then keeps up with ~200ms lag. Reconciliation job confirms parity within 0.01%. - Week 5 — Canary: flag
use-new-user-serviceto 5% of users. Error rate 0.02%, p99 140ms vs legacy 180ms — under thresholds. Ramp 25% → 50% over the week. - Week 6 — Cutover: 100% reads on the new service. Dual-write turns on for
POST /api/users— writes go to new first, replay to legacy. - Week 8 — Decommission: two clean weeks, reconciliation still flat, legacy
/usershandlers removed. The monolith just got smaller.
Nine weeks for one domain — which sounds slow until you compare it with the big-bang rewrite still “three months away” after a year.
Migration Checklist
Phase 1: Preparation
□ Audit legacy system endpoints and data models
□ Identify migration boundaries (which features to extract first)
□ Set up routing layer (API gateway or application router)
□ Set up feature flag service
□ Set up monitoring and comparison logging
□ Set up data synchronization (CDC or dual-write)
Phase 2: Shadow Launch
□ Deploy new system alongside legacy
□ Route traffic to both, compare results
□ Verify data consistency
□ Fix discrepancies found in shadow traffic
→ Exit: mismatch rate at noise level for 1+ week
Phase 3: Canary Release
□ Route 5% of traffic to new system
□ Monitor error rates, latency, and business metrics
□ Gradually increase to 10%, 25%, 50%
→ Exit: metrics within thresholds at 50% for 1+ week
Phase 4: Full Cutover
□ Route 100% of traffic to new system
□ Enable dual-write if writes are migrating too
□ Keep legacy on standby for 1-2 weeks
→ Exit: zero incidents requiring rollback
Phase 5: Decommission
□ Stop writing to legacy database
□ Archive legacy data
□ Shut down legacy infrastructure
□ Remove routing rules for legacy
Best Practices
-
For a deeper guide, see API Gateway Design: Resilience, Routing, and Security.
-
Start with read-only endpoints — lower risk than writes, easier to compare
-
Use shadow traffic before canary — validate the new system without affecting users
-
Set automatic rollback thresholds — error rate, latency, business metric drops
-
Keep the routing layer simple — complexity here blocks the entire migration
-
Migrate one domain at a time — don’t split across multiple domains simultaneously
-
Maintain data consistency — use CDC or dual-write, verify with reconciliation jobs
-
Monitor business metrics, not just technical ones — revenue, conversion rate, order count
-
Keep the legacy system running during migration — rollback needs it available
-
Document the migration state — which endpoints are on which system, what percentage
-
Communicate with stakeholders — migration status, risks, and timeline
Common Mistakes
- Migrating writes before reads: writes have side effects and are harder to roll back. Start with reads.
- No shadow traffic phase: going straight to canary misses data consistency issues.
- No automatic rollback: manual rollback takes too long during an incident. Set thresholds.
- Migrating too many features at once: one failure rolls back everything. Migrate incrementally.
- No data reconciliation: dual-write or CDC can drift. Run periodic consistency checks.
- Decommissioning legacy too early: keep it running for at least 1-2 weeks after full cutover.
- Forgetting non-HTTP traffic: cron jobs, queue consumers, and WebSocket connections bypass the routing layer entirely. Inventory them in Phase 1 or they keep hammering the legacy system after “cutover”.
Further Reading
- StranglerFigApplication — Martin Fowler — the original 2004 article that named the pattern
- Strangler fig pattern — AWS Prescriptive Guidance — cloud-side implementation and phased approach
- Debezium documentation — the standard open-source CDC engine for the data-sync phase
- Unleash documentation — open-source feature flag management for rollout control
See Also
- Monolith to Microservices — Migration Strategies — choosing between strangler fig, branch by abstraction, and parallel run
- API Gateway Design: Resilience, Routing, and Security — the routing layer in depth
- Feature Flags Guide — rollout mechanics and provider trade-offs
- Strangler Fig Pattern — the pattern-format reference
- CDC Pattern — event-driven data synchronization
- Runnable companion — the router, flags, CDC and dual-write code from this guide
Frequently Asked Questions
What is the strangler fig pattern?
An incremental migration strategy where a routing layer directs traffic between a legacy system and a new system. New functionality is built in the new system while old functionality is migrated piece by piece. The legacy system is gradually "strangled" until all traffic routes to the new system.
What is shadow traffic?
Sending the same request to both legacy and new systems in parallel. The legacy response is returned to the client. The new system response is compared against the legacy response for correctness. This validates the new system without affecting users.
What is dual-write?
Writing data to both legacy and new databases during migration. This keeps both systems in sync. The migration progresses from legacy-only to dual-write to new-only. Dual-write adds latency and requires handling partial failures.
When should I use CDC vs dual-write?
Use CDC when you can't modify the legacy application's write path — it reads the database transaction log, so the app never knows. Use dual-write when you control the application and can write to both systems simultaneously. CDC is non-invasive but adds replication lag. Dual-write is immediate but requires application changes and handling partial failures.
Can I use the strangler fig pattern without microservices?
Yes. The pattern routes between two systems, whatever they're — old monolith to new monolith, legacy app to SaaS, v1 API to v2 API. Microservices are the common destination, not a requirement.
How long should the migration take?
Depends on system complexity. A small service might take weeks. A large monolith might take months or years — the worked example above shows ~9 weeks for a single well-scoped domain. The key is incremental progress: each migrated endpoint reduces the legacy system's surface area, so even a slow migration beats a rewrite that never ships.
Related Resources
Monolith to Microservices — Migration Strategies
A practical guide to decomposing monoliths: strangler fig, branch by abstraction, and incremental extraction patterns that reduce risk and preserve business continuity.
GuideModular Monolith: Module Boundaries, Shared Kernel
Design a modular monolith with clear module boundaries, a shared kernel, dependency rules, and a migration path to microservices when scale demands it.
GuideAPI Gateway Design: Resilience, Routing, and Security
A practical guide to designing API gateways: routing, authentication, rate limiting, circuit breakers, caching, and deployment patterns for resilient APIs.
GuideFeature Flags: Progressive Release and Safe Experimentation
A practical guide to feature flags: implementation patterns, progressive rollouts, kill switches, A/B testing, and managing flag lifecycle at scale.
PatternStrangler Fig: Gradually Replace Legacy by Intercepting
How to gradually replace a legacy system by intercepting routes and routing traffic to new services. Covers strangler fig, incremental migration, and cutover.
PatternCDC Pattern: Stream Database Changes to Downstream
How to stream database changes to downstream consumers with CDC. Covers log-based CDC, Debezium, Kafka Connect, outbox pattern, and consumer reconciliation.