Skip to content
Blog

Feature Flags Explained: Rollouts and Kill Switches

By Published A short read

Feature flags: the shop's new checkout went to 1,020 of 10,000 shoppers at 10%, then 2,466 at 25% with all 1,020 still in, then 0 after the kill switch

A feature flag is an if statement whose answer lives outside the code: a switch the team can flip while the app is running. It lets you ship new code switched off, turn it on for 10% of users, then everyone, and switch it off in seconds if it breaks, without a new deploy.

In this post we go back to the shop from the caching strategies post. It has a new checkout page, and nobody wants to bet the whole shop on it on day one. First we see the problem flags solve, with a restaurant trying a new dish. Then we meet the four kinds of flags, see how a flag decides who gets a feature, and build a small flag system in plain Python. We roll the new checkout out to 10% of shoppers, then 25%, and then hit the kill switch. We finish with the mistakes beginners make, including a reused flag that helped cost one company more than $460 million in about 45 minutes of trading, and when not to use a flag at all.

A few words first. To deploy means to put a new version of the code on the servers. To release a feature means to let users see it. Without flags, the two happen at the same moment. Production is the real app that real users use, as opposed to a copy on a developer's laptop. A rollback means going back to the previous version of the code.

Key takeaways

  • A feature flag splits deploy from release. The new code goes to the servers switched off, and the team decides later, and separately, who sees it.
  • There are four common kinds: release flags (hide unfinished work, live for days or weeks), experiment flags (A/B tests), ops flags (kill switches) and permission flags (features only some customers get).
  • A percentage rollout gives each user a fixed number from 0 to 99, made by hashing the flag's name and the user's id. In our test, 10% gave the new checkout to 1,020 of 10,000 shoppers, and at 25% all 1,020 were still in.
  • A kill switch turns a feature off for everyone in seconds. It must win over every other rule: after it, our shop showed the new checkout to 0 shoppers.
  • Don't pick users with a coin toss on every visit: in our test, 1,810 shoppers saw a different checkout on their second visit. A hash gave 0.
  • Every flag is a debt. Give it an owner and a removal date, and never reuse an old flag's name for something new.

What is a feature flag in simple words?

Picture a busy restaurant. The chef has a new dish, a mango curry, and wants to know whether people like it before it goes on the printed menu. The kitchen already knows how to make it. So the manager tells the waiters: "Offer it to tables 3 and 7 tonight, and to anyone who asks for the chef's special." If guests love it, more tables get it tomorrow. If the mangoes run out, or a guest finds it far too spicy, the manager says one word to the kitchen, "stop", and the dish is gone from every table in a minute. Nobody rebuilt the kitchen, and nobody reprinted the menu.

A feature flag is that word from the manager. The code for the new feature is already on the servers (the kitchen can make the dish). A small check in the code asks "is this switched on, for this user?" (should this table be offered it?), and the answer comes from outside the code: a file, a database or a flag service that the team can change at any time. Martin Fowler's site, in Pete Hodgson's long article on the subject, calls feature flags "a powerful technique, allowing teams to modify system behavior without changing code." You'll also hear them called feature toggles, feature switches or feature bits; they all mean the same thing.

What problem do feature flags solve?

Without flags, the only way to show users new code is to deploy it, and the only way to hide it again is another deploy. Three things go wrong:

  • Big, scary releases. The new checkout is built for weeks on a separate copy of the code, called a branch. On launch day it's joined back into the main code and deployed to every user at once. If it has a bug, every shopper hits it at the same moment.
  • Slow escapes. When something breaks, the fix is a rollback: deploy the old version again, and sometimes rebuild and re-test it first. That can take many minutes, and the broken page is live the whole time.
  • Painful merges. A branch that lives for weeks drifts away from everyone else's code, and joining them back together (a merge) gets harder every day.

