Filed underL05 · Software
Published
Reading time25 min
Updated
Field notes · L05 Software

Feature flags at scaleFlag debt, kill switches and progressive delivery

Feature flag best practices for progressive delivery: flag types and lifetimes, removing flag debt, kill switches that work, and SLO-based automatic rollback.

The short answer

Treat every feature flag as code with an owner, a type and an expiry date, and make CI fail when a flag outlives its expiry. Release flags should exist for weeks, not quarters. Kill switches are permanent, so they must be exercised in production on a schedule. Roll out by percentage, but judge each step on the error rate of the cohort that has the flag on, compared against the cohort that doesn't. A service-wide SLO alert will not notice a 1% rollout that is failing completely. Put the SDK behind OpenFeature so the vendor is a swappable detail and evaluations show up in your telemetry.

The rest of this post covers the mechanics. That means the flag types and how long each should live, a removal process that actually removes flags, how kill switches fail, a rollout controller wired to error budgets, and how to test flags without facing 2ⁿ combinations. Near the end is a reference flag manifest and CI gate you can copy.

01Deploy is not release, and why that matters

A flag splits two events that used to be one. Deploy puts code on machines. Release exposes that code to users. Once they are separate, deploys become boring and frequent, and releases become a decision you can reverse in seconds without a rollback build.

That is the whole value. It is also the whole risk. Each flag adds a branch to production that your tests might not have taken, controlled by a system outside your deploy pipeline, changed by people who might not be reading the code. Two well-documented incidents bracket the problem.

  • Too little flagging. In June 2025 a Google Cloud outage began with a new Service Control code path that crashed on a policy record with blank fields. That record was replicated globally within seconds. Google's incident report says the change "did not have appropriate error handling nor was it feature flag protected", and that "if this had been flag protected, the issue would have been caught in staging."
  • Too much flag debt. In August 2012 Knight Capital deployed new code that repurposed a flag once used to switch on a function called Power Peg. Knight had stopped using Power Peg in 2003, but the code was still on its servers. One of eight servers did not receive the new deploy, so the reused flag switched the dead code back on. According to the SEC order, the system took more than 4 million executions in about 45 minutes, and Knight lost more than $460 million.

The lesson from the first is to flag risky code paths. The lesson from the second is to delete flags, and the code behind them, and never reuse a flag name. The rest of this post is about holding both lessons at once.

02Feature flag types and how long each should live

Pete Hodgson's Feature Toggles article on martinfowler.com sorts flags into release, experiment, ops and permission toggles, along two axes: how long they live and how dynamic they are. Most vendors have adopted something similar. Unleash's flag types are a useful concrete reference because each type has a default expected lifetime, and after that the flag is marked "potentially stale".

Type What it's for Unleash default lifetime Our ceiling Who can flip it Default when the provider is unreachable
Release Hide unfinished or not-yet-launched code 40 days 30 days after reaching 100% Owning team Old behaviour
Experiment A/B or multivariate test 40 days Planned test length + 14 days Owning team + analyst Control
Operational Migrate between implementations (new cache, new queue) 7 days 14 days after cutover Owning team Old implementation
Kill switch Shed or degrade a non-critical feature under load or failure Permanent Permanent, exercised quarterly On-call Feature on (normal service)
Permission Entitlements, plan tiers, beta cohorts Permanent Permanent, but see below Product / billing Most restrictive
Sunset Coordinate removing an existing feature 90 days 90 days Owning team Feature still present

Some opinions sit behind that table.

Every flag gets exactly one type at creation, and the type never changes. A release flag that someone starts using as a kill switch is how a 30-day flag becomes a five-year flag. If you need a kill switch for the new feature, create a second flag with a different name.

Permission "flags" should mostly not live in your flag system. Entitlements are authorisation. They need an audit trail, they belong with billing data, and a mistake in them is a security incident, not a bad rollout. A flag platform is fine for early beta cohorts. Once a plan tier is something customers pay for, move it into your authorisation layer. (Tenant isolation itself is covered in multi-tenant SaaS on Postgres with row-level security.)

The default value is a safety decision, not a placeholder. OpenFeature's evaluation API returns the caller's default when evaluation fails, with reason ERROR. That default is what production runs whenever the flag service, the network or the SDK breaks. Choose it on that basis.

03Use OpenFeature, and know what it does and doesn't do

OpenFeature is a vendor-neutral API and SDK specification for flag evaluation. It is a CNCF incubating project. Its mid-2026 update introduced specification v0.9.0, the first spec release since March 2024. That release stabilises the evaluation and provider sections, adds isolated API instances so you are no longer stuck with a global singleton, and includes appendices on multi-provider setups and OpenTelemetry observability. It also has three breaking changes, so read the release notes before upgrading SDKs. The same update lists platforms that now ship OpenFeature providers as their main integration: Datadog, Vercel Flags, Cloudflare Flagship, Google Cloud App Lifecycle Manager (through the community flagd provider), Mixpanel and Octopus Deploy.

What OpenFeature gives you:

  • One evaluation API in each language, with a provider behind it. Changing vendors becomes a provider swap rather than a call-site migration.
  • Hooks that run before and after every evaluation. This is where telemetry, validation and logging go.
  • A multi-provider, useful during a vendor migration or as a fallback chain.
  • OFREP, the OpenFeature Remote Evaluation Protocol. It is an HTTP API (POST /ofrep/v1/evaluate/flags/{key}, plus a bulk endpoint) that any backend can implement, so a generic client can talk to any compliant flag service.
  • flagd, a reference flag daemon that reads flag definitions from files, Kubernetes CRDs or HTTP. It is a good choice if you want flags-as-code with no SaaS.

What it doesn't give you: a UI, approval workflows, audit logs, experiment statistics or stale-flag detection. Those still come from your vendor or your own tooling. OpenFeature standardises the call site, not the governance.

A minimal Node.js setup with flagd:

ts
import { OpenFeature } from '@openfeature/server-sdk';
import { FlagdProvider } from '@openfeature/flagd-provider';

// Block startup until flags are loaded; fail closed to defaults if not.
await OpenFeature.setProviderAndWait(new FlagdProvider());

const flags = OpenFeature.getClient();

export async function checkoutHandler(req, res) {
  const ctx = { targetingKey: req.user.id, plan: req.user.plan, region: req.region };
  const newPricing = await flags.getBooleanValue('checkout.pricing-engine-v2', false, ctx);
  return newPricing ? priceV2(req, res) : priceV1(req, res);
}

And the matching flagd definition, with a deterministic 5% rollout bucketed by targetingKey:

json
{
  "$schema": "https://flagd.dev/schema/v0/flags.json",
  "flags": {
    "checkout.pricing-engine-v2": {
      "state": "ENABLED",
      "variants": { "on": true, "off": false },
      "defaultVariant": "off",
      "targeting": {
        "fractional": [
          { "var": "targetingKey" },
          ["on", 5],
          ["off", 95]
        ]
      },
      "metadata": { "owner": "team-checkout", "type": "release", "expires": "2026-05-29" }
    }
  }
}

Two details here matter at scale. First, bucket on a stable identifier: a user, account or tenant ID, not a session or request ID. Otherwise one user flips between variants and you get bug reports nobody can reproduce. Second, for B2B products, bucket on the account, not the user. Half of a customer's team seeing a different checkout produces support tickets, not data.

04Kill switches: design them to be flipped under stress

A kill switch is a permanent flag that turns off a non-critical feature so the critical path survives. Examples are recommendations on a product page, a fraud model call with a cheaper fallback, or webhook fan-out during an incident. It is the one flag type you hope never to use, which is exactly why it rots.

Cloudflare's 5 December 2025 outage shows the failure mode. Engineers used a well-established killswitch, with a written SOP, to disable an internal WAF rule. Their write-up says: "we have never before applied a killswitch to a rule with an action of 'execute'." The code that ran after the skipped rule expected an object that no longer existed. It threw a Lua nil-index error, and roughly 28% of Cloudflare's HTTP traffic was affected for about 25 minutes. The change also went out through their global configuration system, which reaches the whole network in seconds, rather than through their gradual rollout path. A few weeks earlier, their 18 November 2025 outage came from a generated configuration file that doubled in size and was pushed fleet-wide within minutes.

What to take from that:

  1. The "off" path is a code path, and it needs tests. Every kill switch needs a test that runs the request with the switch engaged and checks the degraded response. That test runs in CI on every build, not once when the switch was added.
  2. Exercise kill switches in production on a schedule. Once a quarter, engage each one for a small cohort, such as one region or internal accounts, and watch the dashboards. If that sounds scary, the switch is not ready for a real incident.
  3. Evaluate locally, from a cached ruleset. A kill switch that needs a network call to the flag service will fail at exactly the moment you need it, because incidents and flag-service degradation tend to arrive together. Use in-process evaluation (flagd in-process mode, or your vendor's server SDK with streaming and local cache), and keep a last-known-good snapshot on disk.
  4. Only switch to a state you have already run. A kill switch should move the system to a configuration that has been exercised recently. Don't use one to try something new during an incident.
  5. Separate speed from blast radius. Kill switches need to be fast, and fast usually means global. Reduce the risk by keeping the switch's effect small and well-tested, not by slowing it down. Everything that isn't a kill switch, including ordinary rollout changes, should go through a staged path.
  6. Give on-call the authority and the UI. Kill switches should be flippable by on-call without an approval workflow. Log who flipped them and why. Make it possible from a phone.

You probably don't need dozens of kill switches. Put one on each expensive, optional dependency on the critical path. That is usually between five and fifteen in a mid-sized product.

05Percentage rollouts tied to SLOs: automated rollback that actually fires

Most "progressive delivery" setups have a hole in them. The rollout goes 1% → 5% → 25% → 100%, and the safety net is the service's ordinary SLO alerting. That alerting cannot see a small cohort.

Why service-wide burn-rate alerts miss small rollouts

Take the standard multi-window, multi-burn-rate alert from the Google SRE Workbook. It pages when the 1-hour and 5-minute error ratios both exceed 14.4× the budget rate. That rate uses up 2% of a 30-day budget in an hour. For a 99.9% SLO the threshold is 14.4 × 0.1% = 1.44% errors.

Here is a worked example. The assumptions are illustrative: a 99.9% availability SLO, a baseline error rate of 0.05%, and a new variant at 5% exposure that fails 10% of its requests.

Text
service error ratio = 0.95 × 0.05%  +  0.05 × 10%
                    = 0.0475%       +  0.5%
                    ≈ 0.55%   → burn rate ≈ 5.5×  (below the 14.4× page threshold)

cohort error ratio  = 10%     → burn rate = 100×

One in ten checkouts is failing for 5% of users, and nothing pages. At 1% exposure, even a variant that fails every request only lifts the service error ratio to about 1.05%, which is still under the page threshold. You will hear about it from support.

Measure error budget per cohort

The fix is to label request telemetry with the cohort and compute burn rate for each variant. The cleanest approach we know uses OpenTelemetry end to end.

Diagram
 request ──▶ app ──▶ OpenFeature hook ──▶ sets span attr rollout.cohort="pricing-v2:on"
                                    │
                                    ▼
                    OTel Collector (spanmetrics connector,
                    dimension: rollout.cohort)
                                    │
                                    ▼
                    Prometheus: calls_total{rollout_cohort, status_code}
                                    │
                                    ▼
                    rollout controller ──▶ flag provider API (advance / hold / revert)

The hook writes the evaluation onto the active span. OpenTelemetry has semantic conventions for flag evaluations (feature_flag.key, feature_flag.result.variant, feature_flag.provider.name and others, currently at Release Candidate stability), and those should go on the evaluation event. For metrics we also set a single, low-cardinality rollout.cohort attribute, but only for the flag that is currently in a guarded rollout. That attribute is our own convention, not part of the spec. A request evaluates many flags, and turning all of them into metric dimensions will blow up your time-series count.

ts
import { trace } from '@opentelemetry/api';
import { OpenFeature } from '@openfeature/server-sdk';
import type { Hook, HookContext, EvaluationDetails, FlagValue } from '@openfeature/server-sdk';

const GUARDED = new Set(['checkout.pricing-engine-v2']); // loaded from the flag manifest

export const cohortHook: Hook = {
  after(hookContext: HookContext, details: EvaluationDetails<FlagValue>) {
    const span = trace.getActiveSpan();
    if (!span) return;
    span.addEvent('feature_flag.evaluation', {
      'feature_flag.key': details.flagKey,
      'feature_flag.result.variant': details.variant ?? String(details.value),
      'feature_flag.result.reason': details.reason ?? 'UNKNOWN',
      'feature_flag.provider.name': hookContext.providerMetadata.name,
    });
    if (GUARDED.has(details.flagKey)) {
      span.setAttribute('rollout.cohort', `${details.flagKey}:${details.variant ?? details.value}`);
    }
  },
};

OpenFeature.addHooks(cohortHook);

The Hook, HookContext and EvaluationDetails types and hookContext.providerMetadata match @openfeature/server-sdk 1.23.0, the current release at the time of writing.

The collector turns server spans into RED metrics with that dimension:

yaml
connectors:
  spanmetrics:
    dimensions:
      - name: rollout.cohort
    exemplars:
      enabled: true

service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [spanmetrics, otlp/tracing-backend]
    metrics:
      receivers: [spanmetrics]
      exporters: [prometheusremotewrite]

Then Prometheus recording rules give an error ratio per cohort:

yaml
groups:
  - name: rollout-cohorts
    rules:
      - record: cohort:requests:rate5m
        expr: |
          sum by (rollout_cohort) (
            rate(traces_span_metrics_calls_total{span_kind="SPAN_KIND_SERVER", rollout_cohort!=""}[5m])
          )
      - record: cohort:errors:rate5m
        expr: |
          sum by (rollout_cohort) (
            rate(traces_span_metrics_calls_total{span_kind="SPAN_KIND_SERVER", status_code="STATUS_CODE_ERROR", rollout_cohort!=""}[5m])
          )
      - record: cohort:error_ratio:rate5m
        expr: cohort:errors:rate5m / cohort:requests:rate5m

The metric and label names assume the spanmetrics connector's default traces.span.metrics namespace and the Prometheus exporter's default name translation, which together produce traces_span_metrics_calls_total. If you set a different namespace, change the translation settings or enable the connector's otel.status_code feature gate, adjust the queries to match.

Do the same for latency, using the duration histogram and histogram_quantile by cohort. Latency regressions are more common than error regressions in pricing, search and recommendation changes.

The rollout controller's decision rule

Every step is evaluated against three conditions. The control cohort (:off) is the baseline, because it shares the same traffic, the same time of day and the same downstream incidents. Comparing against "last week" picks up all of that noise.

Signal Rule Action
Absolute budget burn (treatment) treatment error ratio > 14.4 × (1 − SLO) over both 5m and 30m Revert to 0%, page owner
Relative regression treatment ratio > 2 × control ratio and difference > 0.1 percentage points over 15m Hold, notify owner
Latency treatment p99 > control p99 × 1.25 over 15m Hold, notify owner
Sample size fewer than N treatment requests in the window Wait, never advance on thin data
All clear for the dwell time none of the above Advance to next step

The multipliers are starting points to tune, not universal constants. The minimum sample size matters most, and it is simple arithmetic. With a 0.05% baseline, 2,000 requests gives an expected 1 error in the control. At the 1.44% revert threshold the treatment would show about 29. That gap is too large to be noise. Below about 2,000 requests per window, one unlucky error can trip a relative rule, so the controller should wait for more data. For a low-traffic service, that means longer dwell times at small percentages. It does not mean skipping the small percentages.

A compact controller:

ts
const STEPS = [1, 5, 25, 50, 100];
const DWELL_MIN = { 1: 30, 5: 30, 25: 60, 50: 60 };   // minutes at each step
const SLO = 0.999, PAGE_BURN = 14.4, MIN_REQ = 2000;

async function q(expr: string): Promise<number> {
  const r = await fetch(`${PROM}/api/v1/query?query=${encodeURIComponent(expr)}`).then(x => x.json());
  return r.data.result.length ? Number(r.data.result[0].value[1]) : NaN;
}

export async function evaluateStep(flag: string): Promise<'revert' | 'hold' | 'wait' | 'ok'> {
  const on = `rollout_cohort="${flag}:on"`, off = `rollout_cohort="${flag}:off"`;
  const reqs   = await q(`sum(increase(traces_span_metrics_calls_total{${on},span_kind="SPAN_KIND_SERVER"}[15m]))`);
  if (!(reqs >= MIN_REQ)) return 'wait';

  const t5  = await q(`cohort:error_ratio:rate5m{${on}}`);
  const t30 = await q(`sum(rate(traces_span_metrics_calls_total{${on},status_code="STATUS_CODE_ERROR"}[30m])) / sum(rate(traces_span_metrics_calls_total{${on}}[30m]))`);
  const threshold = PAGE_BURN * (1 - SLO);
  if (t5 > threshold && t30 > threshold) return 'revert';

  const t15 = await q(`sum(rate(traces_span_metrics_calls_total{${on},status_code="STATUS_CODE_ERROR"}[15m])) / sum(rate(traces_span_metrics_calls_total{${on}}[15m]))`);
  const c15 = await q(`sum(rate(traces_span_metrics_calls_total{${off},status_code="STATUS_CODE_ERROR"}[15m])) / sum(rate(traces_span_metrics_calls_total{${off}}[15m]))`);
  if (t15 > 2 * c15 && t15 - c15 > 0.001) return 'hold';

  return 'ok';
}
// Caller: on 'revert' set the flag to 0% via the provider's admin API and page; on 'ok' after
// DWELL_MIN at the current step, advance to the next entry in STEPS. Log every decision.

Three failure modes to design for:

  • The controller loses its metrics. NaN must never mean "healthy". The !(reqs >= MIN_REQ) check deliberately treats missing data as wait. Alert if a rollout sits in wait for longer than twice its dwell time.
  • Shared fate. If treatment and control both degrade because a downstream service is having an incident, the relative rule correctly does nothing and the absolute rule correctly reverts. Reverting during someone else's incident is cheap, so accept that false positive.
  • Effects that don't show up in request errors. Some changes corrupt data, double-send email (the job of idempotency keys and an outbox) or mis-price orders while returning HTTP 200. Request SLOs are the floor, not the ceiling. For risky changes, add one domain metric per cohort, such as order value, payment authorisation rate or refund rate.

Build or buy?

If you already run Argo Rollouts, its AnalysisTemplate does the same thing for deployments: it queries Prometheus on an interval and aborts a canary when a successCondition fails. Several flag vendors now offer the flag-level version. LaunchDarkly's guarded rollouts, for example, compare the new and original variations using sequential testing and can roll back automatically. Here is how we choose:

Situation What we'd do
Changes ship mainly as new deployments, flags are rare Argo Rollouts / Flagger canary analysis at the deploy layer
Many concurrent flag rollouts, a vendor already in use Use the vendor's guarded rollout, but feed it your SLO metrics, not just its own events
Self-hosted flags (flagd, Unleash, Flipt) and Prometheus already in place The ~100-line controller above, run as a cron job or a Kubernetes controller
Fewer than five engineers, under 1 request per second on the changed path Manual steps with a dashboard. Automation needs traffic to judge with.

06Flag debt: a removal process that removes flags

Flag debt piles up because creating a flag is one line and removing it is a code change, a review and a deploy that nobody scheduled. Dashboards that list stale flags don't fix this. Unleash's lifecycle model is helpful here: a flag that has had no production evaluations for two days moves to "archived". But knowing a flag is stale is the easy part. The hard part is making removal the default.

The process we use:

  1. Expiry at creation. No flag without owner, type, expires and a pre-filed removal ticket. The manifest below enforces this.
  2. Removal is part of the definition of done. A release flag reaching 100% does not close the epic. Deleting the flag, the losing branch and its tests closes the epic.
  3. CI warns at T−7 days and fails after expiry. It fails the build for the owning team's service, not everyone's. Extending a flag is allowed: it takes a one-line PR that changes expires, reviewed by a second person, and it shows up in the diff history.
  4. Remove in two PRs. First, hardcode the winning value at the call site, keeping the flag in the platform. Deploy, then wait one release cycle. Second, delete the flag from the platform and the manifest. If PR one breaks something, revert it. Never delete the platform flag first, because every SDK falls back to its code default and you will have rolled back silently.
  5. Never reuse a flag key. Archive keys and block them in the manifest linter. That is Knight Capital's lesson in a single regex.
  6. Automate the mechanical part. Uber's open-source Piranha rewrites code to delete a stale flag and the dead branch for several languages. Even without it, the two-PR shape is easy to script. Most removals are small enough to delegate to a coding agent with the manifest entry as the spec, as long as a human reviews the diff.

A useful health metric: the median age of release flags at 100%. If it is above 30 days, your process is creating debt faster than it pays it back.

07Testing feature flag combinations without 2ⁿ test runs

With n boolean flags there are 2ⁿ possible states. With 20 flags that is 1,048,576. You will not test them all, and you don't need to. NIST's combinatorial testing research reports that "most software bugs and failures are caused by one or two parameters, with progressively fewer by three or more." In practice, the following covers most of the risk:

  1. Production-now. Every flag at its current production value. This is the configuration most users get. Load it from a snapshot of the flag service in CI.
  2. Production-next. Every in-flight release flag at its target value. This is where you will be in a few weeks.
  3. One-flip. Production-now with each in-flight flag flipped individually. That is n runs, not 2ⁿ.
  4. Kill switches engaged. Each kill switch on, one at a time, checking the degraded response. (See Cloudflare above.)
  5. Pairwise only where flags interact. If two flags touch the same code path, test the pairs. For k boolean flags, a pairwise covering array is tiny: the known minimum for 20 boolean parameters is 8 test rows (by the Katona and Kleitman–Spencer result, 7 rows can cover at most 15). Tools such as NIST's ACTS or allpairspy generate them.

To make this cheap, tests must be able to set flag state in-process. OpenFeature's in-memory provider exists for exactly this:

ts
import { OpenFeature, InMemoryProvider } from '@openfeature/server-sdk';
import { describe, it, beforeEach, expect } from 'vitest';

const provider = new InMemoryProvider({});
await OpenFeature.setProviderAndWait(provider);

const state = (on: boolean) => ({
  variants: { on: true, off: false }, defaultVariant: on ? 'on' : 'off', disabled: false,
});

describe('checkout with recommendations kill switch engaged', () => {
  beforeEach(() => provider.putConfiguration({
    'checkout.pricing-engine-v2': state(true),
    'killswitch.recommendations': state(true),
  }));

  it('renders checkout without the recommendations block', async () => {
    const res = await request(app).get('/checkout');
    expect(res.status).toBe(200);
    expect(res.body.recommendations).toBeUndefined();
  });
});

Spec v0.9.0's isolated API instances help with parallel tests. Each test file can own its own API instance instead of sharing global state. Check your language SDK's compliance tracker before relying on this.

One rule we hold firmly: unit tests should not depend on flags at all. Pass the flag value into the function as a parameter, and keep flag evaluation at the edge, in the handler or controller. Then flag combinatorics only matter for integration and end-to-end tests, which are where the matrix above runs.

08The reusable asset: a flag manifest and CI gate

This is the reference we start clients on. It is a single flags.yaml checked into each service's repository. The flag platform is the runtime, and this file is the contract. A CI job enforces it.

yaml
# flags.yaml — one entry per flag this service evaluates
version: 1
retired_keys:            # never reuse
  - checkout.pricing-engine-v1
  - search.legacy-ranker

flags:
  - key: checkout.pricing-engine-v2
    type: release                  # release | experiment | operational | killswitch | permission | sunset
    owner: team-checkout
    created: 2026-04-03
    expires: 2026-05-29            # required unless type is killswitch or permission
    removal_ticket: CHK-1842       # required unless permanent
    default: false                 # the value code uses if the provider is unreachable
    safe_default_rationale: "v1 engine is current production"
    guarded_rollout:
      slo: 0.999
      steps: [1, 5, 25, 50, 100]
      domain_metric: checkout_authorisation_rate

  - key: killswitch.recommendations
    type: killswitch
    owner: team-discovery
    created: 2025-03-02
    default: false                 # false = recommendations served normally
    last_exercised: 2026-03-20     # CI fails if older than 100 days
    runbook: https://runbooks.internal/killswitch-recommendations

The CI gate. It is Node.js with one dependency, and it runs in a few seconds:

js
// scripts/check-flags.mjs — usage: node scripts/check-flags.mjs flags.yaml src/
import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import YAML from 'yaml';

const [manifestPath, srcDir] = process.argv.slice(2);
const m = YAML.parse(readFileSync(manifestPath, 'utf8'));
const today = new Date(); const DAY = 86_400_000;
const PERMANENT = new Set(['killswitch', 'permission']);
const errors = [], warnings = [];

const refs = (key) => {
  try { return execFileSync('rg', ['-l', '--fixed-strings', key, srcDir], { encoding: 'utf8' }).trim(); }
  catch { return ''; } // rg exits 1 on no match
};

for (const f of m.flags) {
  const id = `[${f.key}]`;
  for (const k of ['key', 'type', 'owner', 'created', 'default']) if (f[k] === undefined) errors.push(`${id} missing ${k}`);
  if (m.retired_keys?.includes(f.key)) errors.push(`${id} reuses a retired key`);

  if (!PERMANENT.has(f.type)) {
    if (!f.expires || !f.removal_ticket) { errors.push(`${id} non-permanent flag needs expires + removal_ticket`); continue; }
    const left = (new Date(f.expires) - today) / DAY;
    if (left < 0) errors.push(`${id} expired ${Math.ceil(-left)}d ago — remove it or extend via reviewed PR (${f.removal_ticket})`);
    else if (left < 7) warnings.push(`${id} expires in ${Math.ceil(left)}d`);
  }
  if (f.type === 'killswitch') {
    const age = (today - new Date(f.last_exercised ?? 0)) / DAY;
    if (age > 100) errors.push(`${id} kill switch not exercised in ${Math.floor(age)}d`);
    if (!f.runbook) errors.push(`${id} kill switch needs a runbook`);
  }
  if (!refs(f.key)) warnings.push(`${id} not referenced in ${srcDir} — ready for platform deletion?`);
}

// Flags referenced in code but missing from the manifest (assumes a dotted key convention).
let used = [];
try {
  used = execFileSync('rg', ['-o', '--no-filename', "get(Boolean|String|Number|Object)(Value|Details)\\(\\s*['\"]([a-z0-9.-]+)['\"]", '-r', '$3', srcDir], { encoding: 'utf8' })
    .split('\n').filter(Boolean);
} catch { /* rg exits 1 when nothing matches */ }
const declared = new Set(m.flags.map(f => f.key));
for (const k of new Set(used)) if (!declared.has(k)) errors.push(`[${k}] evaluated in code but not in ${manifestPath}`);

warnings.forEach(w => console.warn('warn ', w));
errors.forEach(e => console.error('error', e));
process.exit(errors.length ? 1 : 0);

What this contract buys you:

  • Expiry is enforced by the build, not by a quarterly clean-up.
  • Kill switches cannot quietly rot. A switch that hasn't been exercised in 100 days fails the owner's build.
  • The safe default is written down with a reason. That gives reviewers something to disagree with.
  • Retired keys cannot come back.
  • The rollout policy lives next to the code, so the controller reads it rather than someone typing percentages into a UI.

Two caveats. The code-reference scan relies on literal flag keys at call sites. Ban computed flag keys in your linter, since you can't remove what you can't find. And the manifest has to agree with the platform: add a nightly job that diffs flags.yaml against the provider's API and opens a ticket on drift.

09Where flags cross into the rest of the stack

Flags are a software concern that leaks into every other layer. A flag platform is an authorisation system whether you meant it to be or not. Whoever can edit targeting rules can change production behaviour for any customer, so it needs SSO, least privilege and audit logs like any other production control plane. Experiment flags are a data problem: exposure events, assignment consistency and analysis all have to agree on what "treatment" meant. Cohort-labelled telemetry is an observability and cost problem, because every dimension multiplies time series. And deciding which changes ship behind flags at all is a delivery strategy question that belongs in your release process, not in each engineer's judgement. We see the most flag pain where these layers are owned by different vendors who never compare notes. (For the telemetry side, see Anatomy of a request: one click traced through CDN, WAF, load balancer, app and database and OpenTelemetry without the bill: sampling, cardinality and when to leave Datadog.)

10FAQ

How many feature flags is too many? Raw count matters less than age and type. A few hundred flags is fine if they are mostly short-lived release flags with owners and expiry dates. Thirty flags is a problem if half of them are release flags at 100% from last year. Track the number of expired flags and the median age of release flags at 100%. Both should be near zero and under 30 days respectively.

Should feature flags be evaluated on the client or the server? On the server, wherever you can. Server-side evaluation keeps targeting rules and user attributes private, gives one source of truth per request, and works with the cohort telemetry described above. Use client-side evaluation for purely presentational changes, through an SDK or OFREP endpoint that sends only evaluated values, never the rules.

What happens if the feature flag service goes down? With in-process evaluation and a cached ruleset, almost nothing: flags keep their last-known values. Without a cache, every evaluation returns the code default with an error reason. This is why defaults must be the safe, current-production behaviour, and why kill switches should never depend on a network call.

Is OpenFeature production-ready? Yes, for the evaluation API. It is a CNCF incubating project, and its spec stabilised the evaluation and provider sections in v0.9.0. Several major platforms ship OpenFeature providers as their main integration. Check the per-language SDK compliance tracker for newer features such as isolated instances and tracking, and review the three breaking changes before upgrading.

Feature flags or canary deployments: which should we use for progressive delivery? Both, at different layers. Canary deployments limit the blast radius of a binary: a new build, a dependency bump, a runtime upgrade. Flags limit the blast radius of a behaviour and can be reversed without a deploy. Use canaries for every deploy and flags for user-facing or risky logic changes. Judge both on per-cohort SLOs.

Can feature flags replace database migrations or API versioning? No. A flag can switch which code path reads or writes. It cannot make two schemas or two API contracts compatible. Use expand/contract for the schema (see zero-downtime Postgres migrations) and an operational flag to switch reads once both shapes exist. For moving a whole capability between systems, flags pair with the routing layer in a strangler fig migration.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →