Skip to content

Lesson 14 of 15 · Applying It to Real Projects

The Strangler Fig Pattern

Advanced•
lesson•
November 16, 2026•
~9 min read

The codebase that needs to keep running

You have a 10-year-old PHP codebase. An old framework version. A 2,000-line application_controller.php. The team can't ship features without breaking something. Management wants a "rewrite". The senior engineers who've been there know the rewrite will probably fail (Joel Spolsky wrote about why in 2000, in "Things You Should Never Do, Part I", and the lesson still applies).

The previous lesson made the case for incremental in-place migration: new features in the new shape, touched code cleaned up, strategic refactors as scoped projects. That works when the old code is shaped close enough to the target. Sometimes the old structure can't be incrementally cleaned into the new structure; the parallel form has to exist temporarily, and traffic has to move from one to the other.

Where the name comes from

Martin Fowler named the pattern after the strangler fig tree. His post was originally titled "Strangler Application". The fig grows around an existing tree, gradually replacing it. In Fowler's words, "its original host tree may die leaving the fig as an echo of its shape."

Applied to software: build new functionality alongside the old, behind some routing or abstraction layer. Gradually shift traffic from old to new. Once everything's migrated, the old code is dead and removable.

Why it works

Three things make the strangler fig more reliable than a full rewrite:

  • The old system keeps running. No "rewrite freeze", no moratorium on features. Customers don't notice the migration happening underneath them.

  • Each step is small. One feature, one route, or one operation moves at a time. The blast radius of any mistake is one piece.

  • Every step is reversible. If the new version doesn't work in production, route back to the old. The cost of rolling back is a flag flip.

The full-rewrite alternative breaks all three: the old system is frozen, the migration is one big bang, and "rolling back" usually means "shipping the old thing as-is and pretending the rewrite never happened".

A worked example

A legacy Laravel app. 50 routes in web.php, all going to LegacyController::method(). The team picks the reservation request flow as the first thing to migrate.

Step 1. Build the new Hearth/Booking/RequestReservation/ slice in the new architecture: Vertical Slice Architecture, commands, handlers, repositories. Tests pass against the new slice in isolation.

Step 2. Add a feature flag. Behind the flag, the request goes to the new slice. By default, traffic still goes to the old controller.

The files the switch touches, old and new:

TEXT
routes/ └── web.php # POST /reservations app/ # legacy, App\ ├── Http/Controllers/ │ ├── LegacyController.php # old path │ └── RequestReservationSwitch.php # picks old or new └── Support/ └── FeatureFlags.php Hearth/Booking/RequestReservation/ # step 1, Hearth\ ├── RequestReservationController.php # new path └── RequestReservationRequest.php

The route file points at one class that makes the decision. The legacy app keeps Laravel's App\ namespace in app/, so the switch lives there, and the new slice lives in Hearth\. Route files may use facades; the switch itself is a plain class that gets its collaborators through the constructor:

PHP
<?php declare(strict_types=1); use App\Http\Controllers\RequestReservationSwitch; use Illuminate\Support\Facades\Route; Route::post('/reservations', RequestReservationSwitch::class);

Two more files make up the switch. First, the flag service the app already has, reduced to the one method the switch needs:

PHP
<?php declare(strict_types=1); namespace App\Support; use Illuminate\Contracts\Auth\Authenticatable; interface FeatureFlags { public function isEnabled(string $flag, ?Authenticatable $user): bool; }

Second, the switch. RequestReservationController is the new slice's controller from Step 1. LegacyController is the old one:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Support\FeatureFlags; use Hearth\Booking\RequestReservation\RequestReservationController; use Hearth\Booking\RequestReservation\RequestReservationRequest; use Illuminate\Contracts\Container\Container; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; final readonly class RequestReservationSwitch { public function __construct( private Container $container, private FeatureFlags $features, private RequestReservationController $newController, private LegacyController $legacyController, ) {} public function __invoke(Request $request): Response { if ($this->features->isEnabled('request-reservation-v2', $request->user())) { return ($this->newController)($this->container->make(RequestReservationRequest::class)); } return $this->legacyController->requestReservation($request); } }

Asking the container for RequestReservationRequest makes Laravel fill it from the current request and validate it (that is what FormRequestServiceProvider does after resolving). The legacy path keeps its old validation, and only flagged users see the new rules.

Step 3. Roll the flag out to 1% of traffic. Watch error rates. Compare the new path's results with what the old path produces for the same input, so differences show up before the flag reaches everyone.

Step 4. Increase to 10%, 50%, 100%. Each step is a real-world A/B between old and new. Each step is reversible.

Step 5. Once 100% of traffic is on the new slice and stable, remove the legacy code path. The old requestReservation method gets deleted. The route file simplifies.

Step 6. Delete dead code. Anything that was only called by the old requestReservation method is now dead, and gets removed too.

Repeat for the next operation.

The routing layer

Something has to decide "old or new" for each request. Three places this decision can live:

  • Application-level routing. A middleware or route group inside the existing Laravel app picks the version. Cheapest. Works inside one codebase.

  • Reverse proxy. NGINX, AWS ALB, Cloudflare. Routes URLs to different backends. More flexible, more infrastructure. Useful when you're splitting an app across processes.

  • API gateway. Kong, Tyk, AWS API Gateway. Same idea with more features (rate limiting, auth, transformation). Useful when you're heading toward microservices.

For most strangler-fig migrations within a single Laravel app, the application-level approach with a feature flag is enough. The reverse proxy and gateway versions earn their place when the migration spans multiple deployable units.

Branch by abstraction

A complementary technique inside the codebase. When the migration crosses a class boundary rather than a route boundary, the strangler shape becomes:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Reservation; use Hearth\Booking\DateRange; use Hearth\Booking\RoomId; interface Reservations { public function withId(ReservationId $id): Reservation; public function save(Reservation $reservation): void; /** @return list<Reservation> */ public function overlapping(RoomId $roomId, DateRange $stayDates): array; }

Two files implement it. EloquentReservations is the adapter built earlier in this course. The legacy adapter translates the old codebase's data into the same Reservation class:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Infrastructure; use Hearth\Booking\DateRange; use Hearth\Booking\Reservation\Reservation; use Hearth\Booking\Reservation\ReservationId; use Hearth\Booking\Reservation\Reservations; use Hearth\Booking\RoomId; use LogicException; final readonly class LegacyReservations implements Reservations { public function withId(ReservationId $id): Reservation { throw new LogicException('Read the old tables and build a Reservation here.'); } public function save(Reservation $reservation): void { throw new LogicException('Write back through the old code here.'); } public function overlapping(RoomId $roomId, DateRange $stayDates): array { throw new LogicException('Query the old tables here.'); } }

The rest of the system depends on Reservations. The container picks which implementation to bind based on a flag, an environment, or a per-tenant rule. Migration becomes a binding change, with the same gradual rollout shape.

This is the dependency-injection shape, used as a migration tool. The decorator and strategy patterns are nearby; you can also wrap the legacy implementation with a decorator that gradually delegates more behavior to the new one.

What strangling looks like over time

The arc for a real legacy product:

  • Stage 1. New features land in the new architecture only. The previous lesson's "first slice" advice. The legacy codebase stops growing.

  • Stage 2. Build new versions of the most-painful old operations. Strangle them in behind flags. Each operation is its own migration.

  • Stage 3. Move legacy controllers and models into a Legacy/ folder, visually marking what's left. New module folders (Hearth/Booking/, Hearth/Pricing/, Hearth/Housekeeping/, Hearth/Payments/) accumulate.

  • Stage 4. Major modules become bounded contexts, each with its own model and its own meaning for shared words. Cross-module imports get caught by tooling. The Legacy/ folder shrinks.

  • Stage 5. Eventually, Legacy/ is empty - or contains only stable, never-changing code that doesn't justify migration.

Strangling at the data layer

The hardest part of many strangler-fig migrations isn't the code; it's the database. Three patterns that help:

Dual-write. New code writes to both the old schema and the new schema during migration. Old code reads from the old. Once new code is dominant, switch reads to the new schema and stop dual-writing. The window is uncomfortable; the upside is no big migration cutover.

Read-from-new, fall-back-to-old. New code tries the new schema first; if not found, queries the old. A backfill job runs in the background or lazily on read. The new schema fills up over time; the old eventually goes cold.

Anti-corruption layer at the data boundary. The new domain code sees a clean view; the legacy schema lives behind a translator, called an anti-corruption layer. The schema can stay terrible without contaminating the new model. This is sometimes the right answer if the legacy schema can't be replaced for political or technical reasons.

When to strangle vs migrate in place

  • Strangle when the old code is too coupled or too foreign-shaped for incremental cleanup to reach it; or when the architectural shift (new routing, new schemas, new boundaries) requires parallel structures temporarily.

  • Migrate in place when the old code is shaped close enough to the target that Boy Scout improvements and small refactors can move it.

Real codebases often use a mix. Some areas get strangled (the worst ones). Others get incrementally cleaned (the close-enough ones). The team picks per area.

Risks

  • Two systems for too long. If the migration stalls, you're maintaining old and new indefinitely. The cost compounds. Either finish the migration or roll back; don't drift.

  • Behavioral drift. The new system behaves almost like the old, but not quite. Edge cases differ. The differences ship as bugs. Mitigate with shadow testing: run both paths on the same request and compare the results, as in step 3.

  • Test gap. Legacy code often has thin testing. Building the new without thorough characterization tests means migrating toward a different system.

  • Political fatigue. The team gets bored. The original roadmap stops being followed. The codebase ends up half-strangled, which is worse than either pure version. Mitigate with visible metrics (lines of code in Legacy/, percentage of routes on the new path).

Pitfalls

Strangling without feature flags. No rollback path. The first error in production is a real outage instead of a flag flip.

Big-bang strangling. A single PR that moves an entire module to the new architecture defeats the whole pattern. The strangler is gradual; each piece is small.

Forgetting to delete the old code. The strangler's whole point is the removal. If the old code lingers "just in case" forever, the migration isn't done. Delete dead branches as soon as the new path is stable.

Using the strangler as cover for unrelated rewrites. "While we're migrating reservation requests, let's also redesign the booking funnel UI." Scope creep. Keep migrations narrow; redesigns are separate projects.

Strangling the wrong things first. Stable, working, ugly code that nobody touches isn't worth strangling. Pick the painful, frequently-changed parts. The previous lesson's "what to migrate first" advice applies here too.

The one thing to remember

The Strangler Fig Pattern lets you replace a legacy system without ever stopping it. New code grows around the old. Traffic shifts gradually behind a feature flag or routing layer. The old becomes dead and removable.

Course Content