I need to design a system for feature flagging and gradual rollouts. This is a classic system design question.
1. Understand the Goal:
The user wants a system that allows developers to turn features on or off (feature flagging) and release them to a subset of users incrementally (gradual rollouts) without deploying new code.
2. Key Requirements & Functionalities:
Feature Flags: Create, update, delete, and read flags.
Targeting: Turn flags on/off for specific users, groups, or percentages of traffic.
Gradual Rollouts: Incrementally increase the percentage of users seeing a feature.
Client SDKs: Easy integration for various languages (Java, Python, JS, Go, etc.).
Dashboard/UI: For non-technical stakeholders (PMs) to manage flags.
Real-time (maybe): Do changes need to happen instantly? Usually yes, or near-instantly.
High Availability: If the flag service is down, the app might hang or use default logic. Resilience is key.
Performance: Minimal latency impact on the main application.
3. Non-functional Requirements:
Low Latency: Flag evaluation should be near zero-latency for the end-user.
High Availability: 99.99% uptime.
Scalability: Handle millions of requests per second.
Consistency: Eventually consistent (users shouldn't flip-flop between variations rapidly if possible, though standard A/B testing allows some drift).
4. High-Level Architecture:
Client Application: The service using the feature flag.
SDK: Embedded in the client app. Handles caching, evaluation, and streaming.
Control Plane (Admin Service): Where flags are configured. Includes API, Database, UI.
Data Plane (Evaluation Engine): Where flags are evaluated. This can be done server-side or client-side (via SDK).
5. Detailed Component Design:
The Database (Storage):
Needs to store Flag definitions (name, rules, status).
Relational (Postgres/MySQL) is fine for config data.
Maybe Redis for caching the ruleset for the ingestion servers.
The Control Plane (Management API):
CRUD operations for flags.
Writes to the Database.
Publishes updates to a message queue (Kafka) or Pub/Sub system to notify Edge/Proxy servers.
The Data Plane (Evaluation):
Option A: Server-side evaluation. Client calls API -> API checks flag -> returns result.
Pros: Secure, logic is hidden.
Cons: Adds network latency. High load on flag service.
Cons: Stale data (until next poll/stream), complex logic exposed to client (security risk if not careful).
Hybrid/Standard approach: Server-side SDKs embedded in the user's microservices. The SDK maintains a local cache of the rules and evaluates locally. It connects via Streaming (SSE/WebSocket) or polling to get updates. This is the LaunchDarkly/Unleash model.
6. Deep Dive: Gradual Rollouts (The Algorithm):
How do we ensure user X always sees the feature if they are in the 10% bucket?
We need a deterministic hashing algorithm (e.g., MurmurHash).
Input: User ID + Flag Key. Output: Hash value.
Normalize hash to 0-100.
If Hash(UserID, FlagKey) % 100 < Percentage, show feature.
This ensures "stickiness" (consistency) for the user.
What if the SDK initializes and can't reach the service?
Use a local file cache or default values (hardcoded).
9. Data Model:
FeatureFlag: ID, Name, Key, Status (on/off).
Variations: True/False or string variants.
Targeting Rules: List of conditions (e.g., user_id in ['1', '2'] or country == 'US').
RolloutRules: Percentage split logic.
10. Refinements/Advanced Topics:
Security: Ensuring unauthorized users don't toggle flags. Ensuring client-side SDKs (JS in browser) don't see rules meant for server-side.
Analytics: Tracking impressions. When a flag is served, send an async event to analytics pipeline.
Multivariate Flags: Not just boolean.
11. Structuring the Answer:
Introduction: Define the problem and requirements (Functional/Non-functional).
High-Level Architecture: The "Big Picture" (Admin vs. Data Plane).
Core Components: Detail the SDK, Service, DB, Streaming.
The Evaluation Mechanism: How rollouts work (Hashing).
Data Model: Database schema.
Handling Scale & Resilience: Caching, Fallbacks.
Analytics/Observability: Auditing changes.
Self-Correction/Review during thought process:
Initial thought: Should I suggest a proxy server?
Correction: Proxies add latency. Modern systems (like LaunchDarkly) rely heavily on the SDK doing the work in-process. The "service" acts more like a configuration broadcaster. I will focus on the SDK-based approach as it's the industry standard for high performance.
Clarification on Gradual Rollout: Make sure to emphasize Consistent Hashing (MurmurHash3) so the user experience is stable.
Drafting the Content:
Start with a clear diagram description.
Explain the "Write Path" (Configuration).
Explain the "Read Path" (Evaluation).
Explain the math behind the rollout.
Wrap up with reliability and monitoring.
Let's organize this into a clean, professional system design proposal.
Phase 2: System Architecture (Control Plane vs Data Plane).
Phase 3: Key Algorithms (Bloom filters? No, simple Hashing).
Phase 4: Data Storage.
Phase 5: Reliability.
Let's write it out.
Architecture:
Client Side: SDK.
Server Side: API (CRUD), Streamer (SSE), DB, Analytics.
Consistency: "Bucketing" logic.
Latency: Local evaluation is key.
(Self-Correction: Don't forget to mention that "Client" can be a backend microservice OR a browser/mobile app. The security considerations differ. I'll assume backend microservices primarily, but mention browser briefly.)
Final Polish:
Ensure clear headings, bullet points for readability, and a summary. The hashing logic is the "secret sauce" for rollouts, so highlight that.
Okay, ready to generate the response.
Designing a feature flagging system requires balancing real-time configuration updates with high availability and ultra-low latency. Unlike standard CRUD applications, a feature flag system sits in the "hot path" of your application code. If the flag service is down or slow, your entire application stops or slows down.
Below is a comprehensive design for a scalable Feature Flagging and Gradual Rollout system.
1. Requirements & Constraints
Functional Requirements
CRUD: Create, Read, Update, Delete feature flags.
Targeting: Enable flags for specific users, groups (e.g., "beta_testers"), or percentages of traffic.
The heavy lifting happens client-side (on your application servers). We do not make an HTTP request to a remote server for every flag check. That would introduce too much latency.
Initialization: When the application starts, the SDK fetches all relevant feature flag configurations and stores them in local memory (RAM).
Evaluation: When isFlagEnabled("new_checkout") is called, the SDK evaluates the logic purely against the local RAM. This ensures sub-millisecond performance.
Updates: The SDK listens to the Stream Service (via Server-Sent Events, WebSockets, or long-polling). When a flag changes, the Stream Service pushes the new config to the SDK, updating the local RAM.
B. Control Plane (Admin Service)
Database: A relational DB (PostgreSQL) is best here. We need ACID compliance for configurations.
Schema:FlagID, Name, Rules (JSONB), Status.
Audit Log: Every change must be versioned. If a rollout breaks production, you must be able to revert to the previous state instantly.
C. The Communication Pattern (Push vs. Pull)
To satisfy the "Real-time" requirement, standard REST polling is inefficient.
Streaming (Recommended): The SDK opens a persistent connection to the Stream Service.
CDN/Polling (Alternative): The Admin API updates a JSON file on a CDN (or highly optimized cache like Redis). SDKs poll this endpoint every 30-60 seconds. This is cheaper but has higher "time-to-live" (lag) for updates.
4. Algorithm: Targeting and Gradual Rollouts
To perform gradual rollouts (e.g., "Show feature to 10% of users"), we must ensure the user experience is deterministic and consistent.
Deterministic: User ID 123 sees the feature every time they refresh.
Consistent: User ID 123 is in the 10% bucket today, and will still be in that bucket tomorrow (unless the percentage increases).
The Bucketing Algorithm
We use a hashing algorithm (like MurmurHash) to map a User ID to a bucket.
Input:Hash(Key = FeatureFlagName + UserID)
Normalization: Convert the hash result (a large integer) into a percentage (0 to 100).
Check: Is NormalizedValue < RolloutPercentage?
Example Logic (Python):
python
def is_enabled(flag_key, user_id, rollout_percentage):
# Generate a hash based on the flag key and user id
hash_val = mmh3.hash(f"{flag_key}-{user_id}")
# Normalize to 0-100 (abs ensures positive, mod 100 maps to range)
bucket = abs(hash_val) % 100
return bucket < rollout_percentage
# If rollout is 50%:
# User A -> Hash -> 42 (Enrolled)
# User B -> Hash -> 88 (Not Enrolled)
# User A reloads -> Hash -> 42 (Still Enrolled)
Why this works for gradual rollouts:
If you increase rollout_percentage from 10% to 20%:
Users 0-9 remain enrolled.
Users 10-19 become newly enrolled.
No user who was previously enrolled gets "unenrolled" (unless you decrease the percentage).
Since this system is critical to application function, it must be resilient.
Local Fallback (Cached Config):
If the application restarts and cannot reach the Control Plane/Stream Service, the SDK should load the last known configuration from a local file (e.g., features.cache.json). This allows the app to start using "yesterday's" settings even if the network is down.
Stale Data Handling:
If the stream disconnects, the SDK continues serving the current config. It should log warnings but not crash or throw errors.
Performance Over Consistency:
In the event of a network partition, it is better to serve a slightly old flag configuration than to block the application request waiting for a timeout.
7. Security Considerations
Server-Side vs. Client-Side SDKs:
Server-Side: The SDK key allows reading all flags. Secure this key.
Client-Side (JavaScript/Mobile): The SDK key should be public-safe. The server should filter flags before sending them to the client so users don't see flags for features they aren't allowed to see or internal admin flags.
Permissioning: Implement Role-Based Access Control (RBAC) in the Control Plane. Junior devs shouldn't toggle critical infrastructure flags without approval.
8. Summary
This design relies on Edge Computation (the SDK). By moving the evaluation logic to the application server's memory, we achieve near-zero latency. By using a Control Plane with Push notifications, we achieve real-time updates. By using Deterministic Hashing, we enable safe, gradual rollouts that provide a consistent user experience.