Course contents · Lesson 9 of 16

Feature Flags Explained: Ship Code, Release Later

Continuous Delivery · Lesson 9 of 16 · 11 min Engineer

Your team finished a new checkout page on Monday, but it launches on Thursday, and nobody is sure it will cope with real traffic. Feature flags let the code go to production switched off, so you turn it on when you choose. This lesson shows how a flag works in code, the main kinds of flags, and how to keep them tidy.

Deploy is not release

In lesson 8 you saw that to deploy is to put a new version onto the machines that run it. To release is to let users actually use a change. Without a flag, both happen at the same moment: the deploy is the launch, and if the new code misbehaves, every user meets it at once.

A feature flag, also called a feature toggle, is a named setting that the code checks while it runs to decide whether a feature is on. New code reaches production behind a flag that is off, so the deploy changes nothing users can see. The release comes later, when you change the flag's value, without building or shipping new code.

In the timelines, the top team must deploy on launch day. The bottom team deployed on Monday, kept deploying other changes, and released on Thursday by flipping the flag.

Two timelines from Monday to Friday. Top, without a flag, deploy equals release: on Thursday a single deploy plus release event gives the feature to everyone at once, so the risky deploy must happen on launch day. Bottom, with a flag: on Monday the code is deployed with the flag off, more deploys follow on Tuesday and Wednesday, and on Thursday flipping the flag is the release. A bracket from Monday to Thursday reads code in production, switched off. Days are illustrative
With a flag, the deploy becomes routine and the release becomes a separate, reversible decision.

Flags also help continuous integration: you can merge half-finished work into the main branch daily, switched off, instead of keeping a long-lived branch. A flag is not a deployment strategy: a canary routes a share of traffic to a second deployed version, while a flag splits users between two code paths in one version.

How a feature flag looks in code

At its core, a flag is an if-statement: run the new path when the flag is on, the old path otherwise. The old path is the default, used whenever the flag is off, missing or unreadable, so a broken flag setup leaves users on code that already works.

Flowchart. A request arrives when a user clicks Pay. The code checks the flag new_checkout, whose value comes from config or a flag service. If it is on, the new code path new_checkout() runs. If it is off, the default, the old code path old_checkout() runs. Both paths return a response to the user. A note says that if the flag value cannot be read, the code uses the default, off
Every request takes exactly one path, and the old path wins whenever the flag is off or unknown.

The simplest flag source is an environment variable, a named setting the operating system hands a program when it starts. This Python function reads one:

import os

def checkout(cart):
    if os.environ.get("NEW_CHECKOUT") == "true":
        return new_checkout(cart)   # new path
    return old_checkout(cart)       # old path: the default

Only the exact text true turns it on. If NEW_CHECKOUT is unset, os.environ.get returns None, so users get the old checkout. The catch: a running program's environment is fixed when it starts, so flipping this flag means restarting the app with the new value. That is still a config change, not a new build.

A flag service stores flags and lets you change them from a dashboard while the app keeps running; open-source examples include Unleash and flagd. Your app talks to it through an SDK (software development kit), a client library for your language.

OpenFeature is a vendor-neutral API for these calls, so you can switch flag services without rewriting every check. The same function with its Python SDK:

from openfeature import api
from openfeature.evaluation_context import EvaluationContext

client = api.get_client()

def checkout(cart, user_id, email):
    ctx = EvaluationContext(targeting_key=user_id, attributes={"email": email})
    if client.get_boolean_value("new_checkout", False, ctx):
        return new_checkout(cart)
    return old_checkout(cart)

The second argument, False, is the default: the OpenFeature specification says an evaluation returns it, instead of crashing, when something goes wrong. Until you register a provider, the plug-in that connects the SDK to your flag service, every flag returns its default. The context says who is asking, for targeting.

Kinds of flags, and who sees them

Flags differ in purpose and in how long they should live:

KindUsed forLives forExample
Release flagHiding code until launchDays or weeks, then deletedThe new checkout
Kill switchTurning a feature off fast in an emergencyAs long as the featureHide slow recommendations
ExperimentA/B testsThe length of the testTwo button texts
Permission flagA feature for certain users onlyLong-livedBeta features for staff

A kill switch lets the on-call engineer turn off a struggling, non-essential feature without waiting for a deploy. An A/B test shows version A to one random group and version B to another, then compares a number such as completed orders.

Two techniques decide who sees a flag. Targeting turns it on for users who match a rule, such as staff email addresses or one country. A percentage rollout turns it on for a share of users, such as 10 percent. flagd, for example, hashes a value such as the user's ID into a fixed bucket, so the same user gets the same answer on every request.

In a release flag's lifecycle, the deploy happens once, at step 2, and the release spreads across steps 3 to 5. Turning the flag off undoes any of them, often the fastest rollback there is (lesson 10 compares the options).

Six steps of a release flag. Step 1, setup: create the flag new_checkout, off, so 0 percent see it. Step 2, deploy: merge and deploy, the new code is in production but off, 0 percent. Step 3, release: enable for staff accounts only. Step 4, release: roll out to 10 percent of users and watch errors and sales. Step 5, release: roll out to 100 percent, with the flag still there. Step 6, cleanup: delete the flag and the old code, leaving one code path. A note says that in steps 3 to 5 one switch turns it back off, and the 10 percent step is illustrative
Deploy once, release in widening steps, then delete the flag so only one code path is left.

Flag hygiene: remove flags, test both paths

Every flag adds a second path through its code, so a release flag should be short-lived. Once it has sat at 100 percent long enough to trust, delete the flag and the old path in an ordinary pull request. Give each flag an owner and a planned removal date when you create it.

Until then, both paths run in production, so both need tests. Run the relevant tests with the flag on and off, for example by setting NEW_CHECKOUT differently in two CI test runs (lesson 5). Test the missing flag too: the default is what users get whenever the flag cannot be read.

What can go wrong with feature flags

Stale flags. A stale flag is one left behind after its launch. Its dead path still has to be maintained, and someone may flip it months later, waking code that no longer fits the app.

Hidden combinations. Ten independent on/off flags allow 1,024 combinations (2 to the power of 10), and nobody tests them all. A bug may appear only when two particular flags are both on. Keep few flags alive, and avoid flags that depend on other flags.

A new dependency. Once every request checks a flag service, that service is part of your app, and its outage can become yours. Prefer SDKs that keep a local copy. Unleash's Python SDK, for example, checks for changes every 15 seconds by default, caches flags on disk, and evaluates every flag as false until its first sync, so make the default the safe path.

Flag changes are production changes: limit who can make them, and log each one.

Check yourself

You turn new_checkout on for 10 percent of users, and checkout errors double. What is the fastest fix, and why is it faster than redeploying?

Turn the flag off. The old path is already running in production, so going back needs no build and no deploy, and with a flag service not even a restart.

Why does a 10 percent rollout hash each user's ID instead of picking at random on every request?

Random picks would show one user the new checkout on one request and the old one on the next. A hash puts each user in a fixed bucket, so they see one version consistently.

A flag reached 100 percent six months ago and was never removed. Why is that still a risk when everyone sees the new path?

The old path is still in the code, untested and unowned. Anyone can flip the flag back by mistake and wake that path; deleting the flag and the old code removes the chance.