Skip to content

Module 05 · Lesson 5.4

Feature Flags and Staged Rollout

40 minUpdated 19 Nov 2026Part of Implementing Changes in an Existing Codebase · Existing Project Engineering
On this page
  1. What you will learn
  2. What a feature flag is, and why use one
  3. Worked scenario: the MIN_ORDER_VALUE_SOURCES flag
  4. A staged rollout plan, with a way back
  5. Step-by-step workflow
  6. Flag debt, limits and tools
  7. Using an assistant for flag work
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

A good electrician fits the light switch before the bulb goes in. The new light can then be turned on when the room is ready, and turned off at once if it flickers. A feature flag does the same job for software. The new code is shipped, but it stays off until you choose to switch it on.

In this lesson you put the minimum order value rule behind a flag, plan a rollout in stages, and prepare the way back. The example continues with the fictional Tidewell Wholesale, after Directing an Assistant on a Bounded Task. The company and data are invented.

What you will learn

  • Explain a feature flag, a staged rollout and a rollback in plain words.
  • Add a flag that is off by default and test both the off and on states.
  • Plan rollout stages with a clear owner, a signal to watch and a way back for each.
  • Plan to remove the flag after the rollout, so it does not become clutter.

Before you start

What a feature flag is, and why use one

Without a flag, the moment your code is deployed, every customer gets the new behaviour. If it is wrong, the only way back is to deploy again, under pressure. A flag separates two things that are usually tied together: putting code live, and turning behaviour on.

Feature flag
A setting that switches a behaviour on or off without changing the code. Like a light switch fitted before the bulb: the wiring is there, and you decide when the light comes on.
Staged rollout
Switching a change on for a small part of the users first, then more, like opening a new shop to a few guests before the grand opening.
Rollback
Going back to how things were before. With a flag, it means switching the behaviour off, which is quicker than undoing code.
Flag debt
The clutter left when a flag stays in the code after its job is done. Each leftover flag is an extra path that someone must understand and test.
Default
The value used when nobody has chosen. A good flag defaults to off, so forgetting to set it is harmless.
Kind of flagPurposeLives for
Release flagShip code now, switch it on later, in stagesDays to weeks. Remove after rollout.
Kill switchTurn a risky part off fast in an emergencyLong. Kept on purpose.
Experiment flagShow two versions to compare resultsUntil the result is clear.
Permission flagGive some customers a paid or special featureLong. It is part of the product.
Four common kinds. This lesson uses the first.

Worked scenario: the MIN_ORDER_VALUE_SOURCES flag

The rule must reach the portal first, and EDI customers only after they have been told. EDI customers are larger customers whose own systems send orders. A sudden rejection could break their automatic process. So you want a switch that says which order sources the rule applies to.

The flag is a setting called MIN_ORDER_VALUE_SOURCES. It is a set of source names. An empty set means the rule is off. This is the default, and it lives in the base settings file.

Pythontidewell/settings/base.py
# Order sources that the minimum order value rule applies to.
# An empty set means the rule is off. Valid sources: "portal", "edi".
MIN_ORDER_VALUE_SOURCES = set()

The default: off. A setting file in the style of Django. Not run here.

In the real Django service, create_order would read the setting itself. This is an excerpt of that idea and is not run. The simplified version you can run takes the same set as an argument.

Python
from django.conf import settings

def create_order(customer, lines, source):
    ...
    enabled_sources = settings.MIN_ORDER_VALUE_SOURCES
    if source in enabled_sources and ...:
        ...

Excerpt for the real service (Django). Not run; shown to explain where the setting is read.

And here is the check in the simplified code you can run. The first line of the condition is the flag.

Pythonorders/services.py
if (
    source in min_order_sources
    and source not in EXEMPT_SOURCES
    and customer.band.lower() == "standard"
    and totals["goods"] < MIN_ORDER_VALUE
):

The guard of the rule, lines 34 to 39 of the finished file.

What each part does

  • source in min_order_sources is the flag. If this order's source is not in the set, the rule does nothing.
  • The default for min_order_sources is an empty set (frozenset()), so the rule is off unless someone turns it on.
  • source not in EXEMPT_SOURCES is separate from the flag. It protects replay orders even if the flag is set wrongly.
  • The band and amount checks come after. They only run when the flag has already said yes.

You test the flag in both states. The first test shows the default is off. The second shows stage one: only the portal is switched on, so an EDI order for the same small basket still goes through.

