Skip to content

Lesson 38 of 59Product features

Feature Flags and Safe Rollouts

Build feature flags into a FastAPI service: rules and stable percentage rollouts, a flag dependency, vendors and OpenFeature, migrations, tests and cleanup.

19 min read0/5 questions

Your team has rebuilt checkout. The product manager wants staff to use it first, then one big customer, then 10% of everyone, and the on-call engineer wants a way to switch it off at 2am without a deploy. None of that is possible if the new code only goes live by merging and shipping. A feature flag is the switch that makes it possible: the code is deployed everywhere, and a runtime decision picks which path each request takes. This lesson is about building that decision into a Python service so it is fast, predictable, testable and easy to remove later.

From release practice to code

The Engineering at Work course's CI/CD and Release Practices covered the idea that deploying is not releasing, and the four kinds of flag: release flags, ops flags (kill switches), experiment flags and permission flags. Here the question is what each kind means for the code you write, because the kind decides where the value lives, who flips it, and what happens when the value cannot be read.

  • Release flags gate unfinished or new work. Engineers flip them. They should default to off, because an unknown state should never expose half-built work. They are deleted within weeks.
  • Kill switches protect the system. On-call flips them during an incident, so they must change in seconds without a deploy. Their safe default is "feature running normally", which is why good teams name them for the thing they turn off: disable-recommendations defaulting to false reads correctly at 2am.
  • Experiment flags return a variant ("control", "new-copy"), not just a boolean, and every evaluation must be recorded as an exposure so the analysis knows who saw what.
  • Permission flags depend on the customer: plan, tenant, region. They are product configuration with a long life, and many teams eventually move them into a proper entitlements table.
Match the pairs0/4 matched

Match each flag to the behaviour its code should have.

Choose an item, then its match on the other side.

A flag engine you can read in one sitting

Before reaching for a vendor, it helps to write the core yourself. Every flag system, however large, evaluates a flag against a context (who is asking) and walks the same short list: is the flag known, is it switched off globally, does a targeting rule match, is this user inside the percentage rollout.

Python
import hashlibfrom dataclasses import dataclass, field @dataclass(frozen=True)class Rule: attribute: str # "plan", "tenant", "country" values: frozenset @dataclass(frozen=True)class Flag: key: str enabled: bool = True # False is the kill switch: off for everyone rules: tuple = () # targeting, checked in order percent: int = 0 # rollout for everyone the rules did not match @dataclass(frozen=True)class Context: user_id: str attributes: dict = field(default_factory=dict) def bucket(key: str, user_id: str) -> int: digest = hashlib.sha256(f"{key}:{user_id}".encode()).digest() return int.from_bytes(digest[:4], "big") % 100 def evaluate(flag, ctx, default=False): if flag is None: return default, "unknown flag, using default" if not flag.enabled: return False, "kill switch" for rule in flag.rules: if ctx.attributes.get(rule.attribute) in rule.values: return True, f"rule {rule.attribute}" if bucket(flag.key, ctx.user_id) < flag.percent: return True, f"in {flag.percent}% rollout" return False, "not in rollout" flags = { "new-checkout": Flag( "new-checkout", rules=(Rule("plan", frozenset({"internal"})), Rule("tenant", frozenset({"acme"}))), percent=10, ), "recommendations": Flag("recommendations", enabled=False, percent=100),} people = [ Context("staff-1", {"plan": "internal"}), Context("u-77", {"plan": "pro", "tenant": "acme"}), Context("u-12", {"plan": "free"}), Context("u-13", {"plan": "free"}),] for ctx in people: on, why = evaluate(flags["new-checkout"], ctx) print(f"new-checkout {ctx.user_id:8} {str(on):5} {why}") print("recommendations", evaluate(flags["recommendations"], people[0]))print("typo'd key ", evaluate(flags.get("new-chekout"), people[0], default=False)) on = sum(evaluate(flags["new-checkout"], Context(f"user-{n}"))[0] for n in range(10_000))print("anonymous users on:", on, "of 10000")
Output
Press Run (⌘ Enter) to see what happens.

Three details carry most of the weight.

