›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Architecture Patterns in Practice

Changing Live Systems: Anti-Corruption Layer, Expand and Contract, Feature Flags

October 13, 2026 · 21 min read

Software Architecture, Design Patterns, C#, Python, Migration, Databases

This post is part of Architecture Patterns in Practice, a series that turns the patterns in my 2026 architecture map into small programs you can run. This one covers section 5 of the map, "How do you change it without breaking it?": three patterns for changing software that can't be switched off while you work on it.

The hard part of most real changes isn't the new code. It's that the old code, the old data and the old clients are all still running while you ship it. Each pattern here handles one side of that:

PatternWhat it protectsThe short version
Anti-corruption layerYour modelTranslate a legacy or third-party model at one boundary, so its words never spread into your code
Expand and contractYour dataChange a schema in backward-compatible steps, so old and new code can run at the same time
Feature flagsYour usersShip code dark, then turn it on for some people, and off again in seconds

The fourth pattern in this family, strangler fig, replaces a whole system one route at a time. I covered it with code in the cloud structure post, so I won't repeat it here. The three below are what you use inside a strangler fig migration, and also on their own.

Every sample below runs as shown: C# as .NET 10 file-based apps (dotnet run file.cs), Python 3.12 with only the standard library. The output blocks are pasted from real runs.

Anti-corruption layer

The name comes from Eric Evans' Domain-Driven Design. When your code has to talk to a system with a different model (a legacy billing system, a vendor API, a database from an acquired product), the easy path is to use its types directly. Then its odd field names, status codes and date formats show up in your services, your tests and your UI. A few years later your code is shaped like their system.

An anti-corruption layer (ACL) is a translator that sits at the boundary. Your code depends on an interface written in your words. One class implements it by calling the other system and translating in both directions. Microsoft's pattern page describes it as "a façade or adapter layer" between the two. In GoF terms it's an Adapter, and often a Facade too, because it hides several legacy calls behind one clean method.

Here's a legacy billing system that returns zero-padded string IDs, one-letter status codes, amounts with thousands separators, and 00000000 for "no date":

from dataclasses import dataclass
from datetime import date, datetime
from decimal import Decimal
from enum import Enum
from typing import Protocol


# ---- Our model: the words our code uses ----
class AccountStatus(Enum):
    ACTIVE = "active"
    SUSPENDED = "suspended"
    CLOSED = "closed"


@dataclass(frozen=True)
class Customer:
    id: int
    status: AccountStatus
    balance: Decimal
    customer_since: date | None


class CustomerDirectory(Protocol):
    """The port our code depends on. Nothing legacy leaks through it."""
    def get(self, customer_id: int) -> Customer: ...
    def suspend(self, customer_id: int, reason: str) -> None: ...


# ---- The legacy system, as it really is (a stand-in for its HTTP client) ----
class LegacyBillingClient:
    def __init__(self):
        self.records = {
            "00042": {"CUST_NO": "00042", "STAT_CD": "A", "BAL_AMT": "1,234.50", "CRT_DT": "20190312"},
            "00077": {"CUST_NO": "00077", "STAT_CD": "H", "BAL_AMT": "0.00", "CRT_DT": "00000000"},
            "00099": {"CUST_NO": "00099", "STAT_CD": "Z", "BAL_AMT": "10.00", "CRT_DT": "20200101"},
        }
        self.sent = []

    def fetch_cust(self, cust_no: str) -> dict:
        return self.records[cust_no]

    def post_txn(self, payload: dict) -> None:
        self.sent.append(payload)


# ---- The anti-corruption layer: the only code that knows both vocabularies ----
class UnknownLegacyValue(Exception):
    pass


