Creating a technical guide
I'm thinking about developing a technical guide that covers safe feature flags at scale. It should touch on various aspects like targeting models, kill switches, and experiments, ensuring there's a focus on blast radius controls and auditability too. I need to discuss architecture patterns, data models, and caching while also considering user attributes and rollout types. I want to incorporate elements like migration cleanup and security in a multi-tenant context. Structuring this with bullet points and pseudocode examples might help clarify the concepts!Drafting feature flag guidelines
I want to provide code snippets in TypeScript, Go, or Python, keeping them concise. I’ll also include pseudocode for evaluation and configuration while suggesting best practices. I’m thinking about a targeting model that utilizes rules based on context and segment membership, incorporating percent rollouts with hashing and deterministic bucketing.
It's essential to create a separate emergency override for the kill switch and ensure clean experiment integration. I'll focus on blast radius management, safe evaluations for attributes, and a well-defined migration cleanup for flags. Lastly, I'll emphasize auditability through event-sourced configuration.Designing a minimal viable safe system
I’m thinking about creating a "minimal viable safe system" architecture that includes various components, starting from an authoring UI to review and then passing through a config repository for CI validation, eventually publishing to a CDN or Redis. It’s important to incorporate an evaluation SDK that supports offline caching, possibly through polling or streaming.
I should also emphasize privacy and compliance by avoiding PII and using hashing. We need to establish signing rules on the client side and evaluate on the server for mobile. Finally, I’ll organize everything into a structured markdown format with headings and a checklist for reference!
1) Targeting model (deterministic, safe, explainable)
Core requirements
- Deterministic evaluation: same user/context → same result across services, regions, and time (unless config changes).
- Explainable: every decision should be traceable (“matched rule #3: segment=beta, rollout=10% bucket=7”).
- Stable bucketing: percent rollouts must not reshuffle users when adding/removing servers.
- Typed context: strict schema for attributes; unknown/missing attributes behave predictably.
- No PII in rules (or at least hashed): keep targeting inputs privacy-safe.
Context model
Define a minimal, shared “targeting context” used everywhere:
{
"subject": {
"key": "user:123", // stable identifier used for bucketing
"kind": "user" // user | device | org | session | etc.
},
"attributes": {
"orgId": "org_9",
"plan": "enterprise",
"region": "us-east-1",
"appVersion": "1.42.0",
"isInternal": false
}
}
Use one stable key per rollout:
- User features:
userId
- B2B features:
orgId (often better than userId to avoid partial org exposure)
- Device features: device ID
- If you must support multiple, make it explicit per-flag (see below).
Flag configuration shape (recommended)
Use an ordered list of rules with strict precedence:
- Emergency override (kill switch)
- Explicit overrides (allowlist/blocklist)
- Rules by conditions (segments/attributes)
- Percent rollout (deterministic)
- Default
Example (conceptual):
key: "new_checkout"
type: "boolean"
owner: "payments-team"
bucketingKey: "orgId" # stable key used for rollout
default: false
rules:
- id: "internal_on"
if: { attr: "isInternal", op: "==", value: true }
serve: true
- id: "enterprise_50pct"
if: { attr: "plan", op: "==", value: "enterprise" }
rollout:
percent: 50
salt: "new_checkout:v3" # change only when you intentionally reshuffle
serve: true
overrides:
forceOn: [ "org_123", "org_999" ]
forceOff: [ "org_555" ]
constraints:
maxPercent: 50
allowedEnvs: [ "staging", "prod" ]
Deterministic percent rollout (safe hashing)
Use a stable hash of (salt + ":" + bucketingKeyValue) and map to [0..9999].
Pseudo:
function bucket(key: string, salt: string): number {
const h = sha256(salt + ":" + key); // stable across languages
return (toUInt32(h.slice(0, 4)) % 10000); // 0..9999
}
function inRollout(b: number, percent: number): boolean {
return b < percent * 100; // percent in [0..100]
}
Rules of thumb
- Always include a salt (versioned) so you can intentionally reshuffle later.
- Pick one bucketing unit per flag (user vs org) to avoid surprises.
- Treat missing bucketing key as not in rollout (fail closed) unless you explicitly choose otherwise.
2) Kill-switch design (fast, independent, fail-safe)
Two-layer “off” mechanism
- Config-level off (normal ops): turn flag off by editing the flag.
- Emergency kill switch (break glass): separate control plane that can disable one flag, a family of flags, or an entire subsystem quickly even if your main flag system is unhealthy.
Kill-switch characteristics
- Out-of-band: stored/served separately from normal flag configs (e.g., a tiny replicated key-value store).
- Fast propagation: push-based or very frequent polling; cached locally with short TTL.
- Fail-safe default: if kill-switch service is unreachable, default to “killed = true” for risky features (or define a per-flag policy).
Example precedence:
if killSwitch[new_checkout] == ON (meaning “kill it”): return false
else evaluate normal rules...
Blast containment in the kill-switch itself
- Support scopes:
global (all traffic)
env (prod only)
region
tenant/org
- Support “kill classes”: e.g.,
payments/* to shut down a whole area.
Operational ergonomics
- “Break-glass” access with strong auth + mandatory reason + paging integration.
- One-click rollback to last-known-good config snapshot.
3) Experiment integration (no double-bucketing, correct exposure logging)
Feature flags and experiments should share:
- The same bucketing function
- The same subject key
- The same evaluation SDK
Recommended model: “experiment is attached to a flag”
A flag can have:
mode: rollout (gradual exposure)
mode: experiment (A/B test)
mode: hybrid (e.g., 10% experiment, then ramp)
Experiment config:
key: "new_checkout"
mode: "experiment"
variants:
control: { value: false, weight: 50 }
treatment: { value: true, weight: 50 }
exposureEvent:
name: "flag_exposed"
logOncePerSubjectPerVersion: true
Exposure logging (audit + analytics correctness)
Log when the user is actually exposed, not just evaluated.
- For backend: log on request paths that render/execute the behavior.
- For frontend: log after the UI actually displays the variant (avoid “prefetch exposure”).
Include:
- flagKey, flagVersion/configETag
- variant
- subject key (or hashed)
- rule id / bucket value
- timestamp
- request id / trace id
Guardrails for experiment quality
- Mutual exclusion groups: prevent overlapping experiments on the same surface.
- Holdouts: reserve a permanent control group for long-term measurement.
- SRM checks (sample ratio mismatch): alert if assignment deviates from expected.
- Avoid flicker: server-side evaluation or consistent client bootstrap.
4) Blast-radius controls (prevent “oops 100% prod”)
Hard constraints enforced by tooling (not by humans)
Add “policy” fields and validate in CI before publishing:
maxPercent allowed in prod
- allowed environments/regions
- requires allowlist before any rollout
- requires SLO monitors attached
- requires approval from owner/oncall above X%
Example policy enforcement:
- If
env == prod and percent > 10% → require 2 approvals.
- If flag is
risk: high → cannot exceed 1% without live error-budget green.
Progressive delivery patterns
- Canary by region: 1 region → 10% → 50% → all regions.
- Canary by tenant: internal tenants → friendly customers → random.
- Time-based ramp with automatic rollback triggers.
Automatic rollback (“circuit breaker for flags”)
Connect rollout increases to live telemetry:
- error rate
- latency
- critical business KPIs
If threshold exceeded after a change, auto-set:
- rollout percent to 0, or
- kill-switch to “killed”
Change safety: validation + simulation
- Schema validation (types, operators)
- “Dry-run evaluation” against sampled production contexts:
- “How many users would match rule #2?”
- “Which top tenants are affected?”
- Diff view: “previous vs proposed targeting”
5) Migration cleanup (flags must die)
Flags that never get removed become technical debt and risk.
Define a flag lifecycle
- Created (must include owner, purpose, ticket link)
- Ramping
- Stable
- Migration complete
- Remove flag (code + config)
Enforce cleanup with deadlines
- Require
expiresAt on creation (or after first prod enablement).
- Alert owner at T-14/T-7/T+0.
- After expiry:
- block further ramp-ups
- require explicit extension approval
Track “dead flags”
Automate detection:
- Never evaluated in last N days
- Always true/always false in prod
- Experiment ended and rollout is 100%
Safe removal technique
- Flip to constant behavior in code (keep flag but unused) → deploy
- Remove flag evaluation paths → deploy
- Remove config + delete from system → deploy
- Add linting: forbid referencing deleted flags
6) Auditability (who changed what, when, why; and who saw what)
Config change audit (control plane)
For every change, record immutable events:
- who (principal)
- when
- what changed (diff)
- why (required reason + ticket)
- approvals (who approved)
- where (env/region scope)
- config version / hash
Implementation patterns:
- Store flag config in versioned repo (GitOps) and treat merges as the change control.
- Or use an event-sourced config store that emits an append-only audit log.
Runtime audit (data plane)
Keep lightweight logs (sampled if necessary) for:
- exposures (for experiments + accountability)
- kill-switch activations
- evaluation failures / fallbacks
Tamper resistance
- Sign published configs (or store a content hash) and verify in SDK.
- Restrict write paths; read-only evaluation endpoints.
- RBAC by scope (team-only flags, prod changes gated).
Reference architecture (works well at scale)
Authoring
- UI or GitOps → validation/CI → approvals → publish
Distribution
- Publish immutable config bundles (ETag/versioned) to a CDN/object store
- Services/clients fetch + cache locally (with jittered polling)
- Optional: streaming updates for fast propagation
Evaluation
- Local SDK evaluates from cached config (low latency, resilient)
- Kill-switch fetched separately with short TTL
- Evaluation returns
{value, variant, reason, ruleId, version}
Observability
- Central metrics: evaluation errors, unknown flags, config age, exposure volume
- Alerting tied to rollout changes
Practical checklist (what to implement first)
- Deterministic hashing + stable bucketing key + rule precedence.
- Local evaluation with cached configs (no per-request network dependency).
- Emergency kill-switch (out-of-band) + fail-safe defaults.
- CI validation + policy constraints (maxPercent, approvals).
- Exposure logging “log once” + mutual exclusion groups for experiments.
- Flag lifecycle with expiry + automated dead-flag cleanup.
- Immutable audit log of config changes + signed config bundles.
If you share your environment (microservices vs monolith, client-side flags, multi-region, B2B vs B2C, regulatory constraints), I can propose a concrete schema and rollout/approval policy that fits your org and failure modes.