With a flag, the new checkout code is merged into the main code every day, switched off. It's deployed with everything else, but nobody sees it. On launch day the team switches it on for a few shoppers, watches, and switches it on for more. The article on Martin Fowler's site calls this "the most common way" to follow the principle of Continuous Delivery (a way of working where the main code is always ready to deploy): "separating [feature] release from [code] deployment." GitLab's documentation puts it the same way: "Feature flags help reduce risk, allowing you to do controlled testing, and separate feature delivery from customer launch."

What are the types of feature flags?

Pete Hodgson's article sorts flags into four kinds. They work the same way in code, but they live for very different lengths of time, and that changes how you should treat them.

  • Release flags hide work that isn't finished. "Release Toggles allow incomplete and un-tested codepaths to be shipped to production as latent code which may never be turned on." (Latent means there, but not active.) They should be short-lived: "They should generally not stick around much longer than a week or two, although product-centric toggles may need to remain in place for a longer period."
  • Experiment flags show two versions to two groups and compare them: "Experiment Toggles are used to perform multivariate or A/B testing." (Multivariate means testing more than two versions at once.) In an A/B test, half the shoppers might see a green "Pay now" button and half a blue one, and the team counts which half pays more often.
  • Ops flags control how the system runs, not what it offers: "These flags are used to control operational aspects of our system's behavior." The best known is the kill switch, which we build below.
  • Permission flags decide which customers get a feature at all: "For example we may have a set of "premium" features which we only toggle on for our paying customers." These can stay for good: "a Permissioning Toggle may be very-long lived compared to other categories of Feature Toggles - at the scale of multiple years."
KindUsed forLives forHow often its answer changes
ReleaseHiding unfinished work; a slow rolloutDays to a few weeksDuring the rollout, then the flag is removed
ExperimentA/B testsAs long as the test runsPer user, on every request
OpsKill switches; turning off heavy features under loadMost short; a few kill switches for goodAny minute, by the people running the app
PermissionPremium features, early-access groupsMonths to yearsPer user, on every request

A permission flag is about who gets a feature, not who is allowed to see private data. Checking that a shopper may only open their own orders is a job for proper access control, which we covered in RBAC vs ABAC.

How does a feature flag decide who gets a feature?

Two pieces work together. The toggle point is the if in your code where the app asks. The toggle router is the code that answers, from the flag's rules. The app passes it two things: the flag's name, and who's asking. The OpenFeature specification, an open standard for flag libraries, calls the "who" the evaluation context, and the user's id inside it the targeting key: "The targeting key uniquely identifies the subject (end-user, or client service) of a flag evaluation."

The router then works through the flag's rules. OpenFeature calls this targeting: "The application of rules, specific user overrides, or fractional evaluations in feature flag resolution." (A fractional evaluation is a percentage rollout: a fraction of users get the feature.) In our shop the rules are checked in this order:

  1. Does the flag exist? If not, return a safe default (off), and don't crash. OpenFeature: "Flag evaluation calls must always return the default value in the event of abnormal execution."
  2. Is the flag switched on? If not (someone has pulled the kill switch), the answer is off, for everyone.
  3. Is this a named user? The team, or a test account, can be listed by name and always get the feature.
  4. Is the user inside the percentage? Everyone else gets a fixed number from 0 to 99, called their bucket. If it's below the rollout percentage, they get the feature.
How a feature flag decides: the checkout code asks is_on(new-checkout, user). The flag router checks in order: does the flag exist (no: default off), is it switched on (no: off for everyone), is the user named (yes: on), is the user's bucket below the percentage (yes: new checkout, no: old checkout)
One question from the code, four rules in a fixed order. The kill switch comes before everything else.

Keep the toggle point and the toggle router apart. The article on Martin Fowler's site warns: "One common mistake with Feature Toggles is to couple the place where a toggling decision is made (the Toggle Point) with the logic behind the decision (the Toggle Router)." If the checkout code itself checks "is this user's id in the list, and is it Tuesday", every change to the rollout means changing checkout code. When the checkout code only asks is_on("new-checkout", user), the rules can change without touching it.

How do you build feature flags in Python?

Let's build one. The rules live in a file, flags.json. JSON is a plain-text format for data that most languages can read. The new checkout is on for 10% of shoppers and for Asha, who works on the team. A second flag, for a dark mode, is also at 10%:

{
  "new-checkout": {"on": true, "percent": 10, "users": ["asha"]},
  "dark-mode": {"on": true, "percent": 10}
}

Now the toggle router. Everything here is in Python's standard library, so there's nothing to install:

# flags.py
"""A small feature flag system: the rules live in flags.json, and the app only ever asks is_on()."""
import hashlib
import json


def bucket(flag, user_id):
    """A number from 0 to 99 for this user and this flag. The same inputs give the same number, every time."""
    digest = hashlib.sha256(f"{flag}:{user_id}".encode()).digest()
    return int.from_bytes(digest[:4], "big") % 100


class Flags:
    def __init__(self, path):
        self.path = path
        self.reload()

    def reload(self):                            # read the rules again, without restarting the app
        with open(self.path, encoding="utf-8") as f:
            self.rules = json.load(f)

    def is_on(self, flag, user_id, default=False):
        rule = self.rules.get(flag)
        if rule is None:                         # a flag nobody created: the safe answer, not a crash
            return default
        if not rule.get("on", False):            # the kill switch: off means off for everyone
            return False
        if user_id in rule.get("users", []):     # named people first, such as the team
            return True
        return bucket(flag, user_id) < rule.get("percent", 0)
  • bucket turns the flag's name and the user's id into a number from 0 to 99. It uses a hash function: a function that mixes any text into a fixed-size number, so that the same text always gives the same number, and texts that differ by one letter give completely different numbers. SHA-256 is one of the hash functions in Python's hashlib module. We take the first 4 bytes of the result as a whole number (32 bits, so up to about 4.3 billion), and % 100 keeps the remainder after dividing by 100, which is 0 to 99.
  • is_on checks the four rules in the order from the diagram: missing flag, kill switch, named users, then the percentage. A shopper whose bucket is 0 to 9 is inside a 10% rollout.
  • reload reads the file again, so the rules can change while the app runs. Real flag systems do the same thing with a database or a flag service, and push changes to every server.

Now the rollout. 10,000 pretend shoppers, called user-1 to user-10000, visit the shop. The change function does what a flag dashboard does: it edits the rules and reloads them, while the app keeps running:

# rollout.py
"""The shop rolls out its new checkout page to more and more shoppers, then hits the kill switch."""
import json

from flags import Flags

flags = Flags("flags.json")
shoppers = [f"user-{n}" for n in range(1, 10_001)]


def change(flag, **new):                         # what a "flags" dashboard does: edit the rules, then reload
    flags.rules[flag].update(new)
    with open("flags.json", "w", encoding="utf-8") as f:
        json.dump(flags.rules, f, indent=2)
    flags.reload()


def who_gets(flag):
    return {s for s in shoppers if flags.is_on(flag, s)}


print("1) new-checkout at 10%")
first = who_gets("new-checkout")
print(f"   shoppers who get it: {len(first)} of {len(shoppers)}")
print("   user-42 on five visits:", [flags.is_on("new-checkout", "user-42") for _ in range(5)])
print("   asha, on the team:", flags.is_on("new-checkout", "asha"))

print("2) No errors, so up to 25%")
change("new-checkout", percent=25)
second = who_gets("new-checkout")
print(f"   shoppers who get it: {len(second)}, still in from the 10%: {len(first & second)}")

print("3) Payments start failing: the kill switch")
change("new-checkout", on=False)
print(f"   shoppers who get it: {len(who_gets('new-checkout'))}, asha: {flags.is_on('new-checkout', 'asha')}")

print("4) A typo in the flag's name")
print("   new-chekout for user-42:", flags.is_on("new-chekout", "user-42"))