class LegacyBillingDirectory:
    _STATUS = {"A": AccountStatus.ACTIVE, "H": AccountStatus.SUSPENDED, "X": AccountStatus.CLOSED}

    def __init__(self, client: LegacyBillingClient):
        self._client = client

    def get(self, customer_id: int) -> Customer:
        raw = self._client.fetch_cust(f"{customer_id:05d}")
        return Customer(
            id=int(raw["CUST_NO"]),
            status=self._status(raw["STAT_CD"]),
            balance=Decimal(raw["BAL_AMT"].replace(",", "")),
            customer_since=None if raw["CRT_DT"] == "00000000"
            else datetime.strptime(raw["CRT_DT"], "%Y%m%d").date(),
        )

    def suspend(self, customer_id: int, reason: str) -> None:
        # Outbound too: our verb becomes their transaction code.
        self._client.post_txn({"TXN_CD": "HOLD", "CUST_NO": f"{customer_id:05d}", "RMK_TXT": reason[:40].upper()})

    def _status(self, code: str) -> AccountStatus:
        if code not in self._STATUS:
            # Fail loudly. A silent default here is how bad data spreads.
            raise UnknownLegacyValue(f"STAT_CD={code!r} has no mapping")
        return self._STATUS[code]


legacy = LegacyBillingClient()
directory: CustomerDirectory = LegacyBillingDirectory(legacy)

print(directory.get(42))
print(directory.get(77))
directory.suspend(42, "Chargeback opened on order 9001")
print(legacy.sent[0])
try:
    directory.get(99)
except UnknownLegacyValue as e:
    print("rejected:", e)
Customer(id=42, status=<AccountStatus.ACTIVE: 'active'>, balance=Decimal('1234.50'), customer_since=datetime.date(2019, 3, 12))
Customer(id=77, status=<AccountStatus.SUSPENDED: 'suspended'>, balance=Decimal('0.00'), customer_since=None)
{'TXN_CD': 'HOLD', 'CUST_NO': '00042', 'RMK_TXT': 'CHARGEBACK OPENED ON ORDER 9001'}
rejected: STAT_CD='Z' has no mapping

Three details matter more than the mapping itself:

  • The interface is ours. CustomerDirectory says suspend, not post_txn with TXN_CD="HOLD". If the billing system is replaced, only LegacyBillingDirectory changes.
  • It translates outbound too. Our verb becomes their transaction code, including their 40-character uppercase remark field. Most ACLs only get written for reads, and then the writes leak.
  • Unknown values fail loudly. Status Z has no mapping, so the translator raises instead of guessing ACTIVE. A silent default is how one odd legacy record turns into a wrong bill. You'll find codes nobody documented. You want to find them in a log, not in a customer complaint.

The C# version has the same shape. The domain types are plain records and an enum, and the translator is the only class that knows the legacy names:

using System.Globalization;

var legacy = new LegacyBillingClient();
ICustomerDirectory directory = new LegacyBillingDirectory(legacy);

Console.WriteLine(directory.Get(42));
Console.WriteLine(directory.Get(77));
directory.Suspend(42, "Chargeback opened on order 9001");
Console.WriteLine(string.Join(", ", legacy.Sent[0].Select(kv => $"{kv.Key}={kv.Value}")));
try { directory.Get(99); }
catch (UnknownLegacyValueException e) { Console.WriteLine($"rejected: {e.Message}"); }

// ---- Our model ----
enum AccountStatus { Active, Suspended, Closed }

record Customer(int Id, AccountStatus Status, decimal Balance, DateOnly? CustomerSince);

interface ICustomerDirectory
{
    Customer Get(int customerId);
    void Suspend(int customerId, string reason);
}

// ---- The legacy system, as it really is (a stand-in for its HTTP client) ----
sealed class LegacyBillingClient
{
    private readonly Dictionary<string, Dictionary<string, string>> _records = new()
    {
        ["00042"] = new() { ["CUST_NO"] = "00042", ["STAT_CD"] = "A", ["BAL_AMT"] = "1,234.50", ["CRT_DT"] = "20190312" },
        ["00077"] = new() { ["CUST_NO"] = "00077", ["STAT_CD"] = "H", ["BAL_AMT"] = "0.00", ["CRT_DT"] = "00000000" },
        ["00099"] = new() { ["CUST_NO"] = "00099", ["STAT_CD"] = "Z", ["BAL_AMT"] = "10.00", ["CRT_DT"] = "20200101" },
    };
    public List<Dictionary<string, string>> Sent { get; } = [];

    public Dictionary<string, string> FetchCust(string custNo) => _records[custNo];
    public void PostTxn(Dictionary<string, string> payload) => Sent.Add(payload);
}

// ---- The anti-corruption layer ----
sealed class UnknownLegacyValueException(string message) : Exception(message);

