Feature Flag System — Flag Evaluation & Experimentation Platform
A deep dive into designing a production-grade feature flag system — from flag evaluation and targeting rules to client-side SDKs with SSE sync, A/B testing, gradual rollouts, and kill switches.
FrontendX EngineeringSystem Design Series
0. What Are We Building?
We are building a feature flag and experimentation platform that lets product teams ship code behind toggles and roll it out gradually. Think LaunchDarkly meets Google Optimize — a system where you define a flag once, configure who sees what through targeting rules, and watch the rollout progress from a dashboard.
Feature flags are surprisingly subtle infrastructure. They look like simple boolean toggles but quickly evolve into a critical part of your deployment pipeline — teams use them for canary releases, trunk-based development, A/B experiments, and emergency kill switches. When the flag system goes down, deployments stop, experiments lose data, and teams cannot disable a broken feature. The platform must be fast (flag evaluations happen on every HTTP request), highly available (flags are read far more often than written), and consistent (a user must see the same flag value for the duration of their session).
Key Insight
The hardest part of a feature flag system is not the flag evaluation logic. It is the latency vs. consistency tradeoff: client-side SDKs evaluate locally for speed, but the flag configuration must propagate to millions of devices within seconds of a change. One engineer toggling a flag in the dashboard expects every SDK to reflect that change immediately.
1. Requirements & Scoping
A feature flag system is not just a key-value store with a UI. It is a real-time configuration distribution system with deterministic targeting, audit trails, and experimentation support. Before we design, we scope what the system must do.
Functional
Flag CRUD — create, read, update, archive flags via dashboard and API
Targeting rules — user %, geo, plan, custom attributes
Kill switch — instantly disable any flag across all environments
Gradual rollout — percentage-based canary releases with staged progression
A/B testing — split traffic into experiment groups with statistical tracking
Client-side SDK — local evaluation with SSE/WebSocket real-time sync
Flag management UI — dashboard for creating, editing, and monitoring flags
Audit log — every flag change recorded with who and when
Non-Functional
Evaluation latency: <10ms for local evaluation, <50ms for server-side
High availability: 99.99% uptime — flags are read on every request
Consistency: sticky bucketing — same user gets same flag value per session
Propagation latency: <2s from dashboard toggle to SDK update
SDK bundle: <10KB gzipped for core flag client, <5KB for React bindings
Graceful degradation: cached flags and default values when network is unavailable
Security: flag configs scoped by environment, role-based access control
Nice-to-Have (Out of Scope for Core Design)
Multivariate flags — flags with more than two variations (e.g., showing 3 different button designs).
Scheduled rollouts — automatic flag progression at pre-set times.
Flag analytics dashboard — metrics on how many users see each flag variation.
Slack/Webhook integrations — notify teams when flags change.
Tip
In an interview, the first clarifying question should be: "Is this a simple toggle service or a full experimentation platform with A/B testing and statistical analysis?" The answer determines whether you need bucketing algorithms, experiment tracking, and a data pipeline for metric collection.
2. Flag Data Model & Architecture
Every flag is a versioned document with multiple variations, targeting rules, and environment-specific overrides. The data model is the foundation — a well-designed flag schema makes the evaluation engine simple; a poorly designed one creates a tangle of edge cases.
The Flag Document
Each flag has a globally unique key(like new-checkout), a set of variations (typically true/false for boolean flags or named values for multivariate flags), and an ordered list of targeting rules. The defaultRule determines the value when no rules match. The isKilled flag is the highest-priority override — when true, every evaluation returns the kill switch value regardless of rules.
Targeting rules are evaluated in priority order. Each rule contains a list of conditions that are AND-ed together. If all conditions match, the user gets the rule's variation. If no rule matches, the default value is returned. Conditions can check user IDs directly, geo-location, subscription plans, custom attributes, or a percentage bucket.
Engineers manage flags via UI or REST API. Changes are written to the flag store.
Flag Store
PostgreSQL primary store with Redis cache. Flag configs versioned for audit.
CDN / Polling Endpoint
Flag configs cached at the edge. SDKs poll every 30s for updates.
SSE / WebSocket Gateway
Real-time push when flags change. SDKs receive flag_update events.
Client-Side SDK
Local evaluation with cached rules. No network call per flag check.
Server-Side SDK
Evaluates with full user context (DB lookups, auth). Returns resolved values.
Key Insight
The architecture separates read path from write path completely. The dashboard writes to the flag store, which invalidates the CDN cache and publishes an SSE event. The SDK reads from its local cache or the CDN — it never hits the flag store directly. This means flag evaluation scales with the number of SDK instances, not the number of flag store connections.
3. Deterministic Bucketing — The Foundation
Every targeting rule that involves percentages relies on deterministic bucketing. Given a user identifier and a flag key, the bucketing function must always return the same bucket number. This is what makes percentage-based rollouts fair and reproducible — a user in the 10% group stays in the 10% group across page reloads.
How Bucketing Works
The bucketing function hashes the concatenation of the flag key and user identifier using FNV-1a, then takes modulo 1000. This produces a bucket number between 0 and 999. A 10% rollout means buckets 0–99 see the new feature; buckets 100–999 see the old one. Because the hash is deterministic, the same user always lands in the same bucket for the same flag.
bucketing.tsTypeScript
function computeBucket( identifier: string, flagKey: string, totalBuckets: number = 1000): number { const hash = hashFNV1a(`${flagKey}:${identifier}`); return hash % totalBuckets;}function evaluatePercentage( user: UserContext, flag: FlagDefinition, rule: PercentageCondition): boolean { const bucketKey = rule.bucketing.key; const identifier = resolveAttribute(user, bucketKey); const bucket = computeBucket(identifier, flag.key); const threshold = rule.percentage * 10; // 10% → buckets 0-99 return bucket < threshold;}// Deterministic: same user, same flag, same bucket every time// Evenly distributed: any user has equal chance of any bucket
Why Bucketing Matters for A/B Tests
When running an A/B experiment, you split users into a control group (sees the old experience) and a treatment group (sees the new one). The split must be stable — a user who saw the treatment on Monday must see the treatment on Tuesday, or the experiment data is meaningless. Bucketing guarantees this stability as long as the flag key and user identifier do not change. It also ensures that overlapping experiments on different flag keys produce independent splits — the same user may be in the treatment group for one experiment and the control group for another.
Algorithm
FNV-1a
MD5
MurmurHash3
Speed
Fastest — ~5 CPU cycles/byte
Moderate — ~10 cycles/byte
Very fast — ~3 cycles/byte
Distribution quality
Good — passes diehard tests
Excellent — cryptographic
Excellent — designed for hashing
Output size
32-bit integer
128-bit
32/128-bit
SDK usage
LaunchDarkly default
Overkill — too heavy for client SDK
Split.io default
Warning
Never use Math.random() for flag evaluation. It breaks bucketing determinism — the same user gets different values on every page load. Always use a hash of (flagKey + userIdentifier) to ensure sticky assignments.
4. Flag Evaluation Pipeline
The evaluation pipeline is the heart of the system. Every flag check follows the same sequence of steps, from kill switch override down to the default fallback. Both the client-side SDK and server-side SDK implement the same pipeline, ensuring consistent behavior regardless of where evaluation happens.
The Evaluation Pipeline
1. Kill Switch Check
If flag.isKilled is true, return killSwitchValue immediately. Bypasses all rules.
2. User Override
Check if a specific user override exists (set via dashboard for testing).
3. Targeting Rules▾
Iterate through rules in priority order. First match wins.
Geo: Check user country against allowed list
Plan: Check subscription tier
Custom: Check arbitrary user attributes
Percentage: Check user bucket against threshold
4. Default Rule
If no rules match, return the flag's default value.
Server-Side vs Client-Side Evaluation
Server-side evaluation is authoritative: it has access to the full user context — subscription plan from the billing database, email, account creation date, and any internal attributes that should not be exposed to the client. The server evaluates the flag and returns the resolved value to the client in the API response. Client-side evaluation is faster: the SDK has the flag rules cached locally and evaluates in <10µs without a network call. The tradeoff is that client-side evaluation only has access to what the client knows — user ID, country from the browser's locale, and any custom attributes you explicitly pass.
server-side-evaluation.tsTypeScript
// Server-side evaluation — full context available// Used when flags depend on server-only data (auth, billing)app.post('/api/flags/evaluate', async (req, res) => { const { flagKeys, session } = req.body; const user = await db.users.findById(session.userId); const subscription = await db.subscriptions .findActiveByUser(user.id); const results: Record<string, FlagValue> = {}; for (const key of flagKeys) { const flag = await flagStore.getFlag(key); results[key] = flagEvaluator.evaluate(flag, { id: user.id, email: user.email, country: user.country, plan: subscription.tier, betaFeatures: user.betaOptIn, createdAt: user.createdAt, }); } res.json({ flags: results });});// Response (HTTP 200):{ "flags": { "new-checkout": true, "recommendation-v2": "treatment", "dark-mode": false }}
5. Client-Side SDK — Architecture & Design
The client-side SDK is the most performance-sensitive component of the system. It runs in the browser alongside the application code and must never block rendering, never throw uncaught exceptions, and never leak memory. The SDK's job is to fetch flag configurations, keep them in sync with the server, and evaluate them locally in microseconds.
Initialization & Flag Payload
On initialization, the SDK downloads the full flag configuration for its environment — a JSON payload containing all flag keys, their current values, targeting rules, and version numbers. The payload is cached in memory and persisted to localStorage. Subsequent page loads check localStorage first and refresh from the CDN in the background, so flag evaluation is instant even when the network is slow.
Once the SDK has the flag payload, all evaluations are local. The getVariation() method takes a flag key and an optional user context, runs the evaluation pipeline in memory, and returns the resolved value. No network call is made. This is what makes feature flag SDKs fast — a flag check is a hash computation and a few condition checks, not an HTTP round trip.
sdk-evaluation.tsTypeScript
class FlagClient { private flags: Map<string, FlagEvaluation> = new Map(); private listeners: Set<FlagListener> = new Set(); getVariation<T extends FlagVariationValue>( flagKey: string, user?: UserContext ): T { const evaluation = this.flags.get(flagKey); if (!evaluation) { return this.config.defaultValues[flagKey] as T; } if (evaluation.isKilled) { return evaluation.killSwitchValue as T; } // For simple boolean flags, return value directly if (!user || !evaluation.hasTargetingRules) { return evaluation.value as T; } // Re-evaluate targeting rules on the client return this.evaluateTargeting( flagKey, evaluation, user ) as T; } private evaluateTargeting( flagKey: string, evaluation: FlagEvaluation, user: UserContext ): FlagVariationValue { for (const rule of evaluation.targetingRules) { if (this.matchRule(rule, user, flagKey)) { return rule.variation; } } return evaluation.value; }}
Real-Time Sync via SSE
Polling alone is not enough. When an engineer toggles a flag in the dashboard, all active SDK instances should reflect the change within seconds. The SDK maintains a persistent SSE (Server-Sent Events) connection to a gateway server. When a flag changes, the gateway pushes a flag_update event with the flag key and new value. The SDK updates its local cache and notifies listeners.
The cache layer has two tiers: an in-memory map for microsecond-fast access during the current page session, and localStorage for persistence across page reloads. Each cached entry has a TTL — after the TTL expires, the SDK refreshes from the CDN on the next access. SSE updates invalidate the cache immediately, so active sessions see changes in real time while idle tabs get them on the next interaction.
For React applications, the SDK provides a useFlag hook that subscribes to flag changes and re-renders automatically when the value updates. The hook accepts a flag key and an optional user context, and returns the resolved value plus a loading state for the initial fetch.
Start with SSE. It is simpler, has built-in browser auto-reconnect, and works through any HTTP proxy. Migrate to WebSocket only if you need client-to-server flag updates (e.g., user-level overrides submitted from the SDK) or if your HTTP/2 deployment makes the 6-connection limit irrelevant.
6. A/B Testing & Experimentation
A/B testing is the reason many companies adopt a feature flag platform in the first place. The flag system provides the infrastructure for splitting traffic, but the experimentation pipeline — metric collection, statistical analysis, and decision reporting — is a separate system that consumes the flag evaluation data.
Experiment Lifecycle
Define experiment
Select a flag, define control and treatment variations, set traffic allocation.
Assign users to groups
Bucketing deterministically assigns each user to control or treatment.
Compare metric distributions, compute p-value and confidence intervals.
Make decision
Roll out treatment to 100%, iterate, or kill the experiment.
Experiment Tracking Events
Each time a user is assigned to an experiment variation, the SDK fires an assignment event: { experiment: 'new-checkout-test', variation: 'treatment', user: 'user_123', bucket: 42 }. This event flows into the analytics pipeline alongside the metric events that measure the experiment's success. The experiment analysis system joins assignment data with metric data to compute the treatment effect.
Key Insight
The most common mistake in A/B testing is peeking — checking results every hour and stopping the experiment as soon as a metric reaches significance. This inflates the false positive rate dramatically. A proper experimentation platform enforces a minimum sample size and recommended duration before the results are considered valid.
7. Gradual Rollout & Kill Switch
Gradual rollout and kill switch are two sides of the same coin. A gradual rollout increases traffic incrementally, monitoring metrics at each stage. A kill switch reverses instantly — cutting traffic to zero with a single toggle. Both rely on the same flag evaluation pipeline, just configured differently.
Gradual Rollout Stages
A staged rollout defines a sequence of traffic percentages, each with a minimum duration and optional approval gate. The system automatically tracks how long the current stage has been active and whether all success metrics are passing before allowing progression to the next stage. This prevents the common mistake of jumping from 5% to 100% and discovering a critical bug only after it affects everyone.
The kill switch is the highest-priority override in the evaluation pipeline. When a flag is killed, every evaluation returns the kill switch value regardless of any targeting rules or overrides. The kill switch is designed for emergencies — an engineer discovers a data-corrupting bug in the new checkout flow and clicks "Kill" in the dashboard. Within two seconds, every SDK instance stops showing the broken feature.
kill-switch.tsTypeScript
// Server-side kill switch — highest priority// When toggled in dashboard, flag.isKilled = true// Propagated to SDKs via SSE within ~500ms// SDK evaluation path (simplified):function resolveFlag(flagKey: string, user?: UserContext): FlagValue { const flag = store.getFlag(flagKey); // 1. Kill switch — unconditional override if (flag.isKilled) return flag.killSwitchValue; // 2. User-specific override (dashboard) if (user && flag.userOverrides.has(user.id)) { return flag.userOverrides.get(user.id)!; } // 3. Targeting rules for (const rule of flag.rules) { if (evaluateRule(rule, user, flagKey)) { return rule.variation; } } // 4. Default fallback return flag.defaultValue;}// Dashboard: one click to killPOST /api/v1/flags/new-checkout/kill{ "isKilled": true, "killSwitchValue": false }// All SDKs receive flag_update SSE event within 500ms
Operation
Latency to SDK
Mechanism
Toggle flag on/off
~500ms via SSE, ~30s via polling
SSE push + CDN cache invalidation
Kill switch
~500ms via SSE, ~30s via polling
SSE push + local cache invalidation
Advance rollout stage
~500ms via SSE, ~30s via polling
Flagon config updated + SSE push
User override
~500ms via SSE, ~30s via polling
Overrides included in flag payload
Warning
A kill switch is not a rollback. When you kill a flag, the feature code is still running in the application — the flag just returns the fallback value. If the broken feature has already corrupted data (e.g., written bad records to the database), the kill switch prevents further damage but does not undo it. Always pair kill switches with automated data validation and alerting.
8. Flag Management UI
The management UI is where product managers, engineering leads, and SREs interact with the flag system. It must be fast, intuitive, and provide full visibility into every flag's state and change history. The UI is built as a single-page application that communicates with the flag API layer.
Dashboard API
The dashboard API follows RESTful conventions with a flat URL structure. Each flag is addressed by its key, and operations like toggling, killing, and overriding are separate endpoints that trigger specific actions — not generic PATCH endpoints. This makes the API self-documenting and the audit log meaningful: we know exactly what action was taken, not just that something changed.
management-api.tsHTTP
// Flag CRUDPOST /api/v1/flags // Create a flagGET /api/v1/flags // List all flagsGET /api/v1/flags/:key // Get flag detailPUT /api/v1/flags/:key // Update flagDELETE /api/v1/flags/:key // Archive flag// Flag operationsPOST /api/v1/flags/:key/toggle // Toggle on/offPOST /api/v1/flags/:key/kill // Kill switchPOST /api/v1/flags/:key/rollout // Start/advance rolloutPOST /api/v1/flags/:key/rules // Add targeting rule// OverridesPUT /api/v1/flags/:key/overrides/:userIdDELETE /api/v1/flags/:key/overrides/:userId// AuditGET /api/v1/flags/:key/audit-log // Full change historyGET /api/v1/flags/:key/usage // Flag evaluation metrics// EnvironmentsGET /api/v1/environments // List environmentsPOST /api/v1/environments/:id/clone // Clone flag configs
Audit Log & Change History
Every change to a flag is recorded in an immutable audit log. Each entry includes the actor, timestamp, previous value, new value, and an optional comment. The audit log is critical for compliance (SOC 2, ISO 27001) and debugging — when a feature breaks in production, the first question is usually "who changed the flag and when?"
Flag Management UI Layout
Screen
Purpose
Flag list
Searchable, filterable table of all flags with status, environment, and last modified. Quick-toggle and kill buttons.
Flag detail
Full flag configuration, targeting rules editor, rollout stage management, user overrides.
Audit log
Timeline of all changes with actor, diff, and test status.
Experiments
A/B test configuration, metric selection, results dashboard with statistical significance.
Environments
Manage development, staging, production environment configs. Clone flag settings between environments.
Note
The UI is a CRUD app on top of the flag API, but with one critical difference: almost every action triggers a real-time propagation event. When an engineer kills a flag in the dashboard, the server updates the flag store, invalidates the CDN cache, publishes an SSE event, and records the audit log entry — all in a single transaction. The SDK should receive the update within 500ms.
9. Tradeoffs & Alternatives
Every architectural decision in a feature flag system involves a tradeoff. Understanding these tradeoffs is what separates a production-grade design from a toy.
Client-Side vs Server-Side Evaluation
Criterion
Client-Side Evaluation
Server-Side Evaluation
Latency
~5µs — local, no network call
~5–20ms — includes network round trip
Context available
Only what the client knows (ID, locale, custom params)
Full backend state (plan, billing, internal flags)
Security
Rules are visible in DevTools — avoid exposing sensitive attributes
Rules stay on server — no exposure of business logic
Offline capability
Full — cached rules evaluate without network
None — requires server connectivity
Bundle size
~10KB — includes evaluation engine
Not applicable (server-side)
Real-world example
LaunchDarkly JS SDK
LaunchDarkly Relay Proxy
Polling vs Push (SSE/WebSocket)
Criterion
Polling
SSE (Push)
Update latency
Up to polling interval (typically 30s)
Sub-second
Server load
Higher — every SDK polls on a timer
Lower — idle connections, no periodic requests
Complexity
Trivial — setInterval + HTTP GET
Moderate — connection management, reconnect logic
Battery on mobile
Worse — periodic wake-ups drain battery
Better — single persistent connection
Best practice
Fallback when SSE/WebSocket is unavailable
Primary sync mechanism
localStorage vs IndexedDB for Cache
Criterion
localStorage
IndexedDB
API
Simple synchronous get/set
Async, promise-based
Read speed
~10µs — synchronous, main thread
~100µs — async, may involve IPC
Storage limit
~5MB per origin
Large — 50% of disk, up to several GB
Blocking
Synchronous — blocks main thread briefly
Async — does not block
Flag SDK usage
LaunchDarkly default — flags are small JSON
Overkill for flag configs under 100KB
Key Insight
localStorage is the right choice for flag caching. Flag payloads are small (typically 5–50KB total), the synchronous read is faster, and the 5MB limit is more than enough for thousands of flags. IndexedDB only becomes necessary if you are storing large flag-related data like experiment assignment logs or custom scripts.
10. Key Takeaways
If you remember only a few things from this article, make them these:
Bucketing must be deterministic and stable
Hash (flagKey + userId), not Math.random(). Same user, same bucket, every time. Essential for consistent A/B assignments and gradual rollouts.
Separate read path from write path
SDKs never hit the flag store directly. They read from local cache or CDN. Only the dashboard writes. This makes flag evaluation scale horizontally.
SSE for real-time push, polling as fallback
SSE gives sub-second flag propagation with built-in auto-reconnect. Fall back to polling (every 30s) when SSE is unavailable. Never use WebSocket unless you need bidirectional communication.
Kill switch is the highest priority override
It bypasses all targeting rules and user overrides. Designed for emergencies — propagates to all SDKs within ~500ms via SSE.
Start with client-side evaluation for speed
Local evaluation is microseconds, not milliseconds. Use server-side evaluation only when the flag depends on server-only context (plan, billing, internal attributes). Provide both SDKs and let teams choose.
Every flag change is an audited event
Immutability record for compliance, debugging, and rollback. Include actor, timestamp, before/after values, and comment.