Strangler fig pattern for replacing legacy behind a seam
The strangler fig pattern replaces legacy code route by route. A shadow run found 31 mismatches in 1,000 generated policies before any caller saw one.
Thirty-one of 1,000 policies came back different when a new reader ran beside the old system, all in one
field. The old system stores "no renewal date" as the string 00000000, which appears in no specification,
and the replacement parsed it into the date 0001-01-01. Those figures come from the sample code in this
post, run on generated insurance policies with that bug planted in the replacement. No caller saw any of the
31, because the legacy answer was the one returned.
Old systems accumulate rules like this, known only to the code that implements them, and that is why replacing a working system all at once goes badly so often. Martin Fowler's Strangler Fig article names the reasons: a serious system takes a long time to replace, users will not wait for features in the meantime, and existing behavior is hard to specify. Its alternative takes the name from a vine he saw in Queensland, which grows around a host tree and eventually stands in its shape. New code grows around the old system and takes over behavior piece by piece, while the old system keeps running.
One route through a strangler fig migration
-
Seam in place
Legacy 100%Every call passes the seam and still reaches legacy. Nothing changes for callers.
Rollback: Remove the seam.
-
Shadow reads
Legacy 100%New code also runs, and its answers are compared and logged. Legacy's answer is returned.
Rollback: Turn the comparison off.
-
Route a cohort
Legacy 75% New 25%A stable hash sends the same policy to the same side on every call.
Rollback: Set the percentage to 0 for reads. Writes need a sync path back.
-
Retire legacy
New 100%Legacy has no callers left. Delete it, then delete the seam.
Rollback: None. This step is deliberate and last.
A seam is a point where you can change which code answers without changing the caller. Two locations are common, and most migrations use both.
The edge seam is a proxy in front of the system. Microsoft's Strangler Fig guidance
describes this facade routing each request to the legacy application or the new services, so clients keep one
interface and need not know a migration is happening. It suits whole routes, such as moving
GET /policies/{id} before anything else:
// The edge facade: the only code that knows two systems exist.
app.MapGet("/policies/{id}", async (string id, CancellationToken ct) =>
{
var policy = rollout.UseReplacement(id)
? await replacementClient.FindAsync(id, ct)
: await legacyClient.FindAsync(id, ct);
return policy is null ? Results.NotFound() : Results.Ok(policy);
});The same guidance warns that the facade must not become a single point of failure or a performance bottleneck, and it says the pattern does not fit when requests to the back end cannot be intercepted.
The in-process seam is what Fowler calls branch by abstraction: introduce an abstraction over the thing being replaced, move callers onto it, build the replacement behind it, then switch. It suits logic buried inside the monolith that has no URL of its own. At either seam, keep the routing decision out of business code, so that deleting the migration later touches only scaffolding.
If you are working in code without tests, write characterization tests around the behavior before moving callers onto the seam. Making the seam itself should change nothing, and those tests are how you know it did not.
The fastest way to lose the benefit of a replacement is to let it speak the old system's language. If new code
checks STAT_CD == "L", you have rebuilt the old model in a new repository, and it will outlive the migration.
An anti-corruption layer, a term from Eric Evans's Domain-Driven Design, is the translator that prevents this. Calls on the new system's side use its model and calls on the legacy side use the legacy one, with the translation in one place:
namespace Underwriting
{
public enum PolicyStatus { Active, Lapsed, Cancelled }
public sealed record Policy(string Id, PolicyStatus Status, DateOnly? RenewsOn);
}
namespace Mainframe.Bridge
{
// The anti-corruption layer. Legacy names stop at this class.
public sealed class LegacyPolicyClient(LegacyPolicyGateway legacy)
{
public Task<Policy?> FindAsync(string id, CancellationToken ct)
{
var record = legacy.Get(id);
return Task.FromResult(record is null ? null : Translate(record));
}
private static Policy Translate(LegacyPolicyRecord record) => new(
record.POL_NO,
record.STAT_CD switch
{
"A" => PolicyStatus.Active,
"L" => PolicyStatus.Lapsed,
"C" => PolicyStatus.Cancelled,
var code => throw new LegacyDataException(
$"Unknown STAT_CD '{code}' on policy {record.POL_NO}"),
},
record.RENEW_DT == "00000000"
? null
: DateOnly.ParseExact(record.RENEW_DT, "yyyyMMdd", CultureInfo.InvariantCulture));
}
}FindAsync returns Policy, so no LegacyPolicyRecord gets past this class. The 00000000 rule behind the 31
mismatches now has one documented home. An unknown code fails at the border with the message
Unknown STAT_CD 'X' on policy P-9999, instead of defaulting to something plausible and spreading.
Microsoft's guidance adds that the layer should hold translation logic and stay free of business rules and orchestration, and that you should decide whether it is temporary. Traffic can flow in both directions during a migration, because unmigrated legacy code may need to call new services, so the translator may need two halves.
For reads, you can run both implementations and return the legacy answer, which is how the 31 mismatches surfaced:
public sealed class ShadowComparison(
LegacyPolicyClient legacy, ReplacementPolicyClient replacement, Action<string> log)
{
public async Task<Policy?> FindAsync(string id, CancellationToken ct)
{
var answer = await legacy.FindAsync(id, ct);
try
{
var candidate = await replacement.FindAsync(id, ct);
if (candidate != answer)
{
log($"mismatch {id}: legacy {JsonSerializer.Serialize(answer)}, " +
$"replacement {JsonSerializer.Serialize(candidate)}");
}
}
catch (Exception e)
{
log($"replacement failed {id}: {e.GetType().Name}");
}
return answer;
}
}The try keeps a crash in the new code away from users. In production you would sample and run the comparison
off the request path, since this sequential version makes every call wait for both. Record equality works here
because Policy is a record, and a real comparison usually needs normalization for rounding, ordering and
timestamps. Only shadow operations without side effects: running a replacement that charges a card or sends a
letter means doing it twice.
Read each mismatch as a question about which side is right. Sometimes the old system has a bug that customers depend on, and then you have a product decision to make.
Once mismatches are understood, send real traffic. The same policy should reach the same side on every call, or one user sees two answers across two page loads. That requires a hash that stays the same across processes:
public sealed class Rollout
{
public int Percent { get; set; }
public bool UseReplacement(string policyId) => Bucket(policyId) < Percent;
public static int Bucket(string key)
{
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(key));
return (int)(BinaryPrimitives.ReadUInt32BigEndian(hash) % 100);
}
}Do not use string.GetHashCode() for this. Its documentation warns that two runs of the same program may return
different hash codes. Two runs of this
sample hashed P-1003 to 439847401 and -895344522, while its bucket stayed 83. Over 100,000 generated ids, the 10%
setting selected 9,965 and the 25% setting selected 24,751, and every id at 10% was still included at 25%. Raising
the percentage therefore only adds policies and never moves one back to legacy.
Lowering Percent from 100 to 0 on the running sample changed renewsOn for P-0007 from 0001-01-01 back to
null on the next request. Read that value from configuration you can change without a deployment, and you have a
rollback that takes seconds, for reads.
Reads went back to legacy by setting one percentage to 0. A write accepted by the new store has no such path: legacy is missing it unless something copies it back.
Decide who holds the system of record per entity, and allow only one at a time.
A cautious order keeps legacy as the record for as long as possible, with new code writing through the anti-corruption layer. When the data must move, Microsoft's guidance describes extracting a domain's tables into a new database, keeping them in sync through change data capture, and validating consistency before cutover. It also marks the point of no easy return: rollback stays practical until the domain's legacy tables and sync processes are removed, so removal should be a deliberate final step.
Avoid having application code write to both stores in one request. Those are two writes with a crash between them, the same gap the transactional outbox exists to close. A change data capture pipeline or an outbox gives you one source and a retryable copy. Where external clients are involved, keep the contract stable through the whole move using the backward compatibility rules.
A migration stalls when delivering the next feature always beats finishing the last few routes, and then you own both systems indefinitely. Fowler notes that people resist building transitional code because it will be thrown away, and argues the reduced risk is worth it. The same logic demands that it actually gets thrown away. Track each route with an owner and a state, and treat deletion as part of the work for that route: the legacy handler, the flag, the shadow reader, and the translator once nothing calls it. Microsoft's last step removes the facade too, unless you keep it as an adapter for old clients.
A migration branch that lands inside a stable core is the version of this that never gets deleted, because removing the old system then means editing code that every request passes through. The architecture exercises include that refactor, and how it works explains how behavior and design are graded together.
The pattern is overkill for a small system that can be replaced whole, and it requires that the old system can keep running for the duration.
Practice Architecture & Design
- Open in the editor: Two Sides of the Hexagon
Architecture Medium Free, no account needed
Two Sides of the Hexagon
A driving (web) adapter reaches the driven (persistence) adapter directly for a quick existence check. Inject the repository "via its interface" and you'll find the seam is still on the wrong side of the hexagon.
- Open the Pro kata: Strangle Behind the Port
Architecture Medium Katabench Pro
Strangle Behind the Port
A pricing core chooses between legacy and replacement tax engines itself, so a temporary migration decision has become permanent domain coupling. Put coexistence behind one core-owned port and let an outer adapter route the strangler migration.
More like this: C# architecture exercises →