sealed class LegacyBillingDirectory(LegacyBillingClient client) : ICustomerDirectory
{
    private static readonly Dictionary<string, AccountStatus> Statuses = new()
    {
        ["A"] = AccountStatus.Active, ["H"] = AccountStatus.Suspended, ["X"] = AccountStatus.Closed,
    };

    public Customer Get(int customerId)
    {
        var raw = client.FetchCust(customerId.ToString("D5"));
        return new Customer(
            Id: int.Parse(raw["CUST_NO"]),
            Status: ToStatus(raw["STAT_CD"]),
            Balance: decimal.Parse(raw["BAL_AMT"], NumberStyles.Number, CultureInfo.InvariantCulture),
            CustomerSince: raw["CRT_DT"] == "00000000"
                ? null
                : DateOnly.ParseExact(raw["CRT_DT"], "yyyyMMdd", CultureInfo.InvariantCulture));
    }

    public void Suspend(int customerId, string reason) =>
        client.PostTxn(new()
        {
            ["TXN_CD"] = "HOLD",
            ["CUST_NO"] = customerId.ToString("D5"),
            ["RMK_TXT"] = reason[..Math.Min(40, reason.Length)].ToUpperInvariant(),
        });

    private static AccountStatus ToStatus(string code) =>
        Statuses.TryGetValue(code, out var status)
            ? status
            : throw new UnknownLegacyValueException($"STAT_CD='{code}' has no mapping");
}
Customer { Id = 42, Status = Active, Balance = 1234.50, CustomerSince = 2019-03-12 }
Customer { Id = 77, Status = Suspended, Balance = 0.00, CustomerSince =  }
TXN_CD=HOLD, CUST_NO=00042, RMK_TXT=CHARGEBACK OPENED ON ORDER 9001
rejected: STAT_CD='Z' has no mapping

When not to use it. If the other system's model is already close to yours, or the integration is one small call, an ACL is ceremony. It's also not free at runtime when it's a separate service: Microsoft's page points out the extra hop adds latency and is one more thing to scale and monitor. I'd start with an ACL as a class or module inside your app, like the one above, and only make it a service when several apps need the same translation.

Expand and contract

Martin Fowler calls this parallel change, and many teams call it expand and contract. You want to change something that other code depends on: a method signature, an API field, a database column. Doing it in one step breaks every caller that hasn't changed yet. So you split it into three phases:

  1. Expand. Add the new thing next to the old one. Nothing breaks, because nothing has to use it yet.
  2. Migrate. Move callers and data over to the new thing, one at a time.
  3. Contract. Once nothing uses the old thing, remove it.

The database case is where it pays off most. During a rolling deploy, old and new versions of your app run at the same time against the same database. A migration that renames or retypes a column in place breaks whichever version didn't expect it.

The example: an orders table stores total as a float in dollars, which is the classic money bug. We want total_cents as an integer, with no downtime. SQLite ships with Python, so this one runs the real SQL:

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, total REAL NOT NULL)")


# v1 of the app: dollars as a float. The thing we want to get rid of.
def v1_place(total: float) -> None:
    db.execute("INSERT INTO orders (total) VALUES (?)", (total,))


v1_place(19.99)
v1_place(5.10)

# ---- 1. EXPAND: add the new column. Nullable, so v1 keeps working untouched. ----
db.execute("ALTER TABLE orders ADD COLUMN total_cents INTEGER")


# v2 of the app: writes BOTH, reads new with a fallback to old.
def v2_place(total_cents: int) -> None:
    db.execute("INSERT INTO orders (total, total_cents) VALUES (?, ?)", (total_cents / 100, total_cents))


def v2_read(order_id: int) -> int:
    (cents,) = db.execute(
        "SELECT COALESCE(total_cents, CAST(ROUND(total * 100) AS INTEGER)) FROM orders WHERE id = ?",
        (order_id,)).fetchone()
    return cents


v2_place(4200)
v1_place(7.25)   # an old v1 instance is still running during the rollout. That's normal.
print("after expand:", db.execute("SELECT id, total, total_cents FROM orders").fetchall())
print("v2 reads order 4 as", v2_read(4), "cents")

