The Feature Flag Discipline Guide — AI Code Toolkit
🚩 Discipline

The Feature Flag Discipline Guide

Feature flag programs that stay controllable at scale. Flag typology (release, experiment, ops, permission, circuit breaker — different lifecycles); when to use flags vs. config vs. code; platform selection (LaunchDarkly, Statsig, PostHog, Unleash, Flagsmith); naming + ownership + TTL discipline; automated stale detection; removal PR pattern (with near-incident cases); experimentation math (MDE, sample size, SRM, guardrails, sequential vs. fixed horizon); rollout patterns; cross-flag interactions; client-side vs. server-side; fail-safe defaults; failure patterns; sunset in definition of done; migration; metrics. Twenty-one sections; 22 minutes.

By Zain Khan
22 min read
Updated Mar 1, 2027
Guide v1.0

What feature flag discipline actually is

Feature flag discipline is treating flags as liability, not asset. Every flag has a cost — cognitive, testing, latency, incident-reasoning — that compounds at scale. Discipline is the framework that keeps flag count bounded: naming makes them findable; ownership makes them accountable; TTL makes lifecycle explicit; sunset makes them go away when done. And experimentation discipline is the math + process that makes A/B tests actually inform decisions.

Not a “buy LaunchDarkly” guide. Platform matters less than discipline. Well-managed 500 flags fine; badly-managed 50 is chaos. Vendor is a small piece; process is the point.

Pairs with the feature-flag-strategist subagent (architectural decisions), feature-flag-lint hook (code-side hygiene), and launchdarkly MCP (state queries).

Flag typology: release, experiment, ops, permission, circuit breaker

Not all flags are the same. Five common types with different lifecycles:

Release toggle. Gates unreleased code. Enables gradual rollout: 1% → 10% → 50% → 100%. Should die within days to weeks after reaching 100%.

Experiment flag. A/B test infrastructure. Traffic split between variants for measurement. Should die after decision made + winning variant deployed.

Ops toggle / kill switch. Emergency disable for a feature. Long-lived; effectively part of resilience infrastructure. Should be periodically tested (does the disable actually work?).

Permission toggle. User segmentation (this feature for enterprise tier only). Effectively product configuration. Consider whether it belongs in a config system rather than flag system.

Circuit breaker flag. Automatic disable when downstream fails. Long-lived; part of resilience discipline.

Sunset discipline applies to release + experiment flags primarily. Ops + permission + circuit breaker flags stay but should be reviewed annually. Aggressive cleanup of ops toggles because “they're at 100%” is a mistake.

When to use flags vs. config vs. code

Not everything needs to be a flag:

Use a flag when:

  • Gradual rollout with monitoring at each stage matters.
  • Experimentation is planned.
  • Emergency disable capability is a requirement.
  • Different user segments should see different experiences.

Use configuration when:

  • Value changes but not per-user (e.g., default page size = 20).
  • Environment-specific values (dev vs. prod).
  • Product configuration by tier (permission toggles technically qualify but may belong in config).

Use code when:

  • Value is stable and won't change.
  • The decision is architectural, not operational.

Common mistake: flag everything “because we might need to disable it.” If disable isn't planned, don't add the flag cost.

Platform selection framework

Common options:

LaunchDarkly: market leader; enterprise-focused; expensive; deep targeting; excellent audit. Standard for mid-market and up.

Statsig: experimentation-heavy; strong stats engine; product analytics integrated. Best when experimentation is core to product culture.

PostHog: analytics + flags + experiments unified; open source + cloud; self-hostable. Good middle-ground when unified stack matters.

Unleash: open source; simpler feature set; self-hosted. Best for cost-conscious + ops-capable teams.

Flagsmith: open source; between Unleash + PostHog. Growing.

DIY: database column + admin UI + evaluation library. Works at small scale (under 50 flags); becomes painful beyond.

Selection framework:

  • Enterprise with deep targeting + audit needs: LaunchDarkly.
  • Experimentation-heavy product culture: Statsig.
  • Unified analytics + flags + experiments: PostHog.
  • Cost-conscious + ops-capable: Unleash or PostHog self-hosted.
  • Under 50 flags + no experimentation: DIY viable.

