What you'll learn: By the end of this lesson you will be able to explain what a feature flag is and which of the four common kinds you are using, describe how a flag is evaluated from a definition and a context, build a deterministic percentage rollout that only ever adds users, split traffic for an A/B test without reshuffling people when traffic grows, choose where a flag is evaluated (browser, server or edge) and what each choice costs, and say why an experiment needs more than a flag: exposure logging and a sample ratio check.
Think of a restaurant trying a new menu. First only the staff taste it. Then a few tables get it, then a quarter of the room, then everyone. If it goes badly, the manager swaps it back without rebuilding the kitchen. For a real experiment the restaurant does something stricter: each table is handed the old or the new menu by a fixed rule, a table always gets the same menu on every visit, and the restaurant compares what each group ordered. A feature flag is the swap-back switch and the dimmer. An A/B test adds the fixed rule and the comparison.
The running example is the product page of a shop that wants to ship a new checkout button. Part of the lab is the code that decides, for each visitor, whether they see it. The shop, the users (user-0 to user-9999) and every number in the lab are made up for the lesson.
The core idea
- A flag is a decision made at run time, not at build time. The code contains both paths, and a rule held outside the code chooses one. That separates deploying code (putting it on servers or in the bundle) from releasing it (letting users see it).
- Who gets what is a pure function of a flag definition and a context. Given the same definition and the same context, the answer is always the same. Rules, percentages and splits are all arithmetic on that input, so they can be tested without a network.
- An experiment is a flag plus a measurement. The flag assigns people to arms; the measurement counts what each arm did. Assignment, exposure and analysis can each go wrong in ways that make the result look fine and be wrong.
Three illustrations run through the lesson: a minimal example (one on/off flag with a safe fallback), a realistic example (the shop's checkout button behind rules, a ramp and a 50/50 test) and a failure example (two experiments that share a salt, and an experiment whose arms stop matching their configured split).
Four kinds of flag
Not every flag is the same animal. Martin Fowler's article on feature toggles names four categories, and the differences are mostly about how long the flag lives and how often its answer changes.
| Kind | Purpose | Typical lifetime | How the answer varies |
|---|---|---|---|
| Release | Merge unfinished work and turn it on when ready | Short: the article says to remove it within a week or two, though product-led ones may last longer | Mostly static: on for everyone once released |
| Experiment | Show different people different versions and measure | Long enough to collect results, then removed | Highly dynamic: per user, held steady for the test |
| Ops | Control operational behaviour, including kill switches | Mostly short, with some long-lived kill switches | Changed quickly by operators |
| Permission | Give features to some users, such as a paid tier | Can last for years | Decided per request |
The lesson's lab is mostly about the second row, and about release rollouts that use the same arithmetic. The same article describes flags as inventory that carries a cost, which is why the next lesson in this course, on flag lifecycle and experiment pitfalls, is about removing them.
Anatomy of an evaluation
Figure 1. A flag is configuration that travels to a small evaluator
How to read this: the flag service holds definitions and is not on the path of each decision. The evaluator is a plain function. Analytics hears about a variant only when the page actually shows it.
The vocabulary below follows the OpenFeature specification, a vendor-neutral standard for flag evaluation APIs. The lab borrows its names; it is a model written for the lesson and does not implement that standard or any product.
- Evaluation context. The OpenFeature specification defines it as the ambient information used for flag evaluation: who the user is, which application, which host. Rules and splits read from it.
- Targeting key. An optional string that, in the specification's words, uniquely identifies the subject of an evaluation, such as a user or a client service. Some providers need it for rules, overrides or percentage splits, and may behave unpredictably without it. In a browser it is a user id once signed in, or an anonymous id kept in a cookie or
localStoragebefore that. MDN notes thatlocalStoragedata persists across browser sessions and belongs to one origin. - Default value. The specification requires every evaluation call to carry a default, and says the call must return it on abnormal execution. The caller chooses it, at the call site, so the call site is where "what is safe if everything fails" is decided.
- Resolution details. Besides the value, an evaluation returns the variant name, a reason (for example
TARGETING_MATCHfor a rule,SPLITfor pseudorandom assignment,DISABLED,DEFAULT,ERROR) and, on failure, an error code such asFLAG_NOT_FOUND,TARGETING_KEY_MISSINGorPROVIDER_NOT_READY. The reason is what makes "why did this user see that?" answerable.
Evaluation in the lab runs in a fixed order, and the order is part of the behaviour.
Figure 2. How one flag is evaluated
exists?"} K -->|"no"| E1["Fallback
ERROR: FLAG_NOT_FOUND"] K -->|"yes"| D{"Enabled?"} D -->|"no"| O1["Off variant
DISABLED"] D -->|"yes"| R{"A rule
matches?"} R -->|"yes, first one"| M["Rule's variant
TARGETING_MATCH"] R -->|"no"| P{"Rollout
defined?"} P -->|"no"| O2["Off variant
DEFAULT"] P -->|"yes"| T{"Targeting
key present?"} T -->|"no"| E2["Fallback
ERROR: TARGETING_KEY_MISSING"] T -->|"yes"| H["Hash the key
(next section)"]
How to read this: rules come before the rollout, so a rule such as "staff always see it" needs no targeting key. A flag that is off beats everything, which is what makes it a kill switch.
Two small consequences. Rules are ordered and the first match wins, so a "blocked market" rule placed before a "staff" rule hides the feature from staff in that market; section 2 of the lab prints that case in the other order. And a missing attribute is "no match", never an exception: evaluation runs on every render path, and a thrown error there is an outage.
Deterministic bucketing
A percentage rollout must answer "is this person in the 20%?" the same way every time they ask, on every device that knows who they are, without a database of who was picked. The standard trick is hashing. Hash the targeting key together with the flag's name (a salt) into a number, reduce it to a bucket from 0 to 9,999, and compare the bucket with a threshold: 20% is "bucket below 2,000". Same input, same bucket, every time.
Vendors describe the same idea. The Unleash documentation says its gradual rollout uses a normalized MurmurHash of a user's unique ID so the distribution is consistent and random, and that the field used is the stickiness field: by default the first available of userId and sessionId. It also says that if neither is available, the calculation returns a random number and stickiness is not guaranteed. That is the same failure the lab reports as TARGETING_KEY_MISSING, handled differently: this model refuses to guess and returns your fallback.
Figure 3. From key to arm, with two independent hashes
bucket 0 to 9999"] H1 --> C{"bucket below
threshold?"} C -->|"no"| OFF["Off variant"] C -->|"yes"| H2["hash(salt + variant)
point 0 to 100"] H2 --> ARM["Arm by cumulative
weights"]
How to read this: the first hash decides if you are in; the second decides which arm. They are separate on purpose, as the next paragraphs show.
Four properties follow from doing it this way, and each has a line in the lab's output.
- Stable. Section 1: the same salt and key give bucket 6,815 twice; another salt gives another bucket for the same key.
- Monotonic ramp. Because "inside" means "bucket below the threshold", raising the percentage only adds keys. Section 3 ramps 1%, 10%, 50%, 100% over 10,000 keys and counts zero keys leaving between steps. Without this property a ramp from 10% to 20% could drop some early users, who would see the feature disappear.
- Arms do not move when traffic grows. If the arm were cut out of the included range (the first 20% of buckets split in half), widening the range would change where the halves fall and users would switch arms mid-test. With a second hash, section 4 raises the allocation from 20% to 40% and counts zero keys that changed arm. Switching arms contaminates both groups with people who saw both.
- Salt per flag. Section 5 puts two 50/50 experiments on the same salt: every user lands in the same arm of both (cells
A+BandB+Aare 0). Their results are tangled together and neither is measuring only its own change. With different salts the four cells are close to a quarter each.
The model's hash (FNV-1a followed by a bit-mixing step) is not the hash of any vendor. The properties above do not depend on which good hash is used; the exact buckets do.
Where the flag is evaluated
The same definition can be evaluated in three places, and the choice shapes both the user experience and the numbers.
| Place | How it works | Good for | Costs |
|---|---|---|---|
| Browser, after load | A script fetches flags and applies them | Fast to set up; late, per-user changes | The page can show the old version first and then swap; scripts that hide content until ready delay what the user sees |
| Server, per request | The server evaluates and renders the variant into the HTML | No flash; first paint is already right | Cache keys must include the variant; needs the targeting key on the request |
| Edge or CDN | Evaluate at the edge and pick a variant of the page | Fast and no flash | Same cache-key problem, plus logic split across systems |
The web.dev guidance on site speed and business metrics makes the speed case: it strongly recommends a server-side test over a client-side one, because client-side testing often works by hiding page content until the experiment has loaded, which skews the very metrics you want to measure. It also says server-side splitting often needs IT resources to set up and that client-side tools are easy to set up and maintain.
Figure 4. Where to evaluate
what first paint shows?"} -->|"yes"| S["Evaluate on the server
or edge, render the variant"] Q -->|"no"| B{"Would a late swap
move content?"} B -->|"yes"| S B -->|"no"| C["Evaluate in the browser
after load"] S --> V["Put the variant in the cache key
and pass the value to the client"]
How to read this: first-paint changes belong where the HTML is made. Browser evaluation is for what happens after the page is already stable.
Two details matter when the server renders the variant. A cache has to store separate copies per variant: the HTTP Vary header "describes the parts of the request message... that influenced the content of the response", and caches store separate responses based on the headers it lists (MDN). The page also has to hand the evaluated values to client code, rather than letting the browser evaluate again and possibly disagree with the HTML; see Debugging Hydration Mismatches for what a disagreement costs, and CDN and Edge Caching for cache keys.
From flag to experiment
An A/B test has a hypothesis, an assignment, an exposure and an analysis. The flag only gives you the second.
Figure 5. What happens for one visitor in an experiment
How to read this: assignment happens at the evaluator; exposure is the page saying "this person really saw it". Analysis should start from exposures.
Assignment is not exposure. Everyone who is evaluated is assigned; only those who reach the changed part of the page are exposed. Counting assignments includes people who never saw the change and dilutes any effect. The lab's ExposureLog counts a key once per flag, however many times the page re-renders.
Check the split before the outcome. A sample ratio mismatch (SRM) is, in Microsoft's description, a statistically significant difference between the ratio of users counted in the variants and the ratio that was configured. A raw comparison of two counts ignores sample size, so the detection uses a statistical test such as chi-square, and the Microsoft platform described uses a p-value below 0.0005 as its conservative cutoff. The article lists causes at every stage: bad bucketing, redirects in one arm, faulty joins, biased analysis conditions, and bot filters that remove users by their behaviour in a variant. The lab's section 7 builds a case like the logging one: part of one arm never gets its exposure logged.
Do not peek. Evan Miller's well-known write-up argues that checking significance repeatedly and stopping when it first looks significant makes the reported significance meaningless. His example is that peeking at an experiment ten times turns what you think is 1% significance into about 5%. The advice is to fix the sample size before starting and wait for it. The next lesson covers this and other traps in more detail.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Hash-based percentage rollout | No stored assignments; same answer everywhere the key is known | Needs a stable targeting key; a changed key changes the bucket |
| Rules before the rollout | Staff and exceptions always work | Rule order becomes behaviour that must be reviewed |
| Two hashes (inclusion, arm) | Ramps and arms are stable | Slightly more to explain and test |
| Server or edge evaluation | No flash, right first paint | Cache variants, a request-time key, more moving parts |
| Browser evaluation | Quick to adopt | Flicker or hidden content, extra script on the critical path |
| Fallback chosen at the call site | Safe by design when the service is down | Every call site must choose well |
Build it: bucketing, rules, ramps and a sample ratio check
Goal. Run a pure model of flag evaluation through seven situations: stable buckets, rules then a rollout, a ramp, a stable experiment split, two experiments sharing a salt, evaluation that never throws, and a sample ratio check on assignments versus exposures.
This is a model, not a flag vendor. The hash, the rule language and the reasons are written for this lesson. It has no network, no cache, no SDK, and it is not an implementation of OpenFeature or of any product. It shows the arithmetic, not how any vendor does it.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no React, no DOM, no clock, no randomness.
cd examples/frontend
pnpm install
cd labs/feature-flag-bucketing
pnpm test # 24 tests
node src/demo.ts
Steps.
- Run the tests, then the demo, and compare it with the output below.
- In section 2, read the
reasoncolumn:TARGETING_MATCHfor the two rules,SPLITfor a user the 20% rollout includes,DEFAULTfor a user it does not. The "staff, no targeting key" row still works, because rules run before the rollout asks for a key. - In section 3, check the "left since the previous step" column: it is 0 at every step.
- In section 7, compare the two rows: the assigned arms are close to 50/50 and pass, and the exposed arms do not.
Expected output, captured from a real run (Node 26.13.1, 2026-12-01):
=== 1. Bucketing is a pure function: same salt and key, same bucket
bucket of user-42 for "new-checkout": 6815
again: 6815
another key, same salt: 5355
same key, another salt: 1705
=== 2. Targeting rules run in order, then the percentage rollout (20%)
staff member -> true variant=on reason=TARGETING_MATCH rule=staff
blocked market -> false variant=off reason=TARGETING_MATCH rule=blocked-market
staff in blocked market -> true variant=on reason=TARGETING_MATCH rule=staff
staff, no targeting key -> true variant=on reason=TARGETING_MATCH rule=staff
user-1, no attributes -> true variant=on reason=SPLIT
user-3, no attributes -> false variant=off reason=DEFAULT
=== 3. Ramping up: 10,000 keys, who is inside at each percentage
1%: 103 inside, 0 left since the previous step
10%: 999 inside, 0 left since the previous step
50%: 4925 inside, 0 left since the previous step
100%: 10000 inside, 0 left since the previous step
=== 4. An experiment: 50/50 split, allocation raised from 20% to 40%
20%: control 991, treatment 1018
40%: control 2004, treatment 2018
keys that changed variant when allocation grew: 0
=== 5. Two experiments with the same salt are not independent
same salt: A+A=5077 A+B=0 B+A=0 B+B=4923
different salts: A+A=2531 A+B=2480 B+A=2481 B+B=2508
=== 6. Evaluation never throws: the caller's fallback is the safety net
unknown flag: false variant=- reason=ERROR error=FLAG_NOT_FOUND
no targeting key: false variant=- reason=ERROR error=TARGETING_KEY_MISSING
flag switched off: false variant=off reason=DISABLED
validateFlag(broken): ["rollout weights add up to 60, not 100"]
validateFlag(new-checkout): []
=== 7. Sample ratio check: assignment is fair, but exposure is not
assigned: control 5077, treatment 4923, chi-square 2.37, p 1.24e-1 -> ok
exposed : control 5077, treatment 4326, chi-square 59.98, p 9.58e-15 -> MISMATCH
What the lab does not show. No browser, no network and no real analytics. The users are strings the demo generates, so the counts depend on this hash and these keys: another hash gives other buckets and similar proportions. The chi-square p-value is implemented for two arms only, and the 12% of the treatment arm that "crashes before logging" in section 7 is a made-up mechanism chosen to show the check firing. It says nothing about how often real pages fail.
Break it. In src/flags.ts, replace the point line in resolve with const point = (bucketOf(${flag.salt}:in, context.targetingKey) / thresholdOf(flag.rollout.percent)) * 100;. The arms are now cut out of the included range, so raising the allocation moves keys between arms, and the test "keeps each key's variant when the allocation grows" fails (it reported 1001 keys changed when this was tried). Revert it.
In practice: a checkout button behind a flag
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A shop's product page has a new checkout button that the team has built over several weeks. They want to merge it now, show it to the team first, then ramp it to everyone, and finally test it against the old button for conversion. A bad release must be reversible in minutes without a deploy.
Starting architecture
Figure 6. Starting point: one flag service, two evaluation sites
How to read this: one evaluation per request, on the server, and the browser only reports what it was shown.
Options considered
| Option | What it gives | What it costs | Risk |
|---|---|---|---|
| Flag evaluated in the browser after load | Easy start | The old button shows first, then swaps | Layout shift and a skewed test |
| Flag evaluated on the server, value passed to the client | No flash, one source of truth | Cache variants, a stable targeting key on the request | A missing key on first visits |
| Deploy the new button to a few servers only | No flag system needed | Release tied to deploys, not per user | A user could see both versions across requests |
The decision
| Field | Decision record |
|---|---|
| Context | A new checkout button must be shown to staff, then a growing share, then compared with the old one. |
| Decision | Evaluate on the server. Rules first (staff always on, a blocked market always off), then a rollout. Targeting key: the user id when signed in, otherwise a first-party anonymous id cookie. The call site's fallback is the old button. |
| Consequences, good | No flash. A ramp that only adds users. A kill switch that needs no deploy. |
| Consequences, bad | The cache must store a copy per variant. Evaluation needs a key on the first request, so the anonymous id must be set before the first render. |
| Revisit when | The same visitor appears under two keys (signed out, then in), or the flag must also run in an installed app. |
Rollout and verification
- Merge behind the flag, off. Confirm the old button renders and the flag's reason is
DISABLED. - Staff only. Use the staff rule; confirm the reason is
TARGETING_MATCHfor staff and not for others. - Ramp. Raise the percentage in steps, watching errors and checkout failures. By the monotonic ramp, no one who has the new button loses it.
- Experiment. Set a 50/50 split with a fixed end date, count exposures and not assignments, and check the split before reading outcomes.
The 2 a.m. failure
The flag service has a partial outage. The page's flag client cannot fetch rules, so every evaluation falls back to the value passed at the call site. One call site, added in a hurry, passes true as its fallback, copied from a local test. For the duration of the outage, every visitor on that page gets the unfinished checkout button (illustrative). The failure is not in the flag system. It is that a fallback is a decision about what is safe, and one call site decided wrongly.
First three checks: (1) look at the reason and errorCode on the evaluations: ERROR with a provider or not-found code means the fallback is being served; (2) search the call sites for fallbacks that are not the old behaviour; (3) check whether the evaluator waited for the flag provider to be ready before the first render. Mitigation: flip the call site's fallback to the old behaviour and redeploy, and in the meantime turn the feature's kill rule off if the service is reachable. Follow-up: wrap evaluation in one helper that takes a typed fallback, add a test that every flag's call-site fallback equals its off variant, and alert on a high share of ERROR reasons.
Architect's notes
- Choose the fallback first. The fallback is the behaviour you ship if every flag system fails.
- Name the targeting key and where it comes from before writing a rule. If it can change (signed out, then in), say what happens to the bucket.
- One salt per flag, and two hashes for experiments. Shared salts tangle results; a single hash makes arms shift as traffic grows.
- Put the reason in your logs. "Which rule or which split served this?" is the question that support asks.
- Evaluate once per request or page and pass the value on. Two evaluations can disagree.
Common mistakes
- A fallback copied from a test that is not the safe, old behaviour.
- Reusing a salt between two experiments.
- Cutting arms out of the included range, so widening the rollout moves people between arms.
- A targeting key that is missing or unstable, such as a fresh random id on each visit.
- Counting assignments as exposures, which includes people who never saw the change.
- Reading outcomes before checking the split.
Key takeaways
- A flag decouples deploying from releasing; Fowler's four kinds differ in lifetime and in how the answer varies.
- Evaluation is a pure function of a flag definition and a context: rules first, first match wins, then a rollout.
- Hash the key with a per-flag salt into a bucket, compare with a threshold, and the same user always gets the same answer and a ramp only adds users.
- Use separate hashes for inclusion and for the arm so arms are stable as the allocation grows.
- Evaluate on the server or edge when the flag changes first paint, and keep the variant in the cache key.
- Assignment is not exposure. Count exposures once, and check the sample ratio before the outcome.
- The fallback is a safety decision made at the call site.
Practice exercises
Exercise 1 — Starter (45 min): Pick one real flag in a project you know. Write down its kind (release, experiment, ops, permission), its fallback, and its targeting key. If it has no owner or no planned removal, say so.
Exercise 2 — Intermediate (2 hours): In the lab, add a rule that serves on to users whose plan attribute is pro, and place it before the "blocked market" rule. Write a test showing what a pro user in a blocked market sees, and a second test with the order swapped.
Exercise 3 — Advanced (half day): Add a sticky store (key to variant) that evaluate reads first. Show what a user sees after the percentage is lowered from 50% to 10% with and without the store, and list the cost of keeping that store on the client.
Related reading
In this course:
- Local vs Global State in the Front End, where a flag's value lives once it is evaluated.
- Debugging Hydration Mismatches, what happens when the server and the browser disagree about a variant.
- CDN and Edge Caching, cache keys and variants.
- Real User Monitoring, where exposure and outcome events come from in practice.
- Cookies and Web Storage, where an anonymous targeting key can be kept.
Official documentation
- Martin Fowler: Feature Toggles, the four categories and the cost of keeping toggles.
- OpenFeature specification: evaluation context, flag evaluation, providers and types.
- Unleash: activation strategies and stickiness, one vendor's description of hash-based rollouts.
- web.dev: Relating site speed and business metrics, the server-side versus client-side testing advice.
- Microsoft Research: Diagnosing sample ratio mismatch in A/B testing and Evan Miller: How Not To Run an A/B Test.
- MDN: Vary and Window.localStorage.