# ---- 2. MIGRATE: backfill in small batches, so no single statement locks the table for long ----
def backfill(batch_size: int) -> int:
    cur = db.execute(
        """UPDATE orders SET total_cents = CAST(ROUND(total * 100) AS INTEGER)
           WHERE id IN (SELECT id FROM orders WHERE total_cents IS NULL LIMIT ?)""",
        (batch_size,))
    return cur.rowcount


while (n := backfill(batch_size=2)):
    print(f"backfilled {n} row(s)")

mismatches = db.execute(
    "SELECT COUNT(*) FROM orders WHERE total_cents IS NULL OR total_cents != CAST(ROUND(total * 100) AS INTEGER)"
).fetchone()[0]
print("mismatches:", mismatches)

# ---- 3. SWITCH: v3 reads only the new column but still writes both, so rolling back to v2 is safe ----
# ---- 4. CONTRACT: once nothing reads `total`, v4 stops writing it, then drop it ----
db.execute("ALTER TABLE orders DROP COLUMN total")
print("columns now:", [row[1] for row in db.execute("PRAGMA table_info(orders)")])
print("after contract:", db.execute("SELECT id, total_cents FROM orders").fetchall())
after expand: [(1, 19.99, None), (2, 5.1, None), (3, 42.0, 4200), (4, 7.25, None)]
v2 reads order 4 as 725 cents
backfilled 2 row(s)
backfilled 1 row(s)
mismatches: 0
columns now: ['id', 'total_cents']
after contract: [(1, 1999), (2, 510), (3, 4200), (4, 725)]

Order 4 is the interesting row. It was written by an old v1 instance after the new column existed, so it has no total_cents. That's not a bug in the process. It's the normal state of a rolling deploy, and it's why the steps are ordered the way they are:

  • v2 reads with a fallback (COALESCE) so it's correct even before the backfill finishes.
  • The backfill runs after every v1 instance is gone, and runs in small batches so no single UPDATE holds a lock on a big table for minutes. Then you verify it with a mismatch count before going further.
  • v3 switches reads but keeps writing both. That keeps the rollback to v2 safe. If you stop writing the old column in the same release that switches reads, a rollback lands on stale data.
  • Contract is its own release. Stop writing total, deploy, wait, then drop the column. Dropping is the only step you can't undo, so it goes last and alone.

After the backfill you'd normally also add a NOT NULL constraint to the new column. SQLite can't add one with ALTER TABLE, which is why it's missing here. Postgres and SQL Server can.

The C# version uses Microsoft.Data.Sqlite (pulled in by the #:package line) and runs the same steps:

#:package Microsoft.Data.Sqlite@10.0.13
using Microsoft.Data.Sqlite;

using var db = new SqliteConnection("Data Source=:memory:");
db.Open();
Exec("CREATE TABLE orders (id INTEGER PRIMARY KEY, total REAL NOT NULL)");

void V1Place(double total) => Exec("INSERT INTO orders (total) VALUES ($a)", total);
V1Place(19.99);
V1Place(5.10);

// 1. EXPAND: nullable new column. v1 code doesn't know it exists, and doesn't need to.
Exec("ALTER TABLE orders ADD COLUMN total_cents INTEGER");

// v2: write both, read new with a fallback to old.
void V2Place(long cents) => Exec("INSERT INTO orders (total, total_cents) VALUES ($a, $b)", cents / 100.0, cents);
V2Place(4200);
V1Place(7.25);   // an old instance still running mid-rollout

// 2. MIGRATE: batched backfill, then verify.
int batch;
while ((batch = Exec("""
    UPDATE orders SET total_cents = CAST(ROUND(total * 100) AS INTEGER)
    WHERE id IN (SELECT id FROM orders WHERE total_cents IS NULL LIMIT 2)
    """)) > 0)
    Console.WriteLine($"backfilled {batch} row(s)");

var mismatches = Scalar("SELECT COUNT(*) FROM orders WHERE total_cents IS NULL OR total_cents != CAST(ROUND(total * 100) AS INTEGER)");
Console.WriteLine($"mismatches: {mismatches}");

// 3. SWITCH reads to total_cents (still writing both). 4. CONTRACT: stop writing total, then drop it.
Exec("ALTER TABLE orders DROP COLUMN total");

using var read = db.CreateCommand();
read.CommandText = "SELECT id, total_cents FROM orders";
using var r = read.ExecuteReader();
while (r.Read()) Console.WriteLine($"order {r.GetInt64(0)}: {r.GetInt64(1)} cents");

int Exec(string sql, params object[] args)
{
    using var cmd = db.CreateCommand();
    cmd.CommandText = sql;
    for (var i = 0; i < args.Length; i++) cmd.Parameters.AddWithValue("$" + (char)('a' + i), args[i]);
    return cmd.ExecuteNonQuery();
}

long Scalar(string sql)
{
    using var cmd = db.CreateCommand();
    cmd.CommandText = sql;
    return (long)cmd.ExecuteScalar()!;
}
backfilled 2 row(s)
backfilled 1 row(s)
mismatches: 0
order 1: 1999 cents
order 2: 510 cents
order 3: 4200 cents
order 4: 725 cents

Each phase is a separate deploy in real life, which is the point. EF Core and other migration tools will happily generate a single "rename column" migration for you. It's worth reading what they generate and splitting it by hand when the table is live.

When not to use it. If you can take a short maintenance window, or the table is small and nothing else reads it, a single migration is simpler and has fewer moving parts. Expand and contract costs you several releases and some temporary duplicate writes. It's worth it when old and new code really do overlap: rolling deploys, multiple services on one database, or mobile apps hitting an API field you want to rename.

Feature flags

Deploying and releasing are different things. A deploy puts code on servers. A release puts behavior in front of users. A feature flag is a runtime switch that lets you do the first without the second, then release gradually, and turn it off again without a deploy.

Pete Hodgson's article on martinfowler.com sorts flags into four kinds, and the kind decides how long it should live:

  • Release toggles hide unfinished or risky work. Days to weeks. Delete after rollout.
  • Experiment toggles split users for an A/B test. As long as the experiment.
  • Ops toggles are kill switches for expensive or risky paths. Sometimes permanent, on purpose.
  • Permission toggles turn features on for some users (beta testers, a paid tier). Often long-lived.

A small evaluator shows the rules that matter, and the order they apply in:

import hashlib
from dataclasses import dataclass, field
from datetime import date


@dataclass(frozen=True)
class Flag:
    name: str
    owner: str
    expires: date                      # every flag gets a removal date on day one
    enabled: bool = True               # the kill switch: False beats every rule below
    allow: frozenset[str] = field(default_factory=frozenset)
    percent: int = 0                   # share of everyone else who gets it


class Flags:
    def __init__(self, load):
        self._load = load              # where definitions come from: a file, a service, a DB

    def is_on(self, name: str, user_id: str) -> tuple[bool, str]:
        try:
            flag = self._load().get(name)
        except Exception:
            return False, "store unavailable, safe default"
        if flag is None:
            return False, "unknown flag, safe default"
        if not flag.enabled:
            return False, "kill switch"
        if user_id in flag.allow:
            return True, "allow list"
        # Hash the flag name WITH the user, so each flag picks a different 10%.
        bucket = int(hashlib.sha256(f"{name}:{user_id}".encode()).hexdigest(), 16) % 100
        return bucket < flag.percent, f"bucket {bucket} vs {flag.percent}%"

    def overdue(self, today: date) -> list[str]:
        return [f"{f.name} (owner {f.owner}, expired {f.expires})"
                for f in self._load().values() if f.expires < today]


definitions = {
    "orders.read_total_cents": Flag("orders.read_total_cents", "payments-team", date(2026, 12, 1),
                                    allow=frozenset({"qa-1"}), percent=10),
    "checkout.new_tax_engine": Flag("checkout.new_tax_engine", "checkout-team", date(2026, 9, 1),
                                    enabled=False, percent=50),
    "search.new_ranking": Flag("search.new_ranking", "search-team", date(2027, 1, 15), percent=10),
}
flags = Flags(lambda: definitions)

for user in ["qa-1", "user-7", "user-8"]:
    print(user, flags.is_on("orders.read_total_cents", user))
print(flags.is_on("checkout.new_tax_engine", "user-7"))
print(flags.is_on("orders.typo_in_name", "user-7"))