Migration between platforms is expensive; pick with a horizon in mind.

Naming convention

Flag names are the first line of hygiene. Bad names create confusion; good names create clarity.

Recommended structure: domain_purpose_variant

  • billing_new_pricing_model: domain=billing; purpose=new pricing; variant=model (as opposed to UI).
  • onboarding_video_intro_v2: domain=onboarding; purpose=video intro; variant=v2 (this is second iteration).
  • checkout_apple_pay_beta: domain=checkout; purpose=Apple Pay; variant=beta (indicates not yet default).

Benefits:

  • Findable by domain (grep for “billing_”).
  • Purpose obvious.
  • Variants distinguishable.

Anti-patterns to avoid:

  • Meaningless (flag_1, test).
  • Person names (ahmed_experiment).
  • Dates in name (launch_2025_q3): dates go in description, not name.
  • Negations (disable_x): use positive form + fail-safe default.

Enforce naming at platform config (if supported) or in code review checklist.

Ownership and TTL at creation

Every flag has:

  • Owner: team responsible (not individual; teams outlast individuals). Enforced at creation via platform tag.
  • TTL: expected lifetime. Default by type: release = 30 days; experiment = experiment duration + 14 days; ops toggle = permanent (annual review); permission = permanent (annual review); circuit breaker = permanent.
  • Description: why this flag exists + when it should be removed. Not just the technical detail.

Platforms that don't enforce: use required fields via API + block direct UI creation with role restriction. Teams routing flag creation through a controlled path.

Retrofitting ownership to legacy flags is a project. Cross-reference with git blame; assign to team that most recently touched the flag's code. Some flags will be orphans; deletion candidates.

Automated stale detection

Weekly automated job:

  • Flags at 100% rollout for >30 days.
  • No negative evaluations (nobody gets the “off” branch).
  • No code changes referring to flag in past 60 days.

These are zombie candidates. Report to owning team. Team decides: remove, extend TTL with justification, or convert type (e.g., release toggle → permission toggle).

Additional signals for sophisticated detection:

  • SDK evaluation counts (flag rarely evaluated = maybe dead code path).
  • Code references (via feature-flag-lint hook or CI scan).
  • Age since last flag change on platform.

Reports go to team leads + tracked in monthly review. Making stale flags visible is what drives cleanup.

The removal PR pattern

Removing a flag correctly:

  1. PR removes code references + platform config in same commit. Not one or the other; both must be reviewed together.
  2. Verify targeting rules before removal: flag at 100% may still have specific targeting overrides (e.g., admin bypass). Removing loses these.
  3. Verify fail-safe default direction: if flag removed, code path that used to check flag might trip fail-safe with wrong default. Change fail-safe before removal.
  4. Deploy code change first: ensure code no longer references flag.
  5. Then delete platform config: with confidence that no code will error on missing flag.
  6. Canary and monitor: watch for issues; rollback plan ready.

Two near-incidents from removals during our cleanup:

  • Removed a flag with targeting rule for admins; admins started seeing non-admin experience. Caught in canary.
  • Removed a flag whose fail-safe default was “off” but the code path expected “on” when flag missing. SDK errors triggered wrong behavior. Caught in load test.

Removal is not trivial. Read the PR carefully.

Experimentation design fundamentals

Experiments need statistical rigor. Key concepts:

Minimum Detectable Effect (MDE): smallest effect worth detecting. Trade-off: smaller MDE requires more sample. Common: 5-10% relative lift for conversion; 1-2% for high-baseline metrics.

Sample size calculation: baseline conversion + MDE + alpha (typically 0.05) + power (typically 0.8) → sample per variant. Use platform's calculator or standard tools (Evan Miller's calculator).

Randomization unit: user, session, request, account? Impacts independence assumption. User-level randomization most common; requires consistent identification.

Duration: at least one full week (day-of-week effects); at least the calculated sample duration.