Pythontests/orders/test_services.py
def test_rule_is_off_when_no_sources_are_enabled(
    make_customer, low_basket, store, stock
):
    create_order(make_customer(), low_basket, "portal", stock=stock, store=store)
    assert len(store.saved) == 1


def test_stage_one_enables_the_portal_only(make_customer, low_basket, store, stock):
    stage_one = frozenset({"portal"})
    with pytest.raises(OrderRejected):
        create_order(
            make_customer(), low_basket, "portal",
            stock=stock, store=store, min_order_sources=stage_one,
        )
    create_order(
        make_customer(), low_basket, "edi",
        stock=stock, store=store, min_order_sources=stage_one,
    )
    assert len(store.saved) == 1

Two flag tests.

pytest on the finished change (real run; timings vary)Captured from a real run
................                                                         [100%]
16 passed in 0.07s

A staged rollout plan, with a way back

A rollout plan is a short table. For each stage it says what is switched on, who decides to move on, and what you watch. A stage ends when the watcher says the signal is quiet, not when a date arrives.

StageSettingMoves on whenWhat to watch
0. Merged, offset()Tests pass and the change is releasedNothing changes for customers. Check that orders still flow.
1. Portal{"portal"}Sales operations manager agrees, after a few days of normal tradingHow many orders are rejected. Whether support hears from customers.
2. Portal and EDI{"portal", "edi"}EDI customers have been told, and support is readyLog lines for rejected EDI orders, with account codes. Calls from EDI customers.
3. Remove the flagCode changeStage 2 has been calm for an agreed timeTests still pass without the switch.
The rollout plan for the minimum order value rule. Roles, not people, decide.

Each stage is a one-line change to a settings file, so it shows up clearly in history. This is the real log of the settings file in the scratch repository. The dates are close together only to keep the example short. A real stage would last days or weeks.

Rollout history of the settings file (real)Captured from a real run
$ git log --format="%h %ad %s" --date=short -- tidewell/settings/production.py
49355a5 2026-11-18 Enable the minimum order value for EDI orders
2c31804 2026-11-17 Enable the minimum order value for the portal
Stage 2 as a diff (real)Captured from a real run
diff --git a/tidewell/settings/production.py b/tidewell/settings/production.py
index b5042f5..2e89276 100644
--- a/tidewell/settings/production.py
+++ b/tidewell/settings/production.py
@@ -1,3 +1,3 @@
 from .base import *  # noqa: F401,F403
 
-MIN_ORDER_VALUE_SOURCES = {"portal"}
+MIN_ORDER_VALUE_SOURCES = {"portal", "edi"}

The way back

Rollback is the same kind of one-line change, in the other direction. Switch the set back to empty and the rule is off again. Orders that were rejected while it was on are not saved, so customers must place them again.

Rollback as a diff (real, not committed)Captured from a real run
diff --git a/tidewell/settings/production.py b/tidewell/settings/production.py
index 2e89276..d637646 100644
--- a/tidewell/settings/production.py
+++ b/tidewell/settings/production.py
@@ -1,3 +1,3 @@
 from .base import *  # noqa: F401,F403
 
-MIN_ORDER_VALUE_SOURCES = {"portal", "edi"}
+MIN_ORDER_VALUE_SOURCES = set()

Step-by-step workflow

  1. Step 1: Decide what the flag switches

    Name the behaviour in one sentence. Pick a name that says what it does, such as MIN_ORDER_VALUE_SOURCES, not NEW_RULE_2.

    What you should see: A flag name and a sentence on what it controls.

  2. Step 2: Choose a safe default

    The default should be the old behaviour, so that forgetting to set it changes nothing.

    What you should see: A default of off.

  3. Step 3: Read the flag in one place

    Check it at a single point in the code, close to the rule. Spreading checks around makes it hard to remove later.

    What you should see: One condition that guards the new behaviour.

  4. Step 4: Test off and on

    Write a test for the default, a test for each stage and a test for any group that must never be affected.

    What you should see: Tests that name each state.

  5. Step 5: Write the rollout plan

    List the stages, who decides, what to watch and how to roll back. Share it with support and the people who talk to customers.

    What you should see: A short plan that others have read.

  6. Step 6: Roll out one stage at a time

    Change the setting for one stage, watch the signal, and only then move on. Record the date and the person's role who agreed.

    What you should see: A history of one-line changes.

  7. Step 7: Remove the flag

    When the rollout is complete and calm, delete the flag and the old path in a small change of its own.

    What you should see: A simpler codebase and no leftover switch.

A staged rollout
  1. Off

    Merged and released

  2. Portal

    Stage 1

  3. Portal and EDI

    Stage 2

  4. Flag removed

    Cleanup change

Each arrow is a one-line settings change. The way back is always to the left.

Flag debt, limits and tools

Every flag doubles the number of ways the code can behave. Two flags give four combinations, and three give eight. That is why release flags need an end date. Put a ticket in the plan: 'remove MIN_ORDER_VALUE_SOURCES after stage 2 is calm'. Then do it.

  • A flag in a settings file is all-or-nothing for each source. You cannot turn the rule on for one customer only.
  • It needs a deploy or restart to change.
  • It is visible in version history, which is a plus: you can see who changed what and when.
  • For per-customer or percentage rollouts, you need something richer.

There are many tools for richer flags. Some are libraries for your framework, such as django-waffle for Django. Some are hosted services. OpenFeature is an open standard for flag code, so that you can change the provider later. This lesson does not recommend one. Pick by your needs, check how current each tool is and read its documentation first. See Feature Toggles (aka Feature Flags) (opens in a new tab) for a longer discussion.

Using an assistant for flag work

Assistants are good at the plumbing: reading a setting, adding a default and writing tests for each state. They are less careful about what 'off' means. Give them the default and the groups that must never be affected, and ask for the tests too.

  • Check the default. An inverted flag, where the old behaviour needs the flag on, is a common mistake.
  • Check that the flag is read in one place, not copied into several functions.
  • Check that 'off' leaves old behaviour untouched. Run the old tests with the flag off.
  • Ask for a rollout table and a removal plan, and edit them with the people who will run the stages.
  • Never accept a claim that a flag is 'safe'. Look at the tests that show it.

The assistant cannot decide who must be told before stage two. That is a conversation with people, such as the sales operations manager and the support engineer.

Conclusion and your next step

You fitted the switch before the bulb. The rule is off by default, it can be turned on source by source, and it can be turned off again with a one-line change. You also planned its removal so that the switch does not stay for ever.

Your next step: now package the work for a reviewer. Continue with Writing a Reviewable Pull Request and describe scope, risk, test evidence and rollback in one page.

Further reading: the module overview Implementing Changes in an Existing Codebase, and the blog post Legacy Modernization with AI: The Strangler Fig Pattern, which uses the same idea of switching between old and new.

Reusable prompt

Flag and rollout planner

Asks an assistant to draft a flag design, tests and a staged rollout table for a change, with unknowns labelled.

I am adding a feature flag to an existing Python service so that a new rule can be switched on in stages. I will decide the rollout myself. Act as a careful assistant, not as the decision maker.

The rule: reject orders from Standard-band customers whose goods total is below 75.00, before VAT and delivery.
Sources of orders: portal, edi, replay. Replay is always exempt.
Stage 1: portal only. Stage 2: portal and edi, after EDI customers are told.
Rollback: switch the rule off.

Flag idea: a setting MIN_ORDER_VALUE_SOURCES, a set of source names. An empty set means off.

Below is the source of create_order. Use ONLY this code.
(paste source)

Produce:
1. The smallest change that adds the flag, as a diff. Read the flag in one place only. Default to off.
2. The tests I need: one for off, one for each stage, one for the exempt source.
3. A rollout table: stage, setting, who decides (a role), what to watch, how to go back.
4. A plan to remove the flag, and what to delete.
5. Anything you could not know, for example how settings reach production or how long a change takes to go live.
Show the reusable template

Replace each {{placeholder}} with your own details.

I am adding a feature flag to an existing {{language}} service so that a new rule can be switched on in stages. I will decide the rollout myself. Act as a careful assistant, not as the decision maker.

The rule: {{the_rule}}
Sources or groups it applies to: {{sources_or_groups}}
Always exempt: {{exempt_sources}}
Stages: {{stages}}
Rollback: {{rollback}}

Flag idea: {{flag_name_and_type}}. {{what_off_means}}

Below is the source of {{function_to_change}}. Use ONLY this code.
{{source}}

Produce:
1. The smallest change that adds the flag, as a diff. Read the flag in one place only. Default to off.
2. The tests I need: one for off, one for each stage, one for the exempt source.
3. A rollout table: stage, setting, who decides (a role), what to watch, how to go back.
4. A plan to remove the flag, and what to delete.
5. Anything you could not know, for example how settings reach production or how long a change takes to go live.

Expected output and limitations

A small diff with the flag read in one place and defaulting to off; a list of tests by state; a rollout table with roles; a removal plan; and a list of things it could not know.

Sample responseIllustrative — your output will differ
Diff (summary)
- tidewell/settings/base.py: MIN_ORDER_VALUE_SOURCES = set()   (default off)
- orders/services.py: guard the rule with  source in min_order_sources  and  source not in EXEMPT_SOURCES

Tests
- test_rule_is_off_when_no_sources_are_enabled
- test_stage_one_enables_the_portal_only
- test_replay_orders_are_exempt (replay is accepted even if it is in the set)

Rollout table
Stage 1 | {"portal"} | decided by: sales operations manager | watch: rejection count, support contacts | back: set()
Stage 2 | {"portal", "edi"} | decided by: sales operations manager and support engineer | watch: EDI rejection log lines | back: set()

Removal plan
- After stage 2 is calm, delete the setting and the "source in min_order_sources" test, and keep the rule.

Could not know
- How a settings change reaches production and how long it takes.

Limitations to keep in mind

  • It cannot tell how your settings reach production or how fast a change takes effect.
  • A rollout table is a draft. The people who run each stage must edit it.
  • A flag that looks safe may still hide a bug. Only tests for both states show it.
  • The assistant may suggest a tool or service. Treat that as an option to research, not a recommendation.

Common errors and how to fix them

A flag that defaults to on, or an inverted flag

Why it happens: The flag was named for the new behaviour but wired the wrong way round.

Fix: Default to the old behaviour. Write a test for the default and run the old tests with the flag off.

Checking the flag in many places

Why it happens: Each place that touched the new behaviour got its own check.

Fix: Read the flag at one point, close to the rule, so that it can be removed in one small change.

Leaving the flag in for ever

Why it happens: The rollout finished, but nobody owned the cleanup.

Fix: Put the removal in the rollout plan with an owner. Remove the flag and the old path in a small change of its own.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Add a flag and plan a rollout in your repository

Take a small change in a repository you may work on. Put it behind a flag that defaults to off, test both states and write a short rollout plan with a rollback and a removal step.

You will need

  • A small change you are allowed to make, such as a new validation rule.
  • The test suite for the code, with a way to run it.
  • The prompt template from this lesson, if your rules allow its use with your code.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • If your project has no settings system, a constant at the top of one module is enough for practice.
  • Run the old tests with the flag off. They should all pass without any change.
  • Write the rollback first. If you cannot say how to go back, the flag is not ready.
Show a model answer

A strong answer has a flag whose name describes its job and whose default changes nothing. One condition in one place guards the new behaviour. Tests name each state: off, the first stage and any group that must stay unaffected. The rollout table has a role for each decision, a concrete thing to watch, such as a count of rejected orders, and a one-line rollback. The removal step lists the setting, the condition and the tests that would be deleted. A weak answer adds checks in several places, defaults to on and has no plan to remove the flag.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.What should a new release flag default to?
    Show the answer and explanation

    Answer: B. A flag exists to let you decide when to switch behaviour on, so the safe default is the old behaviour. Defaulting to on removes the control the flag was meant to give. Personal preference is not a reason to leave the default unclear.

  2. 2.The rollout is complete and calm. What is the right next step for the flag?
    Show the answer and explanation

    Answer: B. A leftover flag adds paths that everyone must understand and test. Keeping it feels safe but is how flag debt builds up. Turning it off would put the old behaviour back, which is not what you want after a finished rollout.

  3. 3.Why is an empty set a good way to say 'rule off' in this lesson's flag?
    Show the answer and explanation

    Answer: B. The condition asks whether the order's source is in the set, so an empty set matches nothing and the old behaviour stays. Speed does not matter here, and the flag is not a Django rule.

Frequently asked questions

What is a feature flag in simple words?

It is a switch in your settings that turns a behaviour on or off without changing the code. The new code is already shipped, but it stays quiet until you flip the switch. If something goes wrong, you flip it back.

What is a staged rollout?

It means switching a change on for a small group first, then for more groups. You watch for problems between steps. It is like opening a new shop to a few guests before the main opening.

Do I need a special tool for flags?

Not at first. A setting in a configuration file is enough for a simple on or off switch. Tools help when you need per-customer rollouts or changes without a deploy, so look at them when those needs appear.

When should I remove a flag?

As soon as the rollout is complete and has been calm for the time you agreed. Delete the flag and the old code path in a small change of its own. A flag left behind becomes clutter that confuses the next developer.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.