def broken_store():
    raise ConnectionError("config service down")


print(Flags(broken_store).is_on("orders.read_total_cents", "qa-1"))

users = [f"user-{i}" for i in range(1000)]
a = {u for u in users if flags.is_on("orders.read_total_cents", u)[0]}
b = {u for u in users if flags.is_on("search.new_ranking", u)[0]}
print(f"{len(a)} and {len(b)} users on two 10% flags, {len(a & b)} on both")
print("overdue:", flags.overdue(date(2026, 11, 10)))
qa-1 (True, 'allow list')
user-7 (False, 'bucket 31 vs 10%')
user-8 (False, 'bucket 67 vs 10%')
(False, 'kill switch')
(False, 'unknown flag, safe default')
(False, 'store unavailable, safe default')
100 and 106 users on two 10% flags, 4 on both
overdue: ['checkout.new_tax_engine (owner checkout-team, expired 2026-09-01)']

What the output shows:

  • The kill switch wins over everything. checkout.new_tax_engine returns off even though it's set to 50%.
  • Failures default to off. A typo in the flag name, or a config service that's down, gives the safe answer instead of an exception in the middle of a request. "Off" should always mean "the old, known-good path".
  • Hash the flag name with the user ID. If you bucket on the user ID alone, every 10% flag gets the same 10% of users, and those people become the test group for every experiment at once. Mixing in the flag name gives each flag an independent slice: 100 and 106 users, with only 4 on both.
  • Every flag has an owner and an expiry date. The overdue check is cheap to run in CI, and it's the simplest way to stop flags piling up for years.

The first flag in the list is the one from the expand and contract example: orders.read_total_cents switches reads to the new column for 10% of users, then everyone. The two patterns are often used together like that.

The C# version is the same evaluator:

using System.Security.Cryptography;
using System.Text;

var definitions = new Dictionary<string, Flag>
{
    ["orders.read_total_cents"] = new("orders.read_total_cents", "payments-team", new DateOnly(2026, 12, 1),
        Allow: ["qa-1"], Percent: 10),
    ["checkout.new_tax_engine"] = new("checkout.new_tax_engine", "checkout-team", new DateOnly(2026, 9, 1),
        Enabled: false, Percent: 50),
};
var flags = new Flags(() => definitions);

foreach (var user in new[] { "qa-1", "user-7", "user-8" })
    Console.WriteLine($"{user} {flags.IsOn("orders.read_total_cents", user)}");
Console.WriteLine(flags.IsOn("checkout.new_tax_engine", "user-7"));
Console.WriteLine(flags.IsOn("orders.typo_in_name", "user-7"));
Console.WriteLine(new Flags(() => throw new HttpRequestException("config service down")).IsOn("orders.read_total_cents", "qa-1"));
Console.WriteLine("overdue: " + string.Join(", ", flags.Overdue(new DateOnly(2026, 11, 10))));

record Flag(string Name, string Owner, DateOnly Expires, bool Enabled = true, string[]? Allow = null, int Percent = 0);

record Decision(bool On, string Reason);

sealed class Flags(Func<IReadOnlyDictionary<string, Flag>> load)
{
    public Decision IsOn(string name, string userId)
    {
        Flag? flag;
        try { flag = load().GetValueOrDefault(name); }
        catch (Exception) { return new(false, "store unavailable, safe default"); }

        if (flag is null) return new(false, "unknown flag, safe default");
        if (!flag.Enabled) return new(false, "kill switch");
        if (flag.Allow?.Contains(userId) == true) return new(true, "allow list");

        var hash = SHA256.HashData(Encoding.UTF8.GetBytes($"{name}:{userId}"));
        var bucket = (int)(BitConverter.ToUInt32(hash) % 100);
        return new(bucket < flag.Percent, $"bucket {bucket} vs {flag.Percent}%");
    }

    public IEnumerable<string> Overdue(DateOnly today) =>
        load().Values.Where(f => f.Expires < today)
            .Select(f => $"{f.Name} (owner {f.Owner}, expired {f.Expires:yyyy-MM-dd})");
}
qa-1 Decision { On = True, Reason = allow list }
user-7 Decision { On = False, Reason = bucket 49 vs 10% }
user-8 Decision { On = False, Reason = bucket 69 vs 10% }
Decision { On = False, Reason = kill switch }
Decision { On = False, Reason = unknown flag, safe default }
Decision { On = False, Reason = store unavailable, safe default }
overdue: checkout.new_tax_engine (owner checkout-team, expired 2026-09-01)