Make a new folder and save the three files in it: flags.json, and the two Python files, each under the name in its first line. Open a terminal (a command-line window) in that folder and run it. In the output blocks, a line starting with $ is what you type, without the $; the lines under it are what it prints. The script rewrites flags.json as it goes, so put the original back before you run it a second time.

$ python rollout.py
1) new-checkout at 10%
   shoppers who get it: 1020 of 10000
   user-42 on five visits: [True, True, True, True, True]
   asha, on the team: True
2) No errors, so up to 25%
   shoppers who get it: 2466, still in from the 10%: 1020
3) Payments start failing: the kill switch
   shoppers who get it: 0, asha: False
4) A typo in the flag's name
   new-chekout for user-42: False

Let's read it step by step:

  1. About 10%, and always the same people. 1,020 of 10,000 shoppers got the new checkout: close to 10%, not exactly. It's like giving every shopper one roll of a 100-sided die and writing it down: about 10 in every 100 roll under 10, not exactly 10. user-42 happens to be one of them, and got the new checkout on all five visits. Asha is in because she's named in the rules.
  2. Raising the percentage only adds people. At 25%, 2,466 shoppers got it, and all 1,020 from the 10% were still in. Nobody who already had the new checkout lost it. That's because each shopper's bucket never changes: a shopper with bucket 7 is inside 10% and inside 25%.
  3. The kill switch beats every rule. One change, on=False, and nobody gets the new checkout, not even Asha, with no deploy and no restart. Every shopper is back on the old checkout, which still works because its code was never removed.
  4. A typo fails safe. new-chekout doesn't exist, so is_on returned the default, False, instead of crashing the checkout page. The catch is that a typo is silent. Real flag systems log a warning for an unknown flag, and many teams keep flag names as constants in one file, so a typo becomes an error the moment the code runs.

How does a percentage rollout keep the same users?

The trick is in bucket. It doesn't toss a coin; it works the number out from the flag's name and the user's id, and the same inputs always give the same answer. Unleash, an open-source flag system, does the same thing with a different hash function: "Unleash hashes a context field together with the strategy's groupId into a number between 0 and 100 using the MurmurHash hash function." (Unleash counts 1 to 100; we count 0 to 99. The idea is the same.) Its docs give the reason: "Because the process is deterministic, the same input always produces the same number." (Deterministic means it gives the same output for the same input, every time.)

Two good things follow, and our run showed both. Unleash's docs again: "Increasing the percentage keeps existing users in the rollout and adds new ones." And going back is safe too: "Returning to a previous percentage brings back the same users." The article on Martin Fowler's site calls these fixed groups cohorts: "groups of users who consistently experience a feature as always being On or Off."

A percentage rollout: each shopper gets a fixed bucket from 0 to 99. At 10%, buckets 0 to 9 get the new checkout, 1,020 of 10,000 shoppers. At 25%, buckets 0 to 24 get it, 2,466 shoppers, and all 1,020 from before are still in. The kill switch makes it 0
Each shopper's bucket never moves. Raising the percentage only adds shoppers.

The flag's name is part of what's hashed. Unleash: "By default, the groupId is the name of the feature flag, giving each flag its own independent distribution, so the same user can fall inside the rollout for one flag and outside it for another." Without it, the same 10% of users would get every new feature first. We'll see that go wrong in the mistakes section below.

The small first group has a name: the canary. Google's SRE Workbook explains the word: "The term canarying refers to the practice of bringing canaries into coal mines to determine if the mine is safe for humans." The small bird got sick from bad air before the miners did. Canarying started as a way to deploy new code to a small part of a service first: "We define canarying as a partial and time-limited deployment of a change in a service and its evaluation." A percentage rollout does the same thing for a feature, without a new deploy. Our canary is the 10%: if the new checkout has a bug, 10% of shoppers meet it instead of all of them, and the team sees it in the error rates before going further. The same chapter makes the link to flags (a binary release is a new build of the program being deployed): "Feature flag or experiment frameworks like Gertrude, Feature, and PlanOut allow you to separate feature launches from binary releases."

