On August 1, 2012, Knight Capital deployed new trading code to seven of its eight production servers. The new code reused a flag that had once switched on “Power Peg”, an order routine Knight had stopped using in 2003. On the eighth server, the old code still answered to that flag. In about 45 minutes the router sent more than 4 million orders while trying to fill 212 customer orders, and Knight lost more than $460 million, according to the SEC.
Feature flags did not cause that on their own, but reusing a flag that had outlived its purpose made it possible. That is the part of feature flags most tutorials skip. An if (flags.isOn('x')) takes five minutes to write. Making it behave correctly for real users takes more work: the same user gets the same answer every time, a 10% rollout is actually 10%, the app survives when the flag service is down, both branches are tested, and the flag gets deleted on schedule.
This post builds all of that in TypeScript, small enough to read in one sitting:
- A flag model that covers the four kinds of flags (release, experiment, ops, permission).
- Deterministic percentage rollouts with hashing, measured against the
Math.random()version and a bad homemade hash. - Ordered targeting rules.
- An OpenFeature provider adapter, so application code never imports a vendor SDK.
- Caching and safe defaults when the flag service is unavailable.
- Tests for both branches.
- A flag-debt linter that fails CI when a flag is past its expiry date.
Versions: Node.js 22.23, TypeScript 5.9.3, tsx 4.23.15, @openfeature/server-sdk 1.23.0 with @openfeature/core 1.12.0. Every output block below is copied from a real run (./run-all.sh in the repo). Timings come from a shared 2-vCPU sandbox, so treat them as rough.
What are feature flags (and why there are four kinds)
A feature flag is a runtime decision point: the code for both behaviors is deployed, and configuration outside the deploy decides which one a given request gets. That separates deploying code from releasing it, which is why MVP teams lean on flags. You ship small, measure activation and retention on a slice of users, and roll back without a redeploy.
Pete Hodgson’s article on Martin Fowler’s site splits flags into four categories by how long they live and how dynamic the decision is. The split matters because each kind needs a different default, owner and expiry policy:
| Kind | Example in this repo | Typical lifetime | Decided per | Default if the flag service is down | Needs an expiry date? |
|---|---|---|---|---|---|
| Release | new-checkout | days to weeks | deploy / user slice | old, proven path (false) | yes |
| Experiment | search-ranking-v2 | hours to weeks | user | control variant | yes |
| Ops (kill switch) | payments-kill-switch | short, a few are permanent | incident | “not killed” (false) | no, but review it |
| Permission | bulk-export | years | request (plan, role) | least privilege (false) | no |
The “default” column is the one people forget. We will come back to it in Step 5.
Step 1. Model flags as data
A flag is data, not code. Each definition carries its kind, an owner and an expiry date, so tooling can reason about it later:
export type FlagKind = 'release' | 'experiment' | 'ops' | 'permission'; export type Op = 'in' | 'notIn' | 'endsWith' | 'gte' | 'lt'; export type Value = boolean | string | number; export interface Condition { attr: string; op: Op; values: Value[] } export interface Rule { name: string; when: Condition[]; // all conditions must match (AND) variant?: string; // serve this variant... rollout?: { percent: number; variant: string }; // ...or a sticky slice of the matched users } export interface FlagDef { kind: FlagKind; owner: string; expires: string | null; // ISO date; null only for permanent kill switches / permissions enabled: boolean; variants: Record<string, Value>; offVariant: string; // served when enabled=false defaultVariant: string; // served when no rule matches rules: Rule[]; } export type FlagConfig = Record<string, FlagDef>; export interface Ctx { targetingKey?: string; [attr: string]: unknown } export interface Decision { value: Value; variant: string; reason: string; rule?: string } And one real definition from config/flags.json:
"new-checkout": { "kind": "release", "owner": "team-payments", "expires": "2026-12-15", "enabled": true, "variants": { "on": true, "off": false }, "offVariant": "off", "defaultVariant": "off", "rules": [ { "name": "internal-staff", "when": [{ "attr": "email", "op": "endsWith", "values": ["@example.com"] }], "variant": "on" }, { "name": "not-launched-regions", "when": [{ "attr": "country", "op": "in", "values": ["BR"] }], "variant": "off" }, { "name": "gradual-20pct", "when": [], "rollout": { "percent": 20, "variant": "on" } } ] }, Rules run top to bottom and the first match wins. Staff always get the new checkout, regions where it has not launched never do, and everybody else falls into a sticky 20% slice.
Step 2. Percentage rollouts: the Math.random() bug
Here is the version that shows up in a lot of first implementations:
const randomRollout = (percent: number) => Math.random() * 100 < percent; It looks like a 30% rollout. Here is what it does to 10,000 users who each make five requests:
// Before/after: does a user keep the same variant across requests? import { inRollout, randomRollout } from '../src/bucket.js'; const USERS = 10_000, REQUESTS = 5, PERCENT = 30; function flipRate(decide: (id: string) => boolean) { let flipped = 0, exposed = 0; for (let u = 0; u < USERS; u++) { const seen = new Set<boolean>(); for (let r = 0; r < REQUESTS; r++) seen.add(decide(`user-${u}`)); if (seen.size > 1) flipped++; if (seen.has(true)) exposed++; } return { flipped: `${((flipped / USERS) * 100).toFixed(1)}%`, sawNewUiAtLeastOnce: `${((exposed / USERS) * 100).toFixed(1)}%` }; } console.log(`${USERS} users x ${REQUESTS} requests, rollout = ${PERCENT}%`); console.table({ 'Math.random()': flipRate(() => randomRollout(PERCENT)), 'sha256(flag:user)': flipRate((id) => inRollout('new-checkout', id, PERCENT)), }); 10000 users x 5 requests, rollout = 30% ┌───────────────────┬─────────┬─────────────────────┐ │ (index) │ flipped │ sawNewUiAtLeastOnce │ ├───────────────────┼─────────┼─────────────────────┤ │ Math.random() │ '83.1%' │ '83.5%' │ │ sha256(flag:user) │ '0.0%' │ '30.3%' │ └───────────────────┴─────────┴─────────────────────┘ With Math.random(), 83% of users saw both checkouts within five requests, and 83% saw the new one at least once. That figure is close to what the math predicts: $1 - 0.3^5 - 0.7^5 \approx 82.9\%$. You did not ship to 30% of users. You shipped a flickering UI to most of them, and any metric you collect is mixed across variants.
Sticky bucketing with a hash
The fix is to derive the decision from something stable: hash the flag key together with the user ID and map the result onto a fixed number of buckets.
import { createHash } from 'node:crypto'; export const BUCKETS = 10_000; // 0.01% granularity // Deterministic: same (salt, id) -> same bucket, on every server, forever. // The salt is the flag key, so different flags pick independent user slices. export function bucket(salt: string, id: string): number { const digest = createHash('sha256').update(`${salt}:${id}`).digest(); return Math.floor((digest.readUInt32BE(0) / 2 ** 32) * BUCKETS); } export function inRollout(salt: string, id: string, percent: number): boolean { return bucket(salt, id) < Math.round(percent * (BUCKETS / 100)); } // --- Anti-patterns, kept here so the demos and tests can measure them --- // "Before" #1: a coin flip on every request. export const randomRollout = (percent: number) => Math.random() * 100 < percent; // "Before" #2: a homemade hash that sums character codes. export function charSumBucket(id: string): number { let sum = 0; for (const ch of id) sum += ch.charCodeAt(0); return sum % 100; } Three details matter:
- Deterministic. No state, no database of assignments. Every server and every process computes the same bucket for
("new-checkout", "user-7"). - 10,000 buckets. That gives you 0.01% steps, so a 0.5% canary is possible.
- The flag key is the salt. Without it, every flag would select the same users (more on that below).
Unleash documents the same approach: it hashes the user or session ID together with a group ID (the flag name by default) with MurmurHash and maps the result to a number between 0 and 100. GrowthBook’s SDK spec uses FNV-1a. I used SHA-256 from node:crypto because it ships with Node and its output is uniform. The cost is measured below.
A bad hash is uneven
“Any hash will do” is not true. A common homemade version sums character codes. Here is how both functions spread 100,000 sequential IDs (user-1 … user-100000) across 100 buckets, where the ideal is 1,000 per bucket:
// How evenly does each bucketing function spread 100,000 sequential user IDs? import { bucket, charSumBucket } from '../src/bucket.js'; const N = 100_000; const ids = Array.from({ length: N }, (_, i) => `user-${i + 1}`); const fns = { 'char-code sum % 100': (id: string) => charSumBucket(id), 'sha256 -> 100 buckets': (id: string) => Math.floor(bucket('new-checkout', id) / 100), }; const rows: Record<string, Record<string, string | number>> = {}; const hist: Record<string, number[]> = {}; for (const [name, fn] of Object.entries(fns)) { const counts = new Array(100).fill(0); for (const id of ids) counts[fn(id)]++; hist[name] = counts; const share = (pct: number) => `${((counts.slice(0, pct).reduce((a, b) => a + b, 0) / N) * 100).toFixed(1)}%`; rows[name] = { 'target 1%': share(1), 'target 10%': share(10), 'target 50%': share(50), 'empty buckets': counts.filter((c) => c === 0).length, 'largest bucket': counts.reduce((a, b) => Math.max(a, b)), }; } console.log(`${N} IDs "user-1".."user-${N}", ideal bucket size = ${N / 100}`); console.table(rows); if (process.argv.includes('--json')) console.log(JSON.stringify(hist)); 100000 IDs "user-1".."user-100000", ideal bucket size = 1000 ┌───────────────────────┬───────────┬────────────┬────────────┬───────────────┬────────────────┐ │ (index) │ target 1% │ target 10% │ target 50% │ empty buckets │ largest bucket │ ├───────────────────────┼───────────┼────────────┼────────────┼───────────────┼────────────────┤ │ char-code sum % 100 │ '0.6%' │ '5.3%' │ '24.4%' │ 18 │ 5565 │ │ sha256 -> 100 buckets │ '1.0%' │ '10.1%' │ '49.9%' │ 0 │ 1093 │ └───────────────────────┴───────────┴────────────┴────────────┴───────────────┴────────────────┘ The char-sum “10% rollout” reaches 5.3% of users, and the “50%” reaches 24.4%. The reason: every ID shares the user- prefix and 90% of them have five digits, so their sums differ only by the digit total (0 to 45). Most IDs land in a band of about 45 buckets, and the rest of the range starves. SHA-256 stays within a tenth of a point of the target.
Salted rollouts and monotonic ramps
Two more properties are easy to check and easy to get wrong:
// Two rollout properties people forget: independent slices per flag, and stable ramps. import { inRollout } from '../src/bucket.js'; const ids = Array.from({ length: 100_000 }, (_, i) => `user-${i + 1}`); const pct = (n: number) => `${((n / ids.length) * 100).toFixed(2)}%`; // 1) Same salt for every flag = the same 10% of users gets every experiment. const both = (saltA: string, saltB: string) => ids.filter((id) => inRollout(saltA, id, 10) && inRollout(saltB, id, 10)).length; console.log('Users inside BOTH 10% rollouts (independent would be ~1.00%):'); console.log(' unsalted (same salt):', pct(both('rollout', 'rollout'))); console.log(' salted with flag key:', pct(both('new-checkout', 'search-ranking-v2'))); // 2) Ramp 10% -> 20% -> 50%: nobody who already had the feature loses it. const at = (p: number) => new Set(ids.filter((id) => inRollout('new-checkout', id, p))); const s10 = at(10), s20 = at(20), s50 = at(50); const kept = (a: Set<string>, b: Set<string>) => [...a].filter((id) => b.has(id)).length; console.log(`Ramp: 10%=${s10.size}, 20%=${s20.size}, 50%=${s50.size} users`); console.log(` of the 10% cohort still on at 20%: ${kept(s10, s20)}/${s10.size}`); console.log(` of the 20% cohort still on at 50%: ${kept(s20, s50)}/${s20.size}`); // 3) Cost of hashing on the hot path. const t0 = process.hrtime.bigint(); let on = 0; for (let r = 0; r < 5; r++) for (const id of ids) if (inRollout('new-checkout', id, 20)) on++; const ms = Number(process.hrtime.bigint() - t0) / 1e6; console.log(`500,000 inRollout() calls: ${ms.toFixed(0)} ms (${((ms * 1000) / 500_000).toFixed(2)} µs per call)`); Users inside BOTH 10% rollouts (independent would be ~1.00%): unsalted (same salt): 10.06% salted with flag key: 0.98% Ramp: 10%=10070, 20%=19992, 50%=49946 users of the 10% cohort still on at 20%: 10070/10070 of the 20% cohort still on at 50%: 19992/19992 500,000 inRollout() calls: 2661 ms (5.32 µs per call) Without a per-flag salt, rollouts are correlated. Two 10% rollouts that share a salt hit the same 10% of users (10.06% overlap instead of ~1%). Those users absorb every new bug, and any measurement on one flag is contaminated by the other. GrowthBook’s spec notes that its first hash version “had a flaw that caused bias” when experiments ran in parallel, which is why a second version exists.
Ramps are monotonic. Because the check is bucket < threshold, moving from 10% to 20% to 50% only adds users. Nobody who had the feature loses it mid-session.
Hashing is cheap enough. A few microseconds per call (2 to 5 µs across my runs on a busy shared sandbox), so it can sit on the request path. Evaluate once per request and pass the result down, not once per template render.
Step 3. Targeting rules
The evaluator is a pure function: definition plus context in, decision out. No I/O, so it is trivial to test and safe to run anywhere.
import { inRollout } from './bucket.js'; import type { Condition, Ctx, Decision, FlagDef } from './types.js'; function matches(c: Condition, ctx: Ctx): boolean { const actual = ctx[c.attr]; if (actual === undefined || actual === null) return c.op === 'notIn'; switch (c.op) { case 'in': return c.values.includes(actual as never); case 'notIn': ...