The buckets differ from the Python run (31 vs 49 for user-7) because each version reads the hash differently: Python takes the whole SHA-256 as one big number, C# takes the first four bytes. Each is stable on its own. But if a web app and an API evaluate the same flag in different languages, they must agree on one bucketing scheme, or a user can see the new feature on one screen and the old one on the next. That's one practical reason to use a flag service and its SDKs rather than rolling your own. In .NET, Microsoft.FeatureManagement is the built-in option, and OpenFeature is a vendor-neutral API with SDKs for both C# and Python.

When not to use it. Every flag doubles the number of paths through that code, and flag combinations are hard to test. A flag for a change you'd ship to everyone anyway, with an easy rollback, is just debt. Don't use flags to hide permanent configuration either: a setting that will never be removed belongs in config with a name that says so. And never let a flag check guard a security decision without the same check on the server, because client-side flags can be flipped by anyone with a debugger.

How the three fit together

A typical risky change uses all three. Say you're moving payments from a legacy provider to a new one:

  1. An anti-corruption layer wraps the legacy provider, so the rest of the code talks about Charge and Refund, not their codes.
  2. A second implementation of the same interface talks to the new provider.
  3. A feature flag picks which implementation runs, for 1%, then 10%, then everyone.
  4. Expand and contract handles the data: a new provider_charge_id column alongside the old one, a backfill, then dropping the old column once the flag is gone.

At that scale, the strangler fig is the same idea applied to a whole system.

Check yourself: questions and answers

1. Your new service needs data from a legacy system with a messy schema. Why not just generate client types from its API and use them everywhere?

Because then the legacy model becomes your model. Every service, test and screen that touches those types now depends on the legacy system's names and quirks, and replacing it later means touching all of them. Generate the client if you like, but use it in exactly one place: the anti-corruption layer that maps it to your own types.

2. The ACL meets a status code it has never seen. Should it map it to a sensible default?

No. It should fail loudly (raise, log, alert) and let you add the mapping on purpose. A default like "active" quietly turns bad legacy data into wrong behavior in your system, and nobody notices until a customer does.

3. Why can't you rename a column in one migration during a rolling deploy?

Because for a while, old and new versions of the app run at the same time. Whichever version doesn't match the schema breaks. Expand and contract keeps the schema compatible with both versions at every step: add the new column, write both, backfill, switch reads, stop writing the old one, then drop it.

4. In expand and contract, why keep writing the old column after reads have switched to the new one?

So you can roll back. If the release that switches reads also stops writing the old column, rolling back to the previous version puts you on a column that missed every write since the deploy. Stop writing it in a later release, once you're sure you won't go back.

5. What should a feature flag return when the flag service is down?

The safe default, which is almost always "off", meaning the old, known-good path. A flag check should never throw in a request path. Good flag SDKs also cache the last known values so a short outage doesn't change behavior at all.

6. Why hash the flag name together with the user ID for a percentage rollout?

So each flag gets an independent sample of users. If you hash only the user ID, the same 10% of users are in every 10% rollout, so they see every new feature at once. Their bad experience is then hard to pin on any one change, and your experiments interfere with each other.

Further reading

  • Microsoft Azure Architecture Center, Anti-Corruption Layer pattern
  • Martin Fowler, Parallel Change (expand and contract)
  • Martin Fowler and Pramod Sadalage, Evolutionary Database Design
  • Pete Hodgson on martinfowler.com, Feature Toggles (aka Feature Flags)
  • OpenFeature, the vendor-neutral feature flag API
  • Martin Fowler, Strangler Fig Application, and my cloud structure post with code for it
  • My Adapter, Facade and Proxy post, for the GoF patterns an anti-corruption layer is built from
← Previous

Composite, Bridge and Flyweight, from Shopping Carts to Agent Teams

Next →

Adapter, Facade and Proxy, the Plumbing Behind AI Apps

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.