Order matters. The global switch is checked first, so a kill switch beats every rule. Targeting comes before the percentage, so staff and the pilot tenant are always in, whatever the rollout number. Put the percentage first and your own staff would lose the feature they are meant to be testing.

The bucket is deterministic. As the CI/CD lesson showed, hashing the flag key with the user id gives each user a stable number from 0 to 99, so they see the same thing on every request and on every server, with nothing stored. Raising the percentage from 10 to 20 only adds users. Python's built-in hash() would be a bug here: string hashing is randomised per process, so each Uvicorn worker would put the same user in a different bucket.

The context needs a stable id. For logged-in users the user id works. For anonymous visitors you need an id that survives between requests, usually a random value in a long-lived cookie. If you bucket on something that changes, such as a request id, the user flips between old and new checkout as they click, which is worse than either version. For tenant-wide features, bucket on the tenant id instead, so a whole company switches together and their support tickets make sense.

Predict the outputPython

The flag is called new_checkout in the store, and the route asks for new-checkout. What prints?

def is_on(flags, key, default=False):
  return flags.get(key, default)

flags = {"new_checkout": True}
print(is_on(flags, "new-checkout"))
Need a nudge? Hints walk you through it.

Wiring flags into FastAPI

In the service, flags arrive through dependency injection like any other resource, which is what makes them easy to override in tests. The context is built from whatever the auth dependency already knows.

app/flags/deps.py
from typing import Annotated
 
from fastapi import Depends, Request
 
from app.auth.deps import CurrentUser
from app.flags.engine import Context, FlagStore
 
 
def get_flags(request: Request) -> FlagStore:
    return request.app.state.flags          # created once in lifespan
 
 
def get_flag_context(user: CurrentUser) -> Context:
    return Context(
        user_id=str(user.id),
        attributes={"plan": user.plan, "tenant": str(user.tenant_id), "country": user.country},
    )
 
 
Flags = Annotated[FlagStore, Depends(get_flags)]
FlagCtx = Annotated[Context, Depends(get_flag_context)]
app/routes/checkout.py
from app.flags import keys
from app.flags.deps import FlagCtx, Flags
 
 
@router.post("/checkout")
async def checkout(body: CheckoutIn, flags: Flags, ctx: FlagCtx) -> CheckoutOut:
    if flags.is_on(keys.NEW_CHECKOUT, ctx):
        return await checkout_v2(body, ctx.user_id)
    return await checkout_v1(body, ctx.user_id)

Keep the if at the edge, in the route or one service function, not scattered through ten helpers. One branch point is easy to read and easy to delete. Evaluate each flag once per request and pass the result down, so a flag flipped halfway through a request cannot give you half a v1 order and half a v2 order. The same goes for background work: if the route enqueues a Celery task, put the evaluated decision in the task arguments rather than re-evaluating in the worker minutes later.

Where flag values live

The engine is the easy part. The hard part is getting fresh values to every process quickly and deciding what happens when you cannot.

Local evaluation with streamed updates
Flag dashboard: someone flips a flagFlag dashboardsomeone flips a flagFlag service: vendor or self-hostedFlag servicevendor or self-hostedSDK in each worker: rules held in memorySDK in each workerrules held in memoryFastAPI route: evaluates locallyFastAPI routeevaluates locallyBrowser: sends a requestBrowsersends a requestExposure events: who saw whatExposure eventswho saw whatsavestream or pollis_on()batched

At startup the SDK downloads all flag rules and holds them in memory. Until that first download finishes, it can only return the defaults written in your code.

1/6

The common options, from simplest up:

  • Settings or environment variables. APP_FLAGS__NEW_CHECKOUT=true through pydantic-settings, as in Settings and Config. Fine for a few ops flags on a small service, but changing one means a restart, and there is no targeting.
  • A database table (key, enabled, rules as JSON, percent, updated_at) cached in each process for 10 to 30 seconds. Cheap and under your control. Never query the table on every request: a hot route evaluating three flags would triple its database load. Accept that a flip takes one cache period to land everywhere, or broadcast changes with Redis pub/sub.
  • A flag service with local evaluation, as in the diagram. This is what vendor server-side SDKs do. Some SDKs instead make a remote call per evaluation; that adds latency and a new failure point to every request, so prefer local evaluation for backend code.

