Designing a feature toggle registry
I’m considering how to propose an architecture for a feature toggle registry that works across multiple languages, such as Go, Java, Python, and Node. I want to focus on schema design, SDK adapters, approval workflows, and observability hooks. It’s essential to keep the details concise but actionable. I need to cover aspects like data models, API configurations, targeting rules, and the toggle lifecycle, while also thinking about GitOps and RBAC implementations. Adopting some existing solutions like OpenFeature or LaunchDarkly could be beneficial for the user.Proposing a feature toggle architecture
I'm outlining an architecture for a central registry service that uses REST or gRPC, alongside backend storage options like PostgreSQL and Redis. For distributing configurations, I’m thinking about using a CDN, S3, or etcd, while ensuring consistency with OpenFeature semantics. I aim to create a blueprint that covers goals such as consistent evaluation, dynamic updates, and low latency. The data model will include tables for flags, environments, and audit logs, with a JSON schema for flag configurations detailing essential fields. Finally, I'll outline the API for registry operations and SDK adapters.Detailing implementation aspects
I’m laying out the implementation details for the feature toggle registry, focusing on configuration fetching, caching, and creating an evaluation engine. I’ll include typed getters and hooks, along with consistent hashing for rollouts and concurrency management, complete with pseudocode examples in various languages. The approval workflow will follow GitOps with a system state flow from draft to archived, ensuring automated checks and documenting approvals. Observability will involve metrics on evaluations, errors, and logs, while rollback processes will ensure quick reverts and system monitoring with guidelines for maintaining multi-service compatibility.Outlining a feature flag lifecycle and adoption roadmap
I’m defining the feature flag lifecycle that includes release phases, clean-up, and automatic reminders. The adoption roadmap will consist of several phases: inventory, selecting an engine, building a registry MVP, integrating services for each language, establishing governance, migrating existing flags, enabling a UI, turning on experiments, and eventually deprecating the old flags. I’ll specify the use of the OpenFeature spec for cross-language compatibility and implement security measures like RBAC and encryption. I'll make the final response structured with headings and bullet points for clarity.
0) Reference architecture (cross-language, consistent semantics)
Recommended backbone: OpenFeature as the unified SDK API across languages + a single “registry” that publishes versioned flag configurations to runtime evaluators.
A practical, low-latency layout:
- Registry service (control plane)
- CRUD flags, segments, environments, approvals, audit log
- Produces versioned config snapshots and deltas
- Stores config + history (Postgres) and caches (Redis)
- Distribution layer
/snapshot endpoint (or S3/CDN) for bulk config
- Optional SSE/WebSocket/Kafka for live updates
- Evaluation plane (data plane)
- Option A (recommended for services): run flagd as sidecar/daemon; apps call localhost → consistent behavior, minimal latency.
- Option B: SDK evaluates locally from pulled snapshot (no sidecar).
- Apps use OpenFeature SDK (Java/Go/Node/.NET/Python/etc.) with a provider:
- Provider talks to flagd (local) or loads snapshots and evaluates locally.
This splits “who can change flags” from “how apps read flags,” and makes cross-language parity realistic.
1) Schema design (registry + runtime config)
1.1 Core concepts
- Project / Namespace: logical boundary (team, domain)
- Environment: dev/stage/prod (each may have different rules/values)
- Flag: typed (boolean, string, number, json), with variations
- Segment: reusable targeting group (by attributes, allow/deny lists)
- Rule: conditions → serve variation, possibly with rollout %
- Prerequisites: flag A depends on flag B state (optional, use sparingly)
- Versioning: immutable published versions per env
1.2 Control-plane relational model (example)
Tables (simplified):
projects(id, key, name)
environments(id, project_id, key, name, tier)
flags(id, project_id, key, type, description, owner, tags, created_at, archived_at)
flag_versions(id, flag_id, version, created_at, created_by, change_summary)
flag_env_state(id, flag_version_id, environment_id, enabled, default_variation, off_variation)
variations(id, flag_version_id, key, value_json, description)
rules(id, flag_version_id, priority, name, condition_ast_json, serve_type, serve_target, rollout_json)
segments(id, project_id, key, name, definition_json, created_at)
rule_segments(rule_id, segment_id) (optional link table)
approvals(id, project_id, environment_id, change_set_id, status, requested_by, approved_by, timestamps…)
audit_log(id, actor, action, object_type, object_key, before_json, after_json, ts, request_id)
Key requirements:
- Immutability: published config is never edited; you publish a new version.
- Environment-specific publishing: same flag version can be promoted, or you can require per-env publish.
- Auditability: every change produces an audit event.
1.3 Runtime config schema (what SDK/flagd consumes)
Aim for a single JSON schema across languages. Example shape:
{
"schemaVersion": 1,
"project": "payments",
"environment": "prod",
"publishedAt": "2025-12-13T10:00:00Z",
"configVersion": "2025-12-13.1000.42",
"flags": {
"new_checkout": {
"type": "boolean",
"enabled": true,
"variations": {
"on": true,
"off": false
},
"defaultVariation": "off",
"rules": [
{
"name": "beta-segment-10pct",
"when": {
"all": [
{ "attr": "country", "op": "in", "values": ["US","CA"] },
{ "segment": "checkout_beta_users" }
]
},
"serve": {
"rollout": {
"bucketBy": "user_id",
"variation": "on",
"percentage": 10
}
}
}
],
"fallthrough": { "variation": "off" },
"metadata": {
"owner": "team-checkout",
"ticket": "PAY-1234",
"expiresAt": "2026-02-01"
}
}
},
"segments": {
"checkout_beta_users": {
"includes": ["user_123", "user_456"],
"excludes": [],
"rules": [
{ "attr": "email", "op": "endsWith", "value": "@example.com" }
]
}
}
}
Condition language: keep it boring and deterministic:
- Use a small operator set (
eq, in, contains, startsWith, matches, numeric comparisons).
- Avoid Turing-complete expressions.
- Define null/unknown behavior explicitly (usually “condition fails”).
Rollout hashing: specify hashing and bucketing precisely for parity:
- Hash: murmur3_32 or xxhash32
- Bucket:
hash(bucketByValue + flagKey + salt) % 100
- Document encoding (UTF-8) and normalization (lowercase keys, etc.)
1.4 Typed evaluation semantics (must be identical across languages)
Define:
- What happens when flag missing → return default + reason
FLAG_NOT_FOUND
- Wrong type → return default + reason
TYPE_MISMATCH
- Context missing attribute used in rule → rule fails (unless operator defines otherwise)
- Precedence:
disabled → prerequisites → rules by priority → fallthrough
Also define an evaluation result envelope (for logging/metrics):
flagKey, variationKey, value, reason, ruleId, configVersion, timestamp
2) SDK adapters (cross-language) and how to keep them consistent
2.1 Pick one unified API: OpenFeature
- Each language uses OpenFeature SDK
- You implement (or configure) a provider:
- Provider fetches snapshot/deltas (or talks to flagd)
- Provider performs evaluation (or delegates to flagd)
This avoids inventing N different SDKs with divergent semantics.
2.2 Provider modes
Mode A: flagd (sidecar)
- Pros: parity, fast, centralize evaluation engine, simpler SDKs
- Cons: operational footprint (sidecar/daemon)
Mode B: embedded evaluation
- Pros: fewer moving parts
- Cons: you must keep evaluation logic consistent in every language (hard)
For “cross-language parity,” Mode A is typically worth it for backend services.
2.3 SDK requirements checklist (all languages)
- Non-blocking startup: if registry unavailable, use last-known snapshot
- Local caching with:
maxAge + background refresh
- atomic swap on update
- Strong defaults:
- safe “off” defaults
- explicit timeouts
- Context model:
- standard fields:
targetingKey/user_id, session_id, tenant_id, device_id
- custom attributes map
- Stable hashing for rollouts (see schema section)
- Hooks:
- before/after evaluation
- error hook
- Optional “exposure events” for experiments (only emit when required)
2.4 Minimal adapter surface
Expose typed getters mirroring OpenFeature:
getBooleanValue(key, default, context)
getStringValue(...), getNumberValue(...), getObjectValue(...)
get*Details(...) to return evaluation envelope (variation, reason, version)
2.5 Compatibility & versioning
- Runtime config has
schemaVersion; providers must support N and N-1.
- Registry refuses publish if it would break declared minimum SDK/provider versions (store this per service).
3) Approval workflow (governance without slowing delivery)
3.1 Lifecycle states (per environment publish)
A practical state machine:
- Draft (editable)
- Ready for review (locks edits except by author)
- Approved (requires policy)
- Published to env (immutable snapshot version)
- Archived (cannot be evaluated; must be removed from code)
3.2 Policies to implement
- RBAC
- Owners per flag (
ownerTeam)
- Environment-level permissions (prod requires elevated role)
- Two-person rule for prod
- Change categories
- “Safe” (description/tags) vs “Risky” (rule/value changes)
- Automated checks
- Must have: owner, ticket link, expiry date (for temporary flags)
- Default variation must be safe (often “off”)
- Rollout must specify bucketBy and max percentage
- Validate condition AST against schema
- Scheduled publishes
- support “publish at time” with automatic audit entries
3.3 GitOps option (recommended for larger orgs)
- Source of truth = Git repo containing flag definitions (YAML/JSON)
- PR review = approval workflow
- Registry syncs from main branch and publishes versions
You can still provide a UI; the UI generates PRs.
4) Observability hooks (so toggles don’t become a blind spot)
4.1 Emit three event streams
- Evaluation events (high volume, sampled)
- flagKey, variation, reason, configVersion, ruleId, service, env, sdkVersion
- Change events (low volume, no sampling)
- who changed what, before/after summary, approvals, publish version
- Health events (provider/runtime)
- last refresh success, snapshot age, parse errors, registry latency
4.2 Metrics (Prometheus/OpenTelemetry)
Recommended counters/gauges:
flag_evaluations_total{flag, variation, reason, service, env}
flag_config_version{service, env} gauge (label value is tricky; better: info metric)
flag_snapshot_age_seconds{service, env}
flag_provider_errors_total{type}
flag_exposure_events_total{experiment, variation} (if experimenting)
4.3 Logs and traces
- Add OpenTelemetry span attributes on important spans:
feature.flag.key
feature.flag.variant
feature.flag.version
- Avoid PII: hash identifiers (or log only targetingKey hash).
- Provide an SDK hook so apps can attach flag decisions to request logs (selectively).
4.4 Debuggability tooling
- “Why did I get this value?” endpoint/tool:
- given flag + context → returns matched rule, reason, and computed bucket
- Config diff view between versions/environments
- Dashboard: top flags by eval volume, erroring flags, stale snapshots
5) Rollback choreography (fast, safe, and predictable)
5.1 Rollback design principles
- Versioned publishes: every publish produces
configVersion; rollback = republish previous version.
- Kill switch: per flag, an emergency “force off” (or force variation) that bypasses rules.
- Propagation guarantees: define SLA:
- e.g., “prod rollout change visible to 99% of instances within 30s”
- Client resilience:
- stale-but-valid snapshot continues to serve
- never crash on bad config; reject and keep last-known-good
5.2 Choreography runbook (typical incident)
- Stop the blast radius
- toggle kill switch / set enabled=false in prod env
- Confirm propagation
- watch
flag_config_version and snapshot_age
- Verify behavior
- check key service metrics (error rate, latency)
- Rollback code if needed
- if code path is unsafe even when “off,” you need code rollback (this is why defaults matter)
- Post-incident
- pin a temporary guardrail policy (e.g., max rollout% for that flag)
- create follow-up task to remove the flag
5.3 Safe rollout patterns
- Progressive delivery: 1% → 5% → 25% → 50% → 100%, with automated gates
- Ring-based: internal users → beta tenants → small region → global
- “Dark launch”: run code path but don’t expose (measure performance)
- Schema/data migrations:
- Use “expand/contract” (write both schemas before reading new)
- Never rely on a flag to protect a destructive migration without additional safeguards
6) Adoption roadmap (reduce risk, avoid flag sprawl)
Phase 1 — Foundation (1–3 weeks)
- Choose: OpenFeature + flagd (or embedded provider if you must)
- Define:
- runtime schema v1
- evaluation semantics doc (type mismatch, missing attrs, hashing)
- naming conventions (
team.domain.flag_purpose)
- Build registry MVP:
- CRUD flags/segments
- publish snapshot per env
- audit log
Phase 2 — First production integration (2–4 weeks)
- Pick 1–2 services (different languages) + one non-critical flag
- Add:
- provider health metrics + snapshot age
- evaluation logging (sampled)
- “why” debugger tool
- Establish on-call runbook for toggle incidents
Phase 3 — Governance & workflow (3–6 weeks)
- Add approvals:
- two-person prod approval
- required metadata (owner, expiry, ticket)
- Add promotion flow:
- dev → stage → prod with diffs
- Add guardrails:
- max rollout caps
- scheduled changes
- automatic expiry reminders
Phase 4 — Broader rollout (ongoing)
- Provide language templates/snippets:
- standardized context construction middleware
- OpenTelemetry hook defaults
- Migrate existing flags from ad-hoc configs
- Add “flag cleanup” program:
- monthly report: stale flags, flags at 100% for >30 days, unused flags
- make cleanup part of “definition of done”
Phase 5 — Advanced (optional)
- Experiments (A/B):
- exposure events
- consistent assignment
- analysis pipeline
- Self-serve UI with GitOps backing
- Multi-region registry with eventual consistency and strict publish ordering
Decisions you should lock early (to avoid cross-language drift)
- Evaluation location: sidecar (flagd) vs embedded
- Condition language: fixed operator set + JSON schema
- Hashing algorithm and bucketing spec
- Event semantics: what is an “evaluation event” vs “exposure event”
- Promotion model: per-env approvals and immutable publishes
- Flag lifecycle enforcement: expiry required or not
If you answer these 6 questions, I can tailor this into a concrete deployment plan (stack + milestones + schemas)
- Which runtimes/languages are in scope (backend only, or mobile/web too)?
- Do you want sidecars/daemons (flagd) allowed in your platform?
- How many environments/regions, and do you require multi-region control plane?
- Do you need experiments (A/B) now, or only feature release toggles?
- Any compliance constraints (SOC2, HIPAA) that affect audit/PII?
- What’s your current state (any existing flag system to migrate)?