Pre-registration: before starting, document primary metric, guardrails, sample size, duration. Prevents post-hoc rationalization.

Sample Ratio Mismatch (SRM)

Allocation should match ratio. 50/50 experiment: actual traffic should be ~50/50. Deviation signals problem.

Chi-square test on allocation vs. expected. If p < 0.01: SRM. Investigate:

  • Bucketing bug: some users deterministically get one variant.
  • Selection effect: some users can't be enrolled (browser incompatibility) and disproportionately fall into one variant.
  • Timing issue: enrollment logic runs before user identified consistently.

SRM invalidates experiments. Sample skewed = comparison skewed. Not fixable by more sample.

Automated SRM check per experiment; alert on trigger. Standard discipline in mature experimentation programs.

Guardrail metrics and primary metric

Every experiment has:

Primary metric: the one you're trying to move. Pre-registered. Sample size calculated against.

Guardrail metrics: metrics that must not regress. Even if primary lifts, if guardrails degrade, don't ship. Common: page load time, error rate, revenue per user, support ticket volume.

Guardrail check: after experiment, if any guardrail regressed significantly, deep review before shipping treatment. Local win + global loss = don't ship.

Multiple-testing correction: if you check many metrics, false positive rate increases. Bonferroni or Benjamini-Hochberg correction for exploratory metrics.

Sequential vs. fixed-horizon testing

Fixed horizon: pre-calculate sample size; run to sample; then analyze. Traditional. Cannot peek and stop early.

Sequential testing: allows early stopping when effect clear. mSPRT (mixture Sequential Probability Ratio Test), Bayesian methods, Optimizely-style always-valid inference. More complex; earlier decisions when clear.

Peeking at fixed-horizon experiments and stopping early inflates false positive rate substantially. Either commit to fixed horizon + don't peek, or use sequential methods designed for it.

Most modern platforms (Statsig, LaunchDarkly Experiments) support sequential; earlier decisions typical.

Rollout patterns

Percentage rollout. 1% → 5% → 25% → 50% → 100%, watching metrics between stages. Simple; safe.

Targeted rollout. Internal → beta users → segment → all. Reveals issues in higher-fidelity users first.

Ring deployment. Ring 0 (internal) → ring 1 (early adopters) → ring 2+ (waves). Enterprise pattern.

Region-by-region. Geographic waves. Catches region-specific issues (locale, compliance, latency) before global rollout.

Progressive delivery with automated rollback. Percentage rollout with metric guardrails; automatic rollback if metrics regress. Modern practice; requires observability discipline.

Stage durations: at least long enough to catch issues (typically hours minimum for high-traffic; days for lower traffic). Not just “bump to next%” on cadence.

Cross-flag interactions

Flag A + flag B interact. Testing each in isolation misses combined effects.

Example failure modes:

  • Flag A adds new UI; flag B changes backend response format. Combined: UI breaks on new response.
  • Experiment X and experiment Y both target same users. Results confounded.
  • Rollout of flag C intersects with rollout of flag D. Which caused the metric change?

Discipline:

  • Test combinations for related flags (adjacent code paths).
  • Coordinate concurrent experiments (no overlap on same primary metric).
  • Rollout coordination for major changes.

At scale: automated tools to detect flag interactions (Statsig experimenter guardrails; homegrown analysis). Manual coordination breaks down beyond a few concurrent experiments.

Client-side vs. server-side flags

Different concerns:

Server-side flags: evaluation in backend; consistent per request; no privacy exposure of targeting rules. Standard for business logic.

Client-side flags: evaluation in browser or mobile app; latency-sensitive; requires SDK; targeting rules potentially visible in browser. For UI variants + client-visible experiments.

Common pattern:

  • Server-side for business logic (paid tier features, pricing changes).
  • Client-side for UI variants (button color, layout changes).
  • Some flags evaluated both sides: server determines eligibility; client renders variant.

Cost:

  • Client SDK adds bundle size + startup time.
  • Client eval requires flag delivery to client (bandwidth).
  • Client can have stale flag state between fetches.