Decide the failure behaviour on purpose. Every lookup takes a code default, and that default must be the safe one for that flag kind: off for release flags, "normal operation" for kill switches. Start the SDK in lifespan and decide whether to wait for the first sync (a few hundred milliseconds of startup, correct values from the first request) or start immediately on defaults. For a kill switch that is currently on, starting on defaults means a fresh pod briefly turns the dangerous feature back on, so wait.

Vendors, self-hosting and OpenFeature

You will meet these names at work. LaunchDarkly is the large commercial option. Unleash and Flagsmith are open source and can be self-hosted or bought as a service. GrowthBook is open source with a focus on experiments and statistics. PostHog bundles flags with product analytics, which is convenient when experiments are the main use. All of them offer Python server SDKs with local evaluation, targeting and percentage rollouts; the differences are in experiment analysis, audit logs, approvals and hosting.

OpenFeature is a CNCF standard API for flags. Your code calls the OpenFeature client, and a provider plugs in the vendor behind it. Switching vendors, or running an in-memory provider in tests, then changes one line of setup instead of every call site.

app/flags/openfeature_setup.py
from openfeature import api
from openfeature.evaluation_context import EvaluationContext
from openfeature.provider.in_memory_provider import InMemoryFlag, InMemoryProvider
 
# Production would call api.set_provider(...) with your vendor's provider package.
api.set_provider(InMemoryProvider({
    "new-checkout": InMemoryFlag("off", {"on": True, "off": False}),
}))
 
client = api.get_client()
ctx = EvaluationContext(targeting_key="user-42", attributes={"plan": "pro"})
 
client.get_boolean_value("new-checkout", False, ctx)        # False
details = client.get_boolean_details("missing-flag", False, ctx)
details.value, details.reason, details.error_code           # False, Reason.ERROR, FLAG_NOT_FOUND

The targeting_key is the stable id used for bucketing. The *_details methods tell you why you got a value, including errors like a missing flag, which is exactly what you want in logs. Provider packages for each vendor are published separately; check the OpenFeature docs for the one you need and its current version.

Flags and database migrations

A flag can turn code off in a second. It cannot undo a schema change. So the code on both sides of a flag must work with the same database, which leads to the expand/contract pattern (also called parallel change). Say the new checkout stores the address in a new shipping_address_id column instead of text fields on orders.

Put it in order6 steps

Put the steps of a flag-guarded schema change in a safe order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

The rule of thumb: during a rollout, turning the flag off must always be safe. If it is not, because the new path writes data the old path cannot read, you do not have a flag, you have a one-way door with a switch painted on it.

Testing flagged code

Every boolean flag doubles the paths through the code, so testing the full matrix is impossible beyond a handful of flags. The practical rule: test both paths of every flag your change touches, with all other flags at their production values. Because the store comes from a dependency, overriding it is one line.

tests/test_checkout_flags.py
import pytest
from fastapi.testclient import TestClient
 
from app.flags.deps import get_flags
from app.flags.engine import Flag, FlagStore
from app.main import app
 
 
@pytest.fixture
def client_with_flags(request):
    store = FlagStore(request.param)
    app.dependency_overrides[get_flags] = lambda: store
    yield TestClient(app)
    app.dependency_overrides.clear()
 
 
@pytest.mark.parametrize(
    ("client_with_flags", "expected"),
    [
        ({"new-checkout": Flag("new-checkout", percent=100)}, "v2"),
        ({"new-checkout": Flag("new-checkout", enabled=False, percent=100)}, "v1"),
        ({}, "v1"),        # flag missing entirely: the default path
    ],
    indirect=["client_with_flags"],
)
def test_checkout_both_paths(client_with_flags, expected, auth_headers):
    response = client_with_flags.post("/checkout", json=CART, headers=auth_headers)
    assert response.json()["flow"] == expected

The third case is the one people forget: the flag service has never heard of the flag. Unit-test the engine itself separately, especially rule order and bucket stability, since a change there affects every flag at once.

Flag debt and cleanup

