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.
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-recommendationsdefaulting tofalsereads 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 each flag to the behaviour its code should have.
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.
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.
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"))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.
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)]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.
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.
The common options, from simplest up:
- Settings or environment variables.
APP_FLAGS__NEW_CHECKOUT=truethrough 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,rulesas 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.
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_FOUNDThe 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 the steps of a flag-guarded schema change in a safe order.
- Tap the steps below in the right order.
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.
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"] == expectedThe 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.tomlor 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.
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.
- 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.