Fail-safe defaults per flag

Every flag has fail-safe: what returns when platform unavailable or flag missing. This value matters.

Example fail-safes:

  • Release toggle for new feature: fail-safe “off” (feature disabled). Doesn't accidentally enable unreleased code.
  • Kill switch for existing feature: fail-safe “on” (feature enabled). Platform outage doesn't accidentally disable working feature.
  • Ops toggle for external integration: fail-safe “on” if you trust the integration; “off” if paranoid about it.

Get this wrong: platform outage produces wrong behavior. Set fail-safe based on: what's safer if we can't check the flag?

Document fail-safe in flag description. Verify in code review.

The failure patterns you will see

Zombie flags: flag at 100% rollout for months; code still checks it. Debt.

Long-lived experiment flags: experiment ended; flag stayed; treatment vs. control users diverged in code.

Flag-driven complexity: nested flag conditionals; untestable.

Cross-flag interactions unmodeled: bug from A+B combination.

Fail-safe wrong direction: platform outage produces wrong behavior.

SRM ignored: allocation drift silently invalidates experiments.

Missing ownership: flag exists; nobody knows why; nobody wants to touch it.

Dead flag checks: code checks flag; flag deleted; check silently returns fail-safe.

Sunset in definition of done

Culture change more than tool. “Feature complete” = shipped to 100% + flag removed + PR merged. Not shipped to 100%.

Enforcement:

  • Code review question: “how does this flag get removed?” Answer required.
  • Feature retro checks flag removal. If not removed: assigned action item.
  • Team lead sees flag list monthly; drives sunset conversations.
  • Public celebration of flag removals (small ritual; reinforces value).

Without sunset in DoD, flags accumulate. Cleanup projects follow. Better to bake into normal flow.

Migration between platforms

Migration is expensive. Reasons to migrate:

  • Cost pressure (LaunchDarkly at scale can be significant).
  • Feature need (experimentation platform for stats depth).
  • Unified stack (consolidating on PostHog for analytics + flags).

Migration pattern:

  1. Deploy new platform SDK alongside existing.
  2. Dual-evaluation for critical flags: check both platforms; log divergence.
  3. Migrate flags in waves (by team, by domain).
  4. Feature freeze on old platform for migrated flags.
  5. Cutover; keep old for rollback.
  6. Decommission old.

Months, not weeks. Verify no divergence before cutover; SRM-like check on flag evaluation consistency.

Metrics that matter

Track:

  • Active flag count: total; by type. Should stabilize; not grow unbounded.
  • Stale flag count: flags past TTL. Should approach zero.
  • Median flag age: for release toggles; should be under 60 days.
  • Experiment throughput: experiments run per quarter.
  • Experiment quality: % with SRM, % powered, % with pre-registered guardrails.
  • Zombie flag detection rate: how many zombies caught by automation.
  • Sunset rate: flags removed per month.

Culture metrics: DoD completion (features shipped with flag removed as % of features shipped).

What to do next

Count your active flags. Categorize by type. If >50% are release toggles at 100%, sunset process is broken.

If flags don't have owners: retrofit. Cross-reference git blame; assign to teams; orphans become sunset candidates.

If you don't have automated stale detection: build. Weekly report of candidates to team leads.

If sunset isn't in DoD: add it. Code review questions + retro checks. Cultural change; takes months.

If experiments run without SRM checks or guardrails: add them. Experiments without discipline are decorative.

Combined with the feature-flag-strategist subagent, this framework is what turns feature flags from “the thing that will bite us later” into an infrastructure you actually control. Discipline compounds. Neglect compounds harder.

FAQ

Frequently asked

Overlaps:

  • Here: flags broader.
  • Experimentation deeper elsewhere.

Hygiene-based:

  • 200 managed: fine.
  • 50 unmanaged: chaos.

Both:

  • Cleanup for debt.
  • Continuous for baseline.

Minimal ongoing:

  • Upfront setup cost.
  • Compounding savings.

Culture change:

  • Show cost.
  • Leadership visibility.
  • Celebrate wins.