Release flags are meant to die. Left alone they become dead branches, confusing conditions and, as the warning in CI/CD and Release Practices describes, a real risk when old code wakes up. Make cleanup mechanical instead of relying on memory:

  • Keep a registry in the repo (a flags.toml or a Python module) with each flag's key, kind, owner and expiry date. Creating a flag means adding a line, in review.
  • Run a CI check that fails when code reads an unregistered flag, a release flag has passed its expiry, or a registered flag is no longer read anywhere.
  • Delete the flag in two steps: first a PR that removes the losing branch and the if, then removal from the flag service once no deployed version reads it. Do it in the other order and old pods fall back to defaults mid-rollout.
Python
import refrom datetime import date # flags.toml in a real repo; a dict hereREGISTRY = { "new-checkout": {"owner": "payments", "kind": "release", "expires": date(2026, 11, 30)}, "search-v2": {"owner": "search", "kind": "release", "expires": date(2026, 9, 1)}, "recommendations": {"owner": "growth", "kind": "ops", "expires": None},} SOURCE = { "app/routes/checkout.py": 'if flags.is_on("new-checkout", ctx):', "app/routes/search.py": 'if flags.is_on("search-v2", ctx):', "app/routes/home.py": 'if flags.is_on("homepage-hero", ctx):',} FLAG_CALL = re.compile(r'is_on\(\s*"([a-z0-9-]+)"') def check(today): problems = [] used = {} for path, text in SOURCE.items(): for key in FLAG_CALL.findall(text): used.setdefault(key, []).append(path) for key, paths in used.items(): if key not in REGISTRY: problems.append(f"{paths[0]}: '{key}' is not in the registry") for key, meta in REGISTRY.items(): if meta["kind"] == "release" and meta["expires"] is None: problems.append(f"'{key}': release flags need an expiry date") elif meta["expires"] and meta["expires"] < today: where = ", ".join(used.get(key, ["no code"])) problems.append(f"'{key}' expired {meta['expires']} (owner {meta['owner']}): {where}") if key not in used: problems.append(f"'{key}' is registered but never read; delete it") return problems problems = check(today=date(2026, 10, 22))for p in problems: print("FAIL", p)print("exit code:", 1 if problems else 0)
Output
Press Run (⌘ Enter) to see what happens.

A regex is crude (it misses keys built from variables), which is one more reason to use constants for flag keys: then the check can import the module instead of scanning text. Several vendors also report flags with no recent evaluations, which catches the same thing from the other side.

Trunk-based development, dark launches and canaries

Flags are what make trunk-based development practical: everyone merges small changes to main daily, and unfinished work ships dark behind a release flag instead of living on a long branch that rots. The cost is that main always contains code paths nobody uses yet, which is why the cleanup discipline above is not optional.

A dark launch goes one step further: the new path runs for real traffic, but its result is thrown away or compared, not shown. For example, the route calls both the old and new pricing functions, returns the old answer, and logs any difference. You find the edge cases with production data and zero user impact. Run the shadow call with a timeout and catch its errors, so the experiment can never break the real response, and watch the extra load.

A canary, from the CI/CD lesson, and a flag answer different questions. A canary tests a new build on a slice of servers: does this image crash, leak memory or slow down? A flag tests a new behaviour on a slice of users: does this feature work for these customers? Teams use both: canary the deploy that contains the flagged code with the flag off, then roll the flag out once the build is trusted.

Quick check
Anonymous visitors in a 20% rollout report the page layout changing between clicks. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.
Quick check
Your flag vendor has an outage. With a local-evaluation SDK, what happens to requests in pods that were already running?
Need a nudge? A hint rules out a wrong answer.
Key terms
evaluation context
The facts about the caller (stable id, plan, tenant, country) that a flag is evaluated against.
targeting rule
A condition such as plan in {internal} that switches a flag on for matching callers before any percentage applies.
bucketing
Hashing the flag key with a stable id into a number from 0 to 99 so percentage rollouts are deterministic.
local evaluation
Holding flag rules in process memory and evaluating them there, with updates streamed or polled in the background.
OpenFeature
A vendor-neutral flag API with pluggable providers, so call sites do not depend on one flag service.
expand/contract
Changing a schema in compatible steps: add, dual write, switch reads, then remove the old shape.
dark launch
Running a new code path on real traffic while hiding or discarding its result, to test it with no user impact.