# Feature Flags as Engineering Infrastructure

Feature flags only separate deploy from release when teams treat them as infrastructure—not as permanent conditionals. Staff engineers assign ownership, define safe defaults for outages, audit targeting changes, time-box experiments, and delete flags on schedule so shipping stays reversible without hiding permanent branching debt.

Published: 2025-02-14

## Deploy should be boring; release should be controlled

Merging to main and showing new behavior to users are different decisions. Continuous integration should keep deploy boring: green tests, artifact promotion, and observability hooks that prove the binary is healthy. Release is the deliberate act of increasing exposure—percentage, tenant ring, or geography—after soak metrics look stable.

Teams that conflate the two rediscover midnight toggles, Slack-only flag edits, and support surprises when a dashboard change outpaces communication. Measure deploy frequency and exposure frequency separately. A valid week may include many deploys and zero exposure increases if soak surfaces latency or error regressions.

Expo and React Native MVPs amplify the gap: App Store review delays mean mobile binaries lag server deploys by weeks. Server-enforced flags with explicit minimum app versions prevent older clients from calling tool schemas the backend no longer supports. Document which changes are server-only versus which require a client release.

Pair flags with release notes aimed at support: what users see when a flag is on, what fallback appears when off, and which cohorts are in scope. Boring deploy plus controlled release is how staff teams ship weekly without gambling brand trust on a single boolean flip.

## Design flags for operability under stress

Every flag needs a default for when the management service is slow or unavailable. Critical paths should fail closed or open intentionally—never randomly. Payment capture, authentication, and data export should default to the safer state documented per environment, not to whatever cached value happened to load last.

Avoid wrapping unrelated behavior in one flag. Coarse flags create cleanup nightmares; hyper-granular flags create combinatorial test cost. Group by user-visible capability with a named owner and a removal date recorded at creation time.

| Concern | Design choice | Operational note |
| --- | --- | --- |
| Outage default | Fail closed for writes | Document in runbook |
| Audit | Actor + reason on change | Required for enterprise |
| Evaluation | Server authoritative | Client hints only |
| Naming | `capability.surface` | No ticket ids in keys |

Keep evaluation out of tight loops when possible—batch or edge-evaluate with short TTL caches, but never cache across tenants without explicit keys. Cloudflare Workers and Supabase edge routes should read the same flag snapshot mobile clients trust, with propagation SLAs measured in minutes, not hours.

When AI features ride flags, evaluation must gate model routes and tool writes—not only UI chrome. A flag that hides a button while the model still streams is an incident waiting for screenshots.

## Targeting tenants, rings, and sticky assignment

Random percentage rollouts are convenient for stateless pages and wrong for many SaaS journeys. Enterprise tenants, regulated workflows, and high-touch accounts need explicit inclusion or exclusion lists—not accidental placement because a load balancer rerolled.

Use rings: internal dogfood, partner cohorts, self-serve plans, then strategic accounts with named approvers. Sticky assignment keeps a tenant or user in a cohort long enough to finish a journey; bouncing between experiences mid-session breaks analytics and support scripts.

Targeting rules must be testable and auditable. Store who changed a rule, the previous JSON, and a human-readable reason code. Support should answer whether a customer is in an experiment without paging backend on-call.

For multi-tenant Postgres MVPs, flags do not replace row-level security—they decide which code path runs, not who may read a row. Cross-tenant leakage tests belong in CI alongside flag matrix tests.

Mobile clients cache responses; server enforcement remains mandatory. Rate-limit and deny with explicit error codes when a stale app hits a disabled capability instead of silently accepting dangerous work.

## Experiments need hygiene before launch

When flags power experiments, define the hypothesis, primary metric, guardrail metrics, and end criteria before increasing exposure. Experiments without end dates pollute analytics, inflate cognitive load, and train product to argue from noisy dashboards.

Segment carefully. Overlapping experiments on the same funnel invalidate conclusions and create confusing UX. Document mutual exclusion groups the same way you document database migration locks.

Experiments on AI surfaces need quality guardrails—not only click-through. Track refusal rate shifts, cost per successful outcome, escalation to human support, and tool failure rates alongside product KPIs. A winning engagement metric with rising harmful completions is a rollback, not a celebration.

Archive experiment configs when they end. Future teams should not resurrect half-finished toggles because the key still exists in a vendor UI. Link experiment records to the flag key in your service catalog so cleanup tickets are searchable.

## Cleanup is part of delivery, not backlog folklore

A flag that survives long after full rollout becomes dead configuration and hidden branching. Schedule cleanup with the same seriousness as launch: delete unused paths, remove dual implementations, and update docs so the codebase reflects reality.

Set removal dates when flags are created—not when someone remembers during a refactor. Mature teams win with flags because they release safely and leave the system simpler afterward, not because they accumulate toggles as organizational memory.

Track flag age and owner in a registry. Alert when cleanup SLA slips: if a flag passes its removal date without a merge, block new exposure increases until debt is addressed or risk acceptance is recorded.

Pair cleanup with contract tests. Removing a flag should fail CI if clients still send headers or query params tied to the old epoch. Static export sites still need server-side enforcement tests because there is no runtime middleware safety net.

## Flags, AI routes, and kill switches

Not every flag is a kill switch. Kill switches stop capability paths—model routes, tool writes, outbound messages—not only marketing buttons. AI-assisted products should map kill scopes to model route, retrieval index, and tool schema hash in the same artifact release trains promote.

Feature flags gate gradual exposure; kill switches gate emergency denial. Defaults for high-stakes AI should fail toward safe degradation: retrieval-only, template responses, or hard stop on write tools—chosen per risk tier and documented in runbooks.

Client-only flags are insufficient for billing, security, and agentic tools. Workers must enforce denial even when Expo builds cache optimistic UI. Pair flags with observability from streaming LLM routes so on-call sees cohort-specific latency, not only global averages hiding a bad tenant.

When a provider outage strikes, flags should route to tested fallback models or deterministic paths rehearsed in staging. Provider dashboards are informational; your switch must work when the provider is up but your product misbehaves.

## Test enabled and disabled paths in CI

Flags double the state space. CI should matrix critical journeys with flags on and off—checkout, signup, export, and AI-assisted flows that write data. Nightly suites catch drift when a refactor assumes the happy path only.

Tag E2E specs with flag dimensions your pipeline can inject via environment or bootstrap config. Flaky tests often mean nondeterministic assignment; fix stickiness in tests the same way you fix it in production.

Contract tests should assert API behavior in both states: response shapes, error codes, and side-effect guards. Mobile contract fixtures must include disabled-tool responses so older clients degrade gracefully.

Measure coverage of flag combinations you actually ship. If combinatorics explode, reduce flag count—that is a signal to simplify capability boundaries, not to skip tests.

## Operational checklist for flag infrastructure

Before relying on flags in production: publish naming conventions, owner rotation, default matrix per environment, audit log retention, and propagation SLA. Before each exposure increase: soak metrics green, support brief updated, rollback = targeting change rehearsed, cohort list attached to the change ticket.

During incidents: stop cohort expansion first, flip kill scope if needed, capture flag revision and model artifact id, communicate user-visible fallback paths. After recovery: re-enter through normal release with documented exception—never silent hotfix outside audit trails.

Registry entries should link to runbooks, experiment records, and related kill switches. Quarterly review flag count, age, and combinatoric test runtime—prune before the system becomes untestable.

Connect flag hygiene to progressive delivery and release trains: exposure increases ride scheduled windows; deploys may continue daily when behavior-neutral. Enterprise buyers ask for predictable change; your flag registry is evidence that engineering matches commercial promises.

Finally, delete flags deliberately: telemetry-first sunset, comms, then code removal—never leave permanent `if (flag)` branches because removal felt risky in sprint planning.

Review flag metrics in weekly ops: count of active flags, median age, failed cleanup SLAs, and incident count where flag state was unknown. Staff teams treat rising median age as architectural smell—capabilities should merge to default-on code paths once evidence is stable, not linger as silent forks forever.

## Observability must include flag state

Incidents that ask “which flag version was live?” without an answer waste the first fifteen minutes of response. Emit flag revision, cohort key, and evaluation latency on the same traces that capture HTTP status and model route. Dashboards should slice error rate by flag state—not only by service version.

Log evaluation failures explicitly: vendor timeout, cache miss, malformed rule JSON, or unauthorized edit attempt. Silent fallback to default-on has caused more production harm than a loud error page because support cannot see the branch users hit.

For Expo clients, include a lightweight config poll or response header that names capability epoch so mobile support matches server truth without guessing from screenshots. Align analytics events with flag keys product managers actually use in experiment docs—renamed keys without event migration recreate the “unknown state” problem under a new label.

During postmortems, reconstruct exposure timeline from audit logs, not memory. If you cannot replay who moved a tenant between rings, targeting is not production-ready regardless of how polished the vendor UI looks.

Export flag evaluation metrics to the same incident tooling that pages on-call for API errors. When flag latency spikes, treat it as a release risk: stale rules may leave tenants on unintended cohorts long after product intended a rollback.