What is a kill switch?

A kill switch turns a feature off for everyone, at once, while the app keeps running. Every flag's off switch works as one, as the on field did in our demo. Some teams also keep separate kill-switch flags in the code for good, so the people running the app can turn heavy extras off in an emergency. Pete Hodgson's article: some systems keep "a small number of long-lived "Kill Switches" which allow operators of production environments to gracefully degrade non-vital system functionality when the system is enduring unusually high load." (To gracefully degrade means to switch off the extras so the important parts keep working.) His own example is a shop: "I consulted with an online retailer that maintained Ops Toggles which could intentionally disable many non-critical features in their website's main purchasing flow just prior to a high-demand product launch."

For our shop, that could mean switching off "people who bought this also bought" and live delivery estimates on a sale day, so the database spends its time on orders. Two rules make a kill switch work. It must be checked before every other rule, as in our is_on. And the old path it falls back to must still work, which is why you don't delete the old checkout until the new one has been fully on for a while.

What mistakes do beginners make with feature flags?

1. A coin toss on every visit. The quick way to show a feature to "10% of users" is random.random() < 0.10. But that tosses a new coin on every page view, so the same shopper sees the new checkout, then the old one, then the new one. Their basket might be built for one and paid for in the other.

2. Leaving the flag's name out of the hash. It looks fine for one flag. But then a shopper's bucket depends only on their id, so every flag's first 10% is the same group of shoppers.

Let's measure both mistakes. Save this next to flags.py:

# mistakes.py
"""Two ways to pick "10% of shoppers" that look right and aren't."""
import hashlib
import random

from flags import bucket

random.seed(1)                                   # so you get the same numbers as we did
shoppers = [f"user-{n}" for n in range(1, 10_001)]


def coin_toss(user_id):                          # mistake 1: a fresh coin toss on every visit
    return random.random() < 0.10


changed = sum(coin_toss(s) != coin_toss(s) for s in shoppers)
print(f"coin toss: {changed} shoppers saw a different checkout on their second visit")
changed = sum((bucket("new-checkout", s) < 10) != (bucket("new-checkout", s) < 10) for s in shoppers)
print(f"bucket:    {changed} shoppers saw a different checkout on their second visit")


def bucket_without_flag(user_id):                # mistake 2: the flag's name is left out of the hash
    digest = hashlib.sha256(user_id.encode()).digest()
    return int.from_bytes(digest[:4], "big") % 100


both = sum(bucket_without_flag(s) < 10 for s in shoppers)
print(f"without the flag's name: {both} shoppers are in both 10% tests")
both = sum(bucket("new-checkout", s) < 10 and bucket("dark-mode", s) < 10 for s in shoppers)
print(f"with the flag's name:    {both} shoppers are in both 10% tests")
$ python mistakes.py
coin toss: 1810 shoppers saw a different checkout on their second visit
bucket:    0 shoppers saw a different checkout on their second visit
without the flag's name: 1031 shoppers are in both 10% tests
with the flag's name:    89 shoppers are in both 10% tests

With the coin toss, 1,810 of 10,000 shoppers flipped between checkouts from one visit to the next. That's what the sums predict: a shopper flips if one toss is in and the other is out, which happens 2 × 0.1 × 0.9 = 18% of the time. The bucket gave 0. With no flag name in the hash, every flag's 10% is the same 1,031 shoppers, so every one of them is in both tests: the same small group gets every new feature first, every bug first, and a test of dark mode is muddled by the new checkout. With the name, 89 shoppers were in both, close to the 1% (10% of 10%) you'd expect by chance.

3. Using Python's built-in hash() for buckets. hash("user-42") % 100 looks like a neat shortcut, and it gives the same number every time you call it in one run. But Python's docs: "By default, the __hash__() values of str and bytes objects are "salted" with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python." So every restart, and every server, would put the shopper in a different bucket. That's why bucket uses hashlib, which gives the same answer on every machine.

4. Never deleting old flags, and reusing their names. A flag stays in the code after its feature is fully on, then another, and soon there are hundreds of ifs nobody dares remove. The article on Martin Fowler's site: "Savvy teams view their Feature Toggles as inventory which comes with a carrying cost, and work to keep that inventory as low as possible." Old flags are worse than clutter when someone reuses one.

What that can cost is on record, in an order from the SEC, the US market regulator. Knight Capital, an American trading firm, had a system called SMARS that sent share orders to the stock exchanges. In the last days of July 2012, Knight copied new code onto its SMARS servers for RLP, a new New York Stock Exchange program starting on 1 August. Old code was still in the system: "This unused code previously had been used for functionality called "Power Peg," which Knight had discontinued using many years earlier." And "The new RLP code also repurposed a flag that was formerly used to activate the Power Peg code." Then: "During the deployment of the new code, however, one of Knight's technicians did not copy the new code to one of the eight SMARS computer servers."

So on 1 August the same flag meant "new code" on seven servers and "old code" on the eighth: "However, orders sent with the repurposed flag to the eighth server triggered the defective Power Peg code still present on that server." The old code no longer knew when to stop, and that server "continuously sent child orders, in rapid sequence" (a child order is one of the smaller orders a big order is split into). It went on for about 45 minutes, and Knight was left with huge trades it never meant to make: shares bought, and shares sold, by mistake. "Ultimately, Knight lost over $460 million from these unwanted positions." Delete a flag's code when you're done with it, and give every new feature a new flag name.

Simple habits keep the count down. "Some teams have a rule of always adding a toggle removal task onto the team's backlog whenever a Release Toggle is first introduced." Others go further: "Some go as far as creating "time bombs" which will fail a test (or even refuse to start an application!) if a feature flag is still around after its expiration date."

5. Flag checks everywhere. If the new checkout has 30 ifs scattered through it, removing the flag means finding all 30. Martin Fowler's advice: "Don't try to protect every code path in the new feature code with a flag, focus on just the entry points that would lead users there and toggle those entry points." For the shop, that's one check where the basket's "Checkout" button decides which checkout page to open. For a flag that will stay a long time, the article suggests going further: "A more maintainable alternative is to implement alternative codepaths using some sort of Strategy pattern", which is the pattern from our strategy pattern post: pick the old or new checkout object once, and the rest of the code just uses it.

6. Testing only with the flag on. Until the flag is removed, both paths are live code, so both need tests. And flags multiply: "With multiple toggles in play we have a combinatoric explosion of possible toggle states." Ten on/off flags make 1,024 combinations. You don't need all of them. Pete Hodgson's rule: "It's most important to test the toggle configuration which you expect to become live in production, which means the current production toggle configuration plus any toggles which you intend to release flipped On."

When shouldn't you use a feature flag?

  • For a small change you can just ship. Fixing a typo or a colour doesn't need a flag. Every flag adds a second path to test and a removal task later.
  • As a substitute for access control. As we saw with permission flags, a flag decides who sees a feature, not who may read whose data.
  • To hide a database change. A flag can switch code paths in a second, but it can't undo a column you dropped. Change the database in safe steps, as in the "expand and contract" pattern from the database migrations post, and flag the code that uses the new column.
  • When the setting never changes while the app runs. If a value is set once per environment, such as the database's address, it's configuration, not a flag.
  • When a dashboard is more than you need. A flag still splits deploy from release even when its rules live in a file kept with the code: the code ships switched off, and a later, small deploy flips it. The article on Martin Fowler's site prefers that simplest place: "Managing toggle configuration via source control and re-deployments is preferable, if the nature of the feature flag allows it." Keep runtime switches, like our reload, for flags that must change in seconds, such as kill switches.
  • When nobody will clean it up. If the team can't name who removes the flag and when, it will still be there in two years.

When you outgrow a JSON file, there are flag services that store the rules, show a dashboard and push changes to every server. OpenFeature's glossary lists the options: "Flag management systems may include SaaS feature flag vendors, custom "in-house" feature flag infrastructure, or open-source implementations." (SaaS, software as a service, means a product you use over the internet and pay for by subscription.) OpenFeature itself is a standard way for code to ask any of them, so you can switch services without rewriting every is_on.

1) In flags.py, move the two lines of the named-users check above the kill switch check. Run rollout.py again (with the original flags.json). What does step 3 print now, and why is that bad in an emergency?

2) Run this line twice in a terminal: python -c "print(hash('user-42') % 100)". Do you get the same number both times? What does that mean for a flag that uses it?

3) After step 3, the team fixes the payment bug, switches the flag back on and sets it to 10%. Do the same 1,020 shoppers get the new checkout, or a new 10%? Add two lines to the end of rollout.py to find out.

Show the answers

1) Step 3 prints shoppers who get it: 0, asha: True. Shoppers are switched off, but Asha, a named user, still gets the broken checkout. In an emergency, a kill switch has to turn the feature off for everyone, including the team and any test or partner accounts that are named in the rules, or the broken path stays live for them. That's why the kill switch check comes first.

2) Almost always, two different numbers. Python salts hash() for text with a new random value each time it starts, so the same shopper gets a different bucket after every restart, and different buckets on different servers. Use hashlib, as bucket does.

3) The same shoppers. Add these lines to the end of rollout.py:

change("new-checkout", on=True, percent=10)
print("5) back on at 10%, the same shoppers as step 1:", who_gets("new-checkout") == first)

It prints 5) back on at 10%, the same shoppers as step 1: True. Each shopper's bucket depends only on the flag's name and their id, so 10% means the same 1,020 shoppers every time. Shoppers who had the new checkout at 25% but are above bucket 9 go back to the old one.

Questions people ask

What is a feature flag?

A feature flag is a switch in the code that turns a feature on or off without a new deploy. The code asks "is this on for this user?", and the answer comes from rules the team can change at any time, in a file, a database or a flag service. It lets a team ship code switched off and release it later, to a few users at first.

What is the difference between a feature flag and a config setting?

A config setting, such as a database address, is set once for each environment and rarely changes while the app runs. A feature flag decides whether a feature is on, can change while the app runs, and often gives different answers for different users. Most flags are also temporary and should be removed once the feature is fully on.

How does a percentage rollout work?

Each user gets a fixed number from 0 to 99, made by hashing the flag's name and the user's id. A 10% rollout gives the feature to users whose number is 0 to 9. Because the number never changes, the same users stay in when you raise the percentage, and nobody flips between the old and new versions.

What is a kill switch in software?

A kill switch is a feature flag that turns a feature off for everyone, at once, while the app keeps running. Teams use it to switch off a new feature that is causing errors, or to turn off extras such as recommendations when the site is under heavy load. It must be checked before every other flag rule.

Are feature flags the same as A/B testing?

A/B testing is one use of feature flags. An experiment flag splits users into fixed groups, shows each group a different version, and the team compares how each group behaves. Feature flags are also used for slow rollouts, kill switches and premium features, which aren't experiments.

Keep going

  • Previous in this System Design series: "Cursor pagination", how to page through a long list without skipping or repeating rows.
  • Next: "Observability: logs, metrics, traces", how to see what a running app is doing, so you can tell when a rollout is going wrong.
  • Related: Strategy pattern, the clean way to swap the old and new code a long-lived flag chooses between, and Database migrations, for the changes a flag can't undo.

Checked on 29 November 2026 against the 11 sources below.

Sources

Every Python sample in this post was run in Python 3.13 before publishing, on 29 November 2026.