Design a Scalable Feature Toggling and Targeting Platform
System DesignModel answerLast updated
Design a feature flag service enabling dynamic percentage rollouts, user targeted overrides, and ultra-low latency evaluation across distributed microservices.
Design a dynamic feature toggling and user targeting system for a large-scale microservice architecture.
The system allows engineering and product teams to manage feature rollouts safely in real time. It must support:
- Global on/off switches.
- Explicit target lists (allow/block overrides for specific user IDs).
- Percentage-based gradual rollouts.
- Multi-variant experiment assignment.
System Requirements & Scale Constraints
- Read Traffic: 2,000,000 evaluation requests per second across hundreds of downstream services.
- Latency Budget: Evaluation must complete in under 1 ms at the $p_{99}$ level, without adding remote network round-trips to the critical path of individual service calls.
- Consistency: User assignment must be deterministic and sticky across devices/requests for a given rollout percentage.
- Propagation Speed: Flag updates made in the management console must propagate to all evaluation engines in under 2 seconds globally (and under 500 ms for emergency kill-switches).
- Availability: High availability ($99.999%$). Evaluation failure must fall back safely to local defaults without throwing runtime exceptions or blocking core user traffic.
Walk through your architecture, covering the control plane, execution/evaluation model, data model, hash-bucketing algorithm, propagation mechanism, and resilience strategies.
Hints
Hint 1
Think carefully about the trade-off between evaluating flags via a centralized REST/gRPC RPC service versus evaluating in-process using an SDK with locally cached configurations.
Hint 2
How do you guarantee sticky percentage bucketing using deterministic hashing without storing every user's assigned state in a database?
Hint 3
How can you push configuration changes to thousands of application instances with sub-second latency while keeping control plane load manageable?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
High-Level System Architecture
A robust feature flag system is fundamentally divided into two clear domains: the Control Plane (where flags are defined and edited) and the Data Plane (where flags are evaluated millions of times per second).
To satisfy the sub-millisecond latency requirement ($p_{99} < 1\text{ ms}$) at $2\text{M RPS}$, we cannot afford a remote network call for every evaluation. Therefore, evaluation is performed in-process via an Embedded Client SDK that reads from a local in-memory configuration engine.
+-------------------------------------------------------------------------------+
| CONTROL PLANE |
| |
| +--------------------+ +--------------------+ +-----------------+ |
| | Management Console | ---> | Control Plane API | ---> | PostgreSQL (DB) | |
| | (Admin UI) | | (Validation/Audit)| | (Persistence) | |
| +--------------------+ +---------+----------+ +-----------------+ |
| | |
+----------------------------------------|--------------------------------------+
| Publishes snapshot/delta events
v
+-------------------------------------------------------------------------------+
| DISTRIBUTION LAYER |
| |
| +---------------------------------------+ |
| | Message Streaming / PubSub (Kafka) | |
| +-------------------+-------------------+ |
| | |
| v |
| +---------------------------------------+ |
| | Distribution Service Engine (CDN / | |
| | Edge Cache / Server-Sent Events) | |
| +-------------------+-------------------+ |
+---------------------------------------|--------------------------------------+
| SSE / Websockets Push
v
+-------------------------------------------------------------------------------+
| DATA PLANE (Application Host) |
| |
| +-----------------------------------------------------------------------+ |
| | Microservice Process | |
| | | |
| | +-------------------+ Local Memory Sync +----------------------+ | |
| | | App Logic | <------------------ | Feature Flag SDK | | |
| | +-------------------+ | (Rules Engine & | | |
| | | In-Mem Ruleset) | | |
| | +----------+-----------+ | |
| +-------------------------------------------------------|---------------+ |
| | Exposure Logs |
+-----------------------------------------------------------|-------------------+
v
+-------------------------------+
| Kafka -> Analytics DB (ClickHouse)|
+-------------------------------+
1. Data Model & Rule Evaluation Engine
Ruleset Configuration Structure (JSON Payload)
The control plane serializes flags into an immutable, versioned JSON payload that is distributed to SDKs.
{
"flag_key": "new_checkout_flow",
"version": 42,
"enabled": true,
"default_variant": "off",
"variants": {
"off": false,
"on": true
},
"rules": [
{
"type": "BLOCK_LIST",
"attribute": "user_id",
"values": ["user_992", "user_401"],
"serve": "off"
},
{
"type": "ALLOW_LIST",
"attribute": "user_id",
"values": ["user_101", "user_102"],
"serve": "on"
},
{
"type": "ATTRIBUTE_MATCH",
"attribute": "country",
"operator": "IN",
"values": ["US", "CA"],
"rollout": [
{ "variant": "on", "weight": 2500 }, // 25.00%
{ "variant": "off", "weight": 7500 } // 75.00%
]
}
]
}
Evaluation Pipeline Algorithm
When an app requests SDK.evaluate("new_checkout_flow", context), rules are processed strictly in top-to-bottom order:
- Global Disable Check: If
enabled == false, immediately returndefault_variant. - Block List Check: If context matches a
BLOCK_LISTrule, return the overridden variant (off). - Allow List Check: If context matches an
ALLOW_LISTrule, return the overridden variant (on). - Targeting & Rollout Match: Evaluate standard rules (e.g., country matching). If matched, perform Deterministic Hash Bucketing using the rollout weights.
- Fallback: Return
default_variantif no rules match.
2. Deterministic Hash Bucketing (Sticky Rollouts)
To maintain consistency without storing state per user in a central database, we perform consistent hashing on the application host.
Hashing Strategy
- To assign user
uto a bucket between $0$ and $9,999$ (representing $0.00%$ to $100.00%$): $$\text{bucket} = \text{MurmurHash3}(\text{user_id} + ":" + \text{flag_key}) \pmod{10000}$$ - Salt Inclusion: Combining
user_idwithflag_keyensures that user distribution across different flags is statistically independent (preventing the same $10%$ of users from being selected for every new feature). - Sticky Rollouts: If the rollout increases from $10%$ to $20%$, any user whose hash mapped to $0–999$ remains in the active set (since their calculated hash value is static).
import mmh3
def evaluate_rollout(user_id: str, flag_key: str, rollout_weights: list) -> str:
# Hash input seed
seed = f"{user_id}:{flag_key}"
# MurmurHash3 returns a 32-bit unsigned integer
hash_val = mmh3.hash(seed, signed=False)
bucket = hash_val % 10000 # Scale to 0 - 9999
cumulative_weight = 0
for entry in rollout_weights:
cumulative_weight += entry["weight"]
if bucket < cumulative_weight:
return entry["variant"]
return "off"
3. Real-Time Configuration Distribution Strategy
Pushing configuration updates to thousands of application SDK instances globally within 2 seconds requires a hybrid push-pull transport architecture.
Propagation Pipeline
- Admin Action: An engineer updates a flag in the Control Plane Console.
- Persistence & Versioning: The Control Plane writes the change to PostgreSQL inside a transaction, incrementing the flag's
versioninteger, and emits a change event to a Kafka topic. - Distribution Edge Layer: A fleet of Distribution Nodes consumes Kafka events. These nodes maintain open persistent connections to every application instance via Server-Sent Events (SSE) or Long-Polling HTTP/2.
- SDK Local Refresh: The SDK receives the new configuration delta or complete JSON blob via SSE, validates the payload structure, and atomically swaps its internal lock-free pointer (
AtomicReference/ read-copy-update) to the new ruleset.
[Control Plane DB] ---> [Kafka Event] ---> [Distribution Fleet (SSE Servers)]
|
+-----------------+-----------------+
| SSE Persistent Push Connections |
v v
[Service SDK Host A] [Service SDK Host B]
Scalability of Connection Layer
If 5,000 backend application pods each maintain an SSE connection, a small cluster of 3–5 SSE Streaming Proxy instances can comfortably manage these connections using non-blocking I/O (epoll).
4. Availability, Resilience, and Failure Modes
Because feature flags gate production logic, a failure in the flag infrastructure must never bring down the primary applications.
| Failure Scenario | Mitigation Strategy |
|---|---|
| Control Plane DB Outage | Data Plane continues functioning independently using cached local memory rulesets. Admin edits are disabled until DB recovers. |
| SSE Distribution System Disruption | SDKs detect lost SSE connections, enter exponential backoff retry, and fall back to periodic HTTP polling against a static public CDN mirror (e.g., Cloudflare/S3) serving full snapshot configs every 10 seconds. |
| Malformed Rule Published | Control plane executes strict JSON schema validation and dry-run static analysis prior to DB commits. SDKs reject unparseable configurations and keep the last-known-good (LKG) ruleset in memory. |
| SDK Cold Start / Network Partition | SDK initializes from a bundled fallback file on local disk. If disk reading fails, hardcoded in-code defaults are served. |
5. Exposure Logging & Analytics
For multi-variant experimentation, product teams need to analyze which users were exposed to which feature variant.
- Non-Blocking In-Memory Queue: When
SDK.evaluate()is called, it computes the result synchronously and immediately places an Exposure Event ({user_id, flag_key, variant, timestamp}) onto a bounded, asynchronous in-memory ring buffer. - Batching & Flushing: A background thread flushes batched exposure events to a local collector agent or directly to a Kafka topic via HTTP/2 at configured intervals (e.g., every 5 seconds or 500 events).
- Deduplication: To avoid streaming millions of identical exposure events per second for hot users, the SDK utilizes a small local Bloom Filter or LRU Cache to record exposure events only once per user per flag version within a time window.
Key Trade-Offs & Design Decisions
-
In-Process Evaluation vs. Centralized RPC Evaluation
- Chosen: In-Process Evaluation SDK.
- Trade-off: Requires SDK implementations in multiple programming languages (Go, Java, Python, Node). However, it drops evaluation latency from ~5–10ms down to microsecond CPU operations and guarantees total resilience against network splits.
-
Full Snapshot Sync vs. Delta Streaming
- Chosen: Full Snapshot Sync for small configurations (<500 KB), and versioned Delta Syncs when rule volumes grow large.
- Trade-off: Full snapshots eliminate out-of-order delta reconciliation bugs at the cost of slightly higher network bandwidth during updates.