The user wants me to design and "implement" a feature flag system with gradual rollouts.
This is a system design problem, but it asks for "implementation," implying code and concrete architectural details, not just a high-level diagram.
Key requirements:
Server/Client SDK design: How do developers interact with the system?
Config delivery: How does the configuration get from the DB to the SDK?
Evaluation caching: How to make it fast?
Metrics: How do we know if it's working or if the flag caused an error?
Rollback paths: How to revert changes quickly.
Scope of implementation:
Since this is a text-based response, I cannot build a full distributed system with a UI, database, and CDN. I should provide a conceptual architecture followed by a core implementation in a specific language (likely Python or Go, or maybe TypeScript for full-stack) that demonstrates the logic. Let's stick to a Python implementation for the server-side logic and SDK interface, as it's readable and widely understood.
Structure of the response:
High-Level Architecture: The moving parts (Dashboard, API, DB, SDKs).
Data Model: What does a feature flag look like? (JSON schema).
Evaluation Logic: The core algorithm (Variants, Percentage Rollouts, Targeting).
Server-Side Implementation:
Config Management Service (Mocked).
Evaluation Engine.
Caching Strategy.
Client SDK Design: A lightweight wrapper.
Metrics & Observability: Tracking impressions and errors.
Let's write it.
This design outlines a complete Feature Flag system focusing on architecture, SDK implementation, caching strategies, and operational safety.
1. High-Level Architecture
The system consists of three main components:
Management Service & API: The administrative interface for setting flag states and rules.
CDN / Edge Storage: A high-availability layer (e.g., S3 + CloudFront or Redis) serving the "compiled" configuration.
SDKs (Server & Client): Libraries embedded in your application that fetch configs, cache them, and evaluate flags locally.
The Data Flow:
Admin changes a flag in the Dashboard.
Management Service publishes a JSON config to the CDN.
SDKs poll the CDN (or receive updates via SSE/Socket) to update their local cache.
Application code calls the SDK to evaluate the flag.
SDK sends usage/metrics data to the Metrics Pipeline asynchronously.
2. The Data Model
We need a flexible JSON structure to support standard boolean flags, variants, and gradual rollouts.
This SDK demonstrates local evaluation (offloading compute from the server) and polling for configuration updates.
A. Configuration & Cache Strategy
The SDK uses a background thread to fetch the latest configuration.
Cache Strategy: "Stale-While-Revalidate". The SDK serves the current config immediately while fetching the new one in the background. If the network fails, it keeps using the old config.
Cache Storage: In-memory dictionary (for single process) or Redis (for multi-process/server).
python
import threading
import time
import hashlib
import requests
import json
class FeatureFlagClient:
def __init__(self, sdk_key, config_endpoint, refresh_interval=30):
self.sdk_key = sdk_key
self.config_endpoint = config_endpoint
self.config = {"flags": {}}
self.etag = None
self.refresh_interval = refresh_interval
self._stop_event = threading.Event()
# Initialize cache
self._fetch_config()
# Start background poller
self._poller_thread = threading.Thread(target=self._poll_config)
self._poller_thread.daemon = True
self._poller_thread.start()
def _poll_config(self):
while not self._stop_event.is_set():
time.sleep(self.refresh_interval)
self._fetch_config()
def _fetch_config(self):
try:
headers = {"Authorization": f"Bearer {self.sdk_key}"}
if self.etag:
headers["If-None-Match"] = self.etag
response = requests.get(self.config_endpoint, headers=headers, timeout=5)
if response.status_code == 304:
# Config unchanged
return
if response.status_code == 200:
self.config = response.json()
self.etag = response.headers.get("ETag")
print("[SDK] Config updated successfully.")
else:
print(f"[SDK] Error fetching config: {response.status_code}")
except Exception as e:
# Network failure: Do nothing, keep existing config (Resilience)
print(f"[SDK] Fetch failed, using cached config. Error: {e}")
def stop(self):
self._stop_event.set()
def _hash_percentage(self, key, seed):
"""
Consistent hashing to ensure a user always falls in the same bucket.
"""
val = f"{seed}-{key}"
hash_val = int(hashlib.md5(val.encode()).hexdigest(), 16)
# Map to 0-100
return (hash_val % 100) + 1
def evaluate(self, flag_key, context, default=False):
flag = self.config.get("flags", {}).get(flag_key)
if not flag or not flag.get("enabled"):
return default
# 1. Whitelist Check (Overrides rollout)
user_rules = flag.get("rules", [])
for rule in user_rules:
# Simplified rule matching logic
if context.get("email") == rule.get("attributes", {}).get("email"):
return rule.get("result")
# 2. Gradual Rollout
rollout = flag.get("rollout")
if rollout:
bucket = self._hash_percentage(context.get("id"), flag_key)
percentage = rollout.get("percentage", 0)
if bucket <= percentage:
return True
else:
return False
return default
B. Usage in Application
python
# Initialization
ff_client = FeatureFlagClient(
sdk_key="sk_live_xxx",
config_endpoint="https://cdn.flagservice.com/config.json"
)
# Request Context
user_context = {"id": "user_123", "email": "bob@example.com"}
# Evaluation
if ff_client.evaluate("new_checkout_flow", user_context):
print("Showing new checkout")
else:
print("Showing old checkout")
4. Metrics & Observability
You cannot safely rollout or rollback without data. The SDK should capture metrics and send them asynchronously.
Metrics Strategy
Exposure Events: Every time evaluate is called, log that a user saw a variation.
Latency: Track how long the evaluation takes (should be < 1ms).
Errors: Track cache misses or configuration parse errors.
Implementation: Async Fire-and-Forget
Use a background queue to send metrics so it never blocks the user's request.
python
# Inside the SDK class...
def __init__(self, ...):
self.metrics_queue = []
def track_exposure(self, flag_key, user_id, enabled):
event = {
"event": "exposure",
"flag": flag_key,
"user": user_id,
"value": enabled,
"ts": time.time()
}
self.metrics_queue.append(event)
if len(self.metrics_queue) > 100:
self._flush_metrics()
def _flush_metrics(self):
# Send to analytics service (Datadog, Mixpanel, etc)
payload = self.metrics_queue[:]
self.metrics_queue = []
# Post payload to /metrics endpoint in a separate thread
5. Rollout & Rollback Strategies
Gradual Rollout (Canary Release)
The rollout.percentage field controls the flow.
0%: No one sees it.
10%: Internal testers + 10% brave users.
50%: Half traffic.
100%: Full release.
Important: When moving from 10% -> 20%, the algorithm must ensure that the original 10% are still in the 20% bucket (stickiness). The hashing logic _hash_percentage handles this naturally (if you are in bucket 5, you are in bucket 5 regardless of the ceiling).
Rollback Paths
A rollback is simply decreasing the percentage back to 0.
The "Kill Switch" Pattern:
For emergencies, implement a separate listener that checks a "Global Kill Switch" file (e.g., a highly available JSON file on a CDN) or a circuit breaker.
If the system detects error rates spiking (monitored via the Metrics pipeline), it can automatically flip the flag off without human intervention.
Client-Side Specifics:
For client-side SDKs (JS, Mobile), you serve a "bootstrap" config on page load. If a rollback happens:
Hard Rollback: Users must refresh the page to get the old feature (unless you have a WebSocket connection forcing a config reload).
Payload: Ensure the client SDK checks for updates every X seconds.