1. Understand the Goal: The user wants a system design for feature flagging (also known as feature toggles) and gradual rollouts.
-
Identify the Core Requirements:
- Feature Flagging: Turning a feature ON or OFF without deploying code.
- Gradual Rollouts: Releasing a feature to a percentage of users or specific segments.
- Scalability: The system needs to handle potentially millions of requests (read-heavy).
- Latency: Checks must be extremely fast (milliseconds) so they don't slow down the user experience.
- Consistency: If a user sees a feature, they should generally keep seeing it (sticky sessions).
- Admin Interface: A way to manage flags.
- Security: Only authorized personnel can change flags.
-
High-Level Architecture:
- Client/Application: The code calling the flag check.
- SDK: A library embedded in the client app to handle caching and evaluation.
- Feature Flag Service (Backend): The central authority storing flag configurations.
- Database: Persistent storage.
- Admin UI/Dashboard: For human interaction.
- Analytics/Telemetry: Optional but useful for feedback loops.
-
Detailed Component Design:
-
Data Model:
- What does a Flag look like?
FlagID, Name, Description.
Status (Enabled/Disabled globally).
Rules:
- Boolean: True/False for everyone.
- Percentage: 10% of traffic.
- Targeting: User IDs, Email domains, Geo-location, Browser type.
- How do we handle targeting?
- Need an attribute map (User context).
-
The Evaluation Logic (The Brain):
- Input:
Flag Key, User Context (ID, attributes).
- Logic:
- Check if flag exists and is ON.
- Check specific targeting rules (e.g., User ID in list ['u1', 'u2']).
- Check percentage rollout (hashing).
- Default fallback.
-
The "Consistency" Problem (Hashing):
- For percentage rollouts (e.g., 10%), how do we ensure User A always gets the feature?
- Solution: Consistent Hashing (or a simple deterministic hash).
- Formula:
Hash(UserID + FlagID) % 100 < Percentage. This ensures User A always falls into the same bucket for the same flag.
-
Performance & Scalability (The bottleneck):
- Calling the backend API for every feature check is too slow and creates too much load.
- Solution 1: Server-side caching. (Redis).
- Solution 2: Client-side evaluation (SDK). The server pushes the rules to the client, and the client runs the logic locally. This is the gold standard (like LaunchDarkly or Unleash).
- SSE (Server-Sent Events) / WebSockets: To update the SDK instantly when a flag changes in the admin panel.
-
Structuring the System Design:
- Phase 1: Requirements & Constraints. (Latency, Availability, Consistency).
- Phase 2: API Design. (Endpoints).
- Phase 3: Database Schema. (SQL vs NoSQL).
- Phase 4: Architecture Diagram (Mental or ASCII).
- Phase 5: The "Secret Sauce" (Algorithms). (Hashing for rollouts).
- Phase 6: Scaling Strategies. (CDN, SDKs, Caching).
-
Refining the Design (Self-Correction):
- Initial thought: Just a simple REST API
GET /flags/user_id.
- Critique: Too slow. Network latency is a killer.
- Better approach: SDKs + Streaming. The configuration is downloaded, and evaluation happens in-process.
- Edge case: What if the flag service is down? The SDK should serve the last known good configuration.
-
Drafting the Content - Section by Section:
- Intro: Definition.
- Core Components: Admin UI, Service, DB, SDK.
- Data Model: JSON structure is flexible. Let's define a schema.
- Rollout Logic: Explain the hash function clearly. This is crucial for interviews.
- Architecture:
- Write path: Admin -> API -> DB -> Event Bus/PubSub -> SDKs.
- Read path: User Request -> App -> SDK (Local Memory) -> Result.
- Reliability: Fallbacks, dark launches.
-
Adding Nuance (The "Senior Engineer" touches):
- Mentioning sticky sessions (bucketer).
- Mentioning targeting groups (Canary vs. Beta).
- Trade-offs of SQL vs. NoSQL (Document store like Mongo/DynamoDB is usually better for arbitrary rule JSONs).
- Observability (InfluxDB/Prometheus) for tracking impression data (did the feature break conversion rates?).
-
Final Polish: Use formatting (bolding, lists, code blocks) to make it readable. Ensure the tone is professional and structured. (The prompt asks to "Design a system", so I should structure it like a system design interview response or a technical spec).
(Self-Correction during drafting): Should I talk about A/B testing?
- Feature flags are the foundation of A/B testing. I should mention that the system supports data export for A/B test analysis, but the core focus is the flagging mechanism itself.
-
Final Output Generation: (This matches the provided good response).
- High-level overview.
- Detailed algorithm for allocation.
- Architecture diagram components.
- Scalability/Caching.
- Resiliency.
Designing a feature flagging system requires balancing low latency (for the user experience) with consistency (for accurate rollouts).
Here is a comprehensive design for a scalable Feature Flagging and Gradual Rollout system.
1. Core Requirements
- Low Latency: Flag evaluation must happen in milliseconds to avoid slowing down the application.
- Scalability: Must handle reads from millions of users while handling infrequent writes from developers.
- Consistency: A user who sees a feature "ON" should continue to see it "ON" upon refresh (stickiness).
- Granularity: Support for global kill-switches, percentage rollouts, and user-segment targeting.
2. High-Level Architecture
The system follows a Read-Heavy pattern. We will use a Client-Side Evaluation strategy to ensure zero network latency for the end-user.
Components
- Admin Dashboard: UI for developers to create flags, define rules, and manage rollouts.
- Flag Management Service (CMS): The backend API that handles authentication, authorization, and updates to flag configurations.
- Database (RDBMS): Stores the "Source of Truth" for flag configurations and audit logs.
- Flag Delivery API (CDN Origin): A highly optimized read-only API that serves flag configurations to clients.
- Client SDKs: Libraries embedded in your application (Web, Mobile, Server) that download rules and evaluate flags locally.
3. The Data Model
We need to store the rules, not just the state.
Table: FeatureFlags
id: UUID
key: String (e.g., new_checkout_flow)
status: ENUM (ENABLED, DISABLED)
default_value: Boolean (What to return if no rules match)
rules: JSON (The core logic)
JSON Rule Structure Example:
{
"rules": [
{
"type": "user_id_list",
"values": ["user_1", "user_2"],
"return": true
},
{
"type": "percentage_rollout",
"percentage": 20,
"return": true
},
{
"type": "segment",
"segment_name": "beta_testers",
"return": true
}
],
"fallthrough": false
}
4. The Rollout Algorithm (The "Secret Sauce")
To perform a gradual rollout (e.g., 10% of traffic), we cannot simply use random() < 0.1. If we did that, a user might see the feature on page load 1, and not see it on page load 2.
We need Deterministic Hashing.
Algorithm:
- Take the
User ID and the Flag Key.
- Hash them together (e.g., using MurmurHash3).
- Map the hash to a number between 1 and 100.
- If the number <= Target Percentage, return
True.
Code Logic:
def is_feature_enabled(user_id, flag_key, percentage):
# Combine user and flag to ensure user gets different buckets for different flags
hash_input = f"{user_id}-{flag_key}"
# Get integer hash (e.g., 32-bit)
hash_val = murmurhash3(hash_input)
# Normalize to 1-100
bucket = (hash_val % 100) + 1
return bucket <= percentage
Result: User "Alice" will always fall into bucket 42. If you set the rollout to 40%, she never sees it. If you bump it to 50%, she sees it immediately and consistently.
5. Detailed Workflow
A. Configuration (The Write Path - Infrequent)
- Developer updates the "Dark Mode" flag from 10% to 20% in the Admin Dashboard.
- Admin Service validates the JSON rule and saves it to the Database.
- Admin Service invalidates the cache/publishes an event (SNS/PubSub) notifying that a config has changed.
- The Flag Delivery API rebuilds the configuration payload.
B. Evaluation (The Read Path - Frequent)
This is the Client-Side Evaluation approach.
- Initialization: The application starts. The SDK makes a single request to the Flag Delivery API (served via CDN) to download the JSON rules.
- Evaluation: Code calls
client.isFeatureEnabled("dark_mode", user_context).
- Local Execution: The SDK runs the logic locally in memory (nanoseconds).
- No network call is made during the request.
- Result: The app renders the UI based on the boolean result.
C. Real-time Updates (Polling vs. Streaming)
- Strategy A (Polling): The SDK polls the API every X seconds (e.g., 30s) for changes. Simple, but eventual consistency.
- Strategy B (Streaming): The SDK opens a WebSocket/Server-Sent Events connection to the Flag Service. When a flag changes, the server pushes the new config immediately. Best for "Kill Switch" scenarios.
6. Scaling and Infrastructure
To handle millions of users:
- CDN Caching: The configuration payload (JSON) should be served via a CDN (Cloudflare, CloudFront, Fastly).
- The SDK hits
https://flags.company.com/config.
- This never hits your actual servers; the edge cache serves the JSON.
- Targeting Segments:
- If you need to target "All users in Germany", passing the user's country into the SDK context (
user_context) allows the local evaluator to check if context.country == 'DE'.
- For complex segments (e.g., "Users who spent > $100"), the client might not have this data. In this case, you use a Server-Side Evaluation mode where the server queries the Data Warehouse to determine eligibility.
7. Safety and Best Practices
- Fail-Safe Defaults: If the SDK cannot reach the server to download rules (network down), or if the rule evaluation crashes, it must default to the
False (Safe) state hardcoded in the client.
- Audit Logs: Every time a percentage changes or a rule is added, record who did it and when.
- CI/CD Integration: Add a check in your deployment pipeline to ensure you don't delete a feature flag key that is still being referenced in the code.
Summary View
| Aspect | Solution |
|---|
| Latency | 0ms (Client-Side Evaluation via SDK) |
| Consistency | MurmurHash bucketing based on UserID |
| Data Storage | SQL (Metadata) + JSON (Rules) |
| Distribution | CDN (Edge caching of rules) |
| Updates | WebSockets/SSE (Push updates) or Short Polling |