We have:
FeatureFlag:
id
name
is_active: boolean
rules: list of Rule
Rule:
id
condition: Condition (abstract, with subclasses: UserAttributeCondition, PercentageCondition, etc.)
action: Action (abstract, with subclasses: EnableAction, DisableAction, AssignVariationAction)
Then, for an experiment, we might have:
condition: PercentageCondition(50) -> 50% of users
action: AssignVariationAction(variation_id="treatment")
But then how do we split the 50% into multiple variations? We can have:
We can have multiple rules for the same condition? But condition is the same? Not necessarily.
Alternatively, we can have:
In the experiment, we define:
Experiment:
flag_id
variations: [ {id: "control", weight: 0.5}, {id: "treatment", weight: 0.5} ]
condition: PercentageCondition(100) -> 100% of users are in the experiment, but then split by weights.
Then, when evaluating, we:
- Check if the user is in the experiment (by condition, e.g., 100% of users, or 50% of users, etc.)
- If yes, then assign a variation based on the weights.
But then we might have multiple experiments on the same flag? Probably not, one experiment per flag at a time.
So we can have:
FeatureFlag:
id
name
is_active: boolean
rules: list of Rule (for non-experiment targeting)
experiment: optional Experiment
Experiment:
condition: Condition (e.g., PercentageCondition(100) for all users, or 50% for half)
variations: list of Variation (with id, value, and weight)
Then, when evaluating:
if flag.is_active is false -> return disabled (or a default).
Then, if there is an experiment and the experiment.condition matches the user, then assign a variation by weight.
Then, if no experiment condition matches, then go through the rules.
But note: we might want to have rules that override the experiment? For example, target a specific group to always get the treatment.
We can design:
Step 1: Check if the flag is active? If not, return disabled.
Step 2: Check the rules in order. If a rule condition matches, then:
- If the rule action is enable/disable, return that.
- If the rule action is assign_variation, then return that variation.
Step 3: If no rule matches, then check if there's an experiment and the experiment condition matches? But what if we want the experiment to be the default?
Alternatively, we can have:
The experiment is just a special rule? But then how do we handle the weights?
Let's think of the experiment as a rule that has a condition that matches a percentage of users and then assigns a variation randomly by weight.
We can have:
Rule:
condition: Condition
action: Action
And for the experiment, we create a rule with:
condition: PercentageCondition(percentage) -> this condition matches for a given percentage of users (by a deterministic hash of user id, so same user always same result)
action: AssignVariationAction(variation_id) -> but then we can only assign one variation.
So we need multiple rules for the experiment? We can split the experiment condition into multiple rules? Not ideal.
Alternatively, we can have:
Action types:
- EnableAction
- DisableAction
- AssignVariationAction(variation_id)
And then for an experiment with multiple variations, we create multiple rules with the same condition (e.g., 50% of users) but different variation_id? But then we need to split the condition.
Example:
Rule1: condition: PercentageCondition(25) -> assign variation A
Rule2: condition: PercentageCondition(25) -> assign variation B
Rule3: condition: PercentageCondition(50) -> assign variation C
But note: the conditions are evaluated in order, so the first 25% of users (by hash) get A, next 25% get B, and the rest 50% get C.
This works if we order the rules appropriately and the conditions are designed to be disjoint and cover 100% of the users in the experiment.
So we can model an experiment as a set of rules that together cover the experiment allocation.
Then, we don't need a separate Experiment entity.
But then how do we define the experiment? We can have:
Experiment:
flag_id
rules: list of Rule (but these are the same as the flag's rules? then we are mixing)
Alternatively, we can have:
FeatureFlag:
id
name
is_active: boolean
rules: list of Rule
And then we define an experiment by creating a set of rules for that flag that allocate variations by percentage.
But then we lose the ability to have a single experiment configuration (like a name, start/end dates, etc.)
Given the complexity, let's simplify:
We'll have two types of flags:
1. Boolean flags: have rules that return true/false.
2. Multivariate flags: have rules that return a variation id, and the flag has a mapping from variation id to value.
And we'll have:
FeatureFlag:
id
name
type: "boolean" or "multivariate"
is_active: boolean
rules: list of Rule
variations: list of Variation (only for multivariate)
Rule:
condition: Condition
value: for boolean -> boolean; for multivariate -> variation_id
Then, for an experiment, we set up multiple rules with PercentageCondition that together cover the desired allocation.
Example for 50% control, 50% treatment:
Rule1: condition: PercentageCondition(50) -> value: "control"
Rule2: condition: PercentageCondition(50) -> value: "treatment"
But note: the second condition will match the remaining 50%? Actually, if we use a deterministic hash, then:
We can define:
PercentageCondition(percentage): matches a user if (hash(user_id) mod 100) < percentage.
Then:
Rule1: PercentageCondition(50) -> matches if hash < 50 -> assign control.
Rule2: PercentageCondition(100) -> matches if hash < 100 -> but then we want the other 50%? Actually, we want:
We want 50% control, 50% treatment.
Rule1: PercentageCondition(50) -> control.
Rule2: PercentageCondition(100) -> treatment? But then Rule2 matches 100% of users, but Rule1 already matched 50%? We need to make sure the conditions are evaluated in order and the first match wins.
So:
Rule1: PercentageCondition(50) -> control.
Rule2: PercentageCondition(100) -> treatment.
Then, for a user with hash=30: Rule1 matches (30<50) -> control.
For hash=70: Rule1 doesn't match (70>=50), Rule2 matches (70<100) -> treatment.
This works.
So we can have:
Rule1: condition: PercentageCondition(50) -> variation_id: "control"
Rule2: condition: PercentageCondition(100) -> variation_id: "treatment"
But note: if we have more than two variations, we can chain:
Rule1: PercentageCondition(25) -> A
Rule2: PercentageCondition(50) -> B
Rule3: PercentageCondition(100) -> C
Then:
hash<25 -> A
25<=hash<50 -> B
50<=hash<100 -> C
This works.
So we don't need a separate experiment configuration. The experiment is defined by the set of rules.
However, we might want to have an experiment object for tracking (start date, end date, goal metric, etc.). We can have:
Experiment:
id
flag_id
name
start_date
end_date
status: "draft", "running", "completed"
# We can also store the expected allocation? But we can compute from rules.
But then we have to keep the rules and the experiment in sync.
Given the scope, let's not overcomplicate. We'll store the experiment metadata in the flag? Or separately?
Since the requirement says "experiment hooks", we might want to have a way to register an experiment and then have the flag automatically generate the rules? Or we can have:
We create an experiment, and then the experiment creates the rules for the flag.
But for simplicity, let's assume that the experiment is defined by a set of rules and we track experiment metadata in a separate table.
However, for the purpose of this code, we'll focus on the flag evaluation and assume that the rules are set up appropriately for experiments.
"""
Feature Flag System Architecture
Comprehensive solution with targeting, experiments, kill switches, cleanup, and audit
"""
import hashlib
import json
import uuid
from datetime import datetime, timedelta
from enum import Enum
from typing import Any, Dict, List, Optional, Set, Tuple
from abc import ABC, abstractmethod
from dataclasses import dataclass, field, asdict
from collections import defaultdict
# ==================== Core Types ====================
class FlagType(Enum):
BOOLEAN = "boolean"
MULTIVARIATE = "multivariate"
EXPERIMENT = "experiment"
class EvaluationResult(Enum):
ENABLED = "enabled"
DISABLED = "disabled"
VARIATION = "variation"
@dataclass
class Variation:
"""Represents a variation in a multivariate flag or experiment"""
id: str
value: Any
weight: float = 1.0 # For percentage allocation
meta: Dict[str, Any] = field(default_factory=dict)
@dataclass
class Rule:
"""Targeting rule with conditions and actions"""
id: str = field(default_factory=lambda: str(uuid.uuid4()))
name: Optional[str] = None
conditions: List[Dict[str, Any]] = field(default_factory=list) # List of condition objects
action: str = "enable" # "enable", "disable", "assign_variation"
variation_id: Optional[str] = None # Required if action is "assign_variation"
priority: int = 0 # Higher priority evaluated first
percentage: Optional[float] = None # For percentage-based rules (0-100)
description: Optional[str] = None
created_at: datetime = field(default_factory=datetime.utcnow)
expires_at: Optional[datetime] = None
@dataclass
class FeatureFlag:
"""Main feature flag entity"""
key: str
name: str
description: str = ""
flag_type: FlagType = FlagType.BOOLEAN
is_active: bool = True # Kill switch
rules: List[Rule] = field(default_factory=list)
variations: List[Variation] = field(default_factory=list)
# Metadata for cleanup and audit
created_by: str = ""
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
last_evaluated_at: Optional[datetime] = None
evaluation_count: int = 0
# Cleanup policy
cleanup_policy: Dict[str, Any] = field(default_factory=lambda: {
"max_age_days": 365,
"max_unused_days": 90,
"auto_delete": False
})
# Experiment metadata
experiment_id: Optional[str] = None
experiment_hooks: List[str] = field(default_factory=list) # Metrics to track
def to_dict(self) -> Dict:
"""Serialize for storage"""
return {
"key": self.key,
"name": self.name,
"description": self.description,
"flag_type": self.flag_type.value,
"is_active": self.is_active,
"rules": [asdict(r) for r in self.rules],
"variations": [asdict(v) for v in self.variations],
"created_by": self.created_by,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
"last_evaluated_at": self.last_evaluated_at.isoformat() if self.last_evaluated_at else None,
"evaluation_count": self.evaluation_count,
"cleanup_policy": self.cleanup_policy,
"experiment_id": self.experiment_id,
"experiment_hooks": self.experiment_hooks
}
# ==================== Condition Evaluators ====================
class ConditionEvaluator(ABC):
"""Abstract base for condition evaluators"""
@abstractmethod
def evaluate(self, condition: Dict, user_context: Dict) -> bool:
pass
class UserAttributeEvaluator(ConditionEvaluator):
"""Evaluates user attribute conditions"""
def evaluate(self, condition: Dict, user_context: Dict) -> bool:
attr = condition.get("attribute")
op = condition.get("operator", "eq")
expected = condition.get("value")
actual = user_context.get(attr)
operators = {
"eq": lambda a, b: a == b,
"neq": lambda a, b: a != b,
"contains": lambda a, b: b in a if isinstance(a, (list, str)) else False,
"in": lambda a, b: a in b if isinstance(b, list) else False,
"gt": lambda a, b: a > b if a is not None else False,
"gte": lambda a, b: a >= b if a is not None else False,
"lt": lambda a, b: a < b if a is not None else False,
"lte": lambda a, b: a <= b if a is not None else False,
}
if op not in operators:
return False
return operators[op](actual, expected)
class PercentageEvaluator(ConditionEvaluator):
"""Evaluates percentage-based rollout conditions"""
def evaluate(self, condition: Dict, user_context: Dict) -> bool:
percentage = condition.get("percentage", 0)
seed = condition.get("seed", "")
# Use user ID or a consistent identifier for hash
user_id = user_context.get("user_id", "")
hash_input = f"{user_id}:{seed}"
hash_value = int(hashlib.sha256(hash_input.encode()).hexdigest()[:8], 16)
return (hash_value % 100) < percentage
class ConditionEvaluatorRegistry:
"""Registry of condition evaluators"""
def __init__(self):
self.evaluators = {
"user_attribute": UserAttributeEvaluator(),
"percentage": PercentageEvaluator(),
}
def evaluate(self, condition: Dict, user_context: Dict) -> bool:
condition_type = condition.get("type", "user_attribute")
evaluator = self.evaluators.get(condition_type)
if not evaluator:
return False
return evaluator.evaluate(condition, user_context)
# ==================== Feature Flag Service ====================
class FeatureFlagService:
"""Main service for feature flag operations"""
def __init__(self, storage_backend, audit_logger=None):
self.storage = storage_backend
self.audit_logger = audit_logger
self.evaluator_registry = ConditionEvaluatorRegistry()
self._flags_cache = {}
self._cache_ttl = 60 # seconds
def create_flag(self, flag_data: Dict, created_by: str) -> FeatureFlag:
"""Create a new feature flag"""
flag = FeatureFlag(
key=flag_data["key"],
name=flag_data["name"],
description=flag_data.get("description", ""),
flag_type=FlagType(flag_data.get("flag_type", "boolean")),
created_by=created_by,
rules=[Rule(**r) for r in flag_data.get("rules", [])],
variations=[Variation(**v) for v in flag_data.get("variations", [])],
cleanup_policy=flag_data.get("cleanup_policy", {}),
experiment_id=flag_data.get("experiment_id"),
experiment_hooks=flag_data.get("experiment_hooks", [])
)
self.storage.save_flag(flag)
self._log_audit(flag.key, "create", created_by, flag_data)
self._invalidate_cache(flag.key)
return flag
def update_flag(self, flag_key: str, updates: Dict, updated_by: str) -> Optional[FeatureFlag]:
"""Update an existing flag"""
flag = self.storage.get_flag(flag_key)
if not flag:
return None
old_state = flag.to_dict()
# Apply updates
for key, value in updates.items():
if key == "rules":
flag.rules = [Rule(**r) for r in value]
elif key == "variations":
flag.variations = [Variation(**v) for v in value]
elif hasattr(flag, key):
setattr(flag, key, value)
flag.updated_at = datetime.utcnow()
self.storage.save_flag(flag)
self._log_audit(flag.key, "update", updated_by, {
"old": old_state,
"new": updates
})
self._invalidate_cache(flag.key)
return flag
def toggle_kill_switch(self, flag_key: str, is_active: bool, toggled_by: str) -> bool:
"""Toggle the kill switch for a flag"""
flag = self.storage.get_flag(flag_key)
if not flag:
return False
old_state = flag.is_active
flag.is_active = is_active
flag.updated_at = datetime.utcnow()
self.storage.save_flag(flag)
self._log_audit(flag.key, "kill_switch", toggled_by, {
"old_value": old_state,
"new_value": is_active
})
self._invalidate_cache(flag.key)
return True
def evaluate_flag(self, flag_key: str, user_context: Dict,
default_value: Any = None) -> Tuple[EvaluationResult, Any]:
"""
Evaluate flag for a user
Returns: (result_type, value)
"""
flag = self._get_flag_cached(flag_key)
if not flag:
return EvaluationResult.DISABLED, default_value
# Update metrics
flag.evaluation_count += 1
flag.last_evaluated_at = datetime.utcnow()
self.storage.save_flag(flag, update_metrics_only=True)
# Check kill switch first
if not flag.is_active:
return self._get_disabled_result(flag, default_value)
# Sort rules by priority
sorted_rules = sorted(flag.rules, key=lambda r: r.priority, reverse=True)
# Evaluate rules in order
for rule in sorted_rules:
# Check expiration
if rule.expires_at and rule.expires_at < datetime.utcnow():
continue
# Evaluate all conditions in the rule
all_conditions_met = True
for condition in rule.conditions:
if not self.evaluator_registry.evaluate(condition, user_context):
all_conditions_met = False
break
if all_conditions_met:
return self._apply_rule_action(rule, flag, default_value)
# No rules matched
return self._get_default_result(flag, default_value)
def _apply_rule_action(self, rule: Rule, flag: FeatureFlag,
default_value: Any) -> Tuple[EvaluationResult, Any]:
"""Apply the action from a matched rule"""
if flag.flag_type == FlagType.BOOLEAN:
if rule.action == "enable":
return EvaluationResult.ENABLED, True
elif rule.action == "disable":
return EvaluationResult.DISABLED, False
elif flag.flag_type in [FlagType.MULTIVARIATE, FlagType.EXPERIMENT]:
if rule.action == "assign_variation" and rule.variation_id:
for variation in flag.variations:
if variation.id == rule.variation_id:
return EvaluationResult.VARIATION, variation.value
elif rule.action == "disable":
return EvaluationResult.DISABLED, None
return self._get_default_result(flag, default_value)
def _get_disabled_result(self, flag: FeatureFlag, default_value: Any) -> Tuple[EvaluationResult, Any]:
"""Result when flag is disabled via kill switch"""
if flag.flag_type == FlagType.BOOLEAN:
return EvaluationResult.DISABLED, False
return EvaluationResult.DISABLED, None
def _get_default_result(self, flag: FeatureFlag, default_value: Any) -> Tuple[EvaluationResult, Any]:
"""Default result when no rules match"""
if flag.flag_type == FlagType.BOOLEAN:
return EvaluationResult.DISABLED, False
return EvaluationResult.DISABLED, default_value
def get_experiment_allocation(self, flag_key: str, user_context: Dict) -> Optional[Variation]:
"""Get experiment variation for user (for experiment tracking)"""
result_type, value = self.evaluate_flag(flag_key, user_context)
if result_type == EvaluationResult.VARIATION:
flag = self._get_flag_cached(flag_key)
for variation in flag.variations:
if variation.value == value:
return variation
return None
def run_cleanup_policy(self) -> Dict[str, List[str]]:
"""Run cleanup policy on all flags"""
now = datetime.utcnow()
deleted_flags = defaultdict(list)
all_flags = self.storage.get_all_flags()
for flag in all_flags:
policy = flag.cleanup_policy
should_delete = False
# Check age-based cleanup
max_age_days = policy.get("max_age_days", 365)
if (now - flag.created_at).days > max_age_days:
should_delete = True
reason = "age_expired"
# Check unused-based cleanup
max_unused_days = policy.get("max_unused_days", 90)
if flag.last_evaluated_at and (now - flag.last_evaluated_at).days > max_unused_days:
should_delete = True
reason = "unused_expired"
if should_delete and policy.get("auto_delete", False):
self.storage.delete_flag(flag.key)
deleted_flags[reason].append(flag.key)
self._log_audit(flag.key, "cleanup", "system", {"reason": reason})
return dict(deleted_flags)
def _get_flag_cached(self, flag_key: str) -> Optional[FeatureFlag]:
"""Get flag with caching"""
# Simple in-memory cache (in production use Redis/Memcached)
if flag_key in self._flags_cache:
return self._flags_cache[flag_key]
flag = self.storage.get_flag(flag_key)
if flag:
self._flags_cache[flag_key] = flag
return flag
def _invalidate_cache(self, flag_key: str):
"""Invalidate cache entry"""
self._flags_cache.pop(flag_key, None)
def _log_audit(self, flag_key: str, action: str, user: str, details: Dict):
"""Log audit event"""
if self.audit_logger:
audit_entry = {
"flag_key": flag_key,
"action": action,
"user": user,
"timestamp": datetime.utcnow().isoformat(),
"details": details
}
self.audit_logger.log(audit_entry)
# ==================== Audit Logger ====================
class AuditLogger:
"""Handles audit logging with multiple backends"""
def __init__(self, backends: List['AuditBackend'] = None):
self.backends = backends or []
def log(self, entry: Dict[str, Any]):
"""Log to all configured backends"""
for backend in self.backends:
try:
backend.write(entry)
except Exception as e:
# Log error but don't fail main operation
print(f"Audit backend error: {e}")
class AuditBackend(ABC):
"""Abstract audit backend"""
@abstractmethod
def write(self, entry: Dict[str, Any]):
pass
class DatabaseAuditBackend(AuditBackend):
"""Store audit logs in database"""
def __init__(self, db_connection):
self.db = db_connection
def write(self, entry: Dict):
# Insert into audit_logs table
query = """
INSERT INTO audit_logs
(flag_key, action, user_id, timestamp, details)
VALUES (%s, %s, %s, %s, %s)
"""
self.db.execute(query, (
entry["flag_key"],
entry["action"],
entry["user"],
entry["timestamp"],
json.dumps(entry["details"])
))
class FileAuditBackend(AuditBackend):
"""Write audit logs to file"""
def __init__(self, filepath: str):
self.filepath = filepath
def write(self, entry: Dict):
with open(self.filepath, 'a') as f:
f.write(json.dumps(entry) + '\n')
# ==================== Storage Backend ====================
class StorageBackend(ABC):
"""Abstract storage backend"""
@abstractmethod
def save_flag(self, flag: FeatureFlag, update_metrics_only: bool = False):
pass
@abstractmethod
def get_flag(self, key: str) -> Optional[FeatureFlag]:
pass
@abstractmethod
def delete_flag(self, key: str):
pass
@abstractmethod
def get_all_flags(self) -> List[FeatureFlag]:
pass
class InMemoryStorage(StorageBackend):
"""In-memory storage for development"""
def __init__(self):
self.flags = {}
def save_flag(self, flag: FeatureFlag, update_metrics_only: bool = False):
if update_metrics_only and flag.key in self.flags:
existing = self.flags[flag.key]
existing.evaluation_count = flag.evaluation_count
existing.last_evaluated_at = flag.last_evaluated_at
else:
self.flags[flag.key] = flag
def get_flag(self, key: str) -> Optional[FeatureFlag]:
return self.flags.get(key)
def delete_flag(self, key: str):
self.flags.pop(key, None)
def get_all_flags(self) -> List[FeatureFlag]:
return list(self.flags.values())
class DatabaseStorage(StorageBackend):
"""Database storage backend"""
def __init__(self, db_connection):
self.db = db_connection
def save_flag(self, flag: FeatureFlag, update_metrics_only: bool = False):
if update_metrics_only:
query = """
UPDATE feature_flags
SET evaluation_count = %s, last_evaluated_at = %s, updated_at = %s
WHERE key = %s
"""
self.db.execute(query, (
flag.evaluation_count,
flag.last_evaluated_at.isoformat() if flag.last_evaluated_at else None,
flag.updated_at.isoformat(),
flag.key
))
else:
# Full update/insert
query = """
INSERT INTO feature_flags
(key, name, description, flag_type, is_active, rules, variations,
created_by, created_at, updated_at, cleanup_policy,
experiment_id, experiment_hooks)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (key) DO UPDATE SET
name = EXCLUDED.name,
description = EXCLUDED.description,
flag_type = EXCLUDED.flag_type,
is_active = EXCLUDED.is_active,
rules = EXCLUDED.rules,
variations = EXCLUDED.variations,
updated_at = EXCLUDED.updated_at,
cleanup_policy = EXCLUDED.cleanup_policy,
experiment_id = EXCLUDED.experiment_id,
experiment_hooks = EXCLUDED.experiment_hooks
"""
self.db.execute(query, (
flag.key, flag.name, flag.description, flag.flag_type.value,
flag.is_active, json.dumps([asdict(r) for r in flag.rules]),
json.dumps([asdict(v) for v in flag.variations]),
flag.created_by, flag.created_at.isoformat(), flag.updated_at.isoformat(),
json.dumps(flag.cleanup_policy), flag.experiment_id,
json.dumps(flag.experiment_hooks)
))
def get_flag(self, key: str) -> Optional[FeatureFlag]:
query = "SELECT * FROM feature_flags WHERE key = %s"
result = self.db.execute(query, (key,)).fetchone()
if result:
return self._row_to_flag(result)
return None
def delete_flag(self, key: str):
self.db.execute("DELETE FROM feature_flags WHERE key = %s", (key,))
def get_all_flags(self) -> List[FeatureFlag]:
query = "SELECT * FROM feature_flags"
results = self.db.execute(query).fetchall()
return [self._row_to_flag(row) for row in results]
def _row_to_flag(self, row) -> FeatureFlag:
"""Convert database row to FeatureFlag object"""
return FeatureFlag(
key=row["key"],
name=row["name"],
description=row.get("description", ""),
flag_type=FlagType(row["flag_type"]),
is_active=row["is_active"],
rules=[Rule(**r) for r in json.loads(row["rules"])],
variations=[Variation(**v) for v in json.loads(row["variations"])],
created_by=row["created_by"],
created_at=datetime.fromisoformat(row["created_at"]),
updated_at=datetime.fromisoformat(row["updated_at"]),
last_evaluated_at=datetime.fromisoformat(row["last_evaluated_at"]) if row.get("last_evaluated_at") else None,
evaluation_count=row.get("evaluation_count", 0),
cleanup_policy=json.loads(row["cleanup_policy"]),
experiment_id=row.get("experiment_id"),
experiment_hooks=json.loads(row.get("experiment_hooks", "[]"))
)
# ==================== Experiment Tracking ====================
class ExperimentTracker:
"""Tracks experiment metrics and statistics"""
def __init__(self, metrics_backend):
self.metrics = metrics_backend
def track_exposure(self, flag_key: str, user_id: str, variation_id: str,
experiment_id: str, timestamp: datetime = None):
"""Track that a user was exposed to a variation"""
timestamp = timestamp or datetime.utcnow()
self.metrics.record_exposure(experiment_id, flag_key, user_id, variation_id, timestamp)
def track_conversion(self, experiment_id: str, user_id: str,
metric_name: str, value: float = 1.0,
timestamp: datetime = None):
"""Track a conversion metric for an experiment"""
timestamp = timestamp or datetime.utcnow()
self.metrics.record_conversion(experiment_id, user_id, metric_name, value, timestamp)
def get_experiment_stats(self, experiment_id: str) -> Dict[str, Any]:
"""Get statistics for an experiment"""
return self.metrics.get_experiment_stats(experiment_id)
# ==================== Usage Example ====================
def example_usage():
"""Demonstrate the feature flag system"""
# Initialize storage (use InMemoryStorage for dev, DatabaseStorage for prod)
storage = InMemoryStorage()
# Initialize audit logger
audit_logger = AuditLogger([
FileAuditBackend("audit.log"),
# DatabaseAuditBackend(db_connection)
])
# Initialize service
service = FeatureFlagService(storage, audit_logger)
# Create a boolean flag with targeting
boolean_flag = service.create_flag({
"key": "new_checkout_flow",
"name": "New Checkout Flow",
"description": "Enable new checkout experience",
"flag_type": "boolean",
"rules": [
{
"id": "rule1",
"name": "Beta users",
"conditions": [
{"type": "user_attribute", "attribute": "user_type", "operator": "eq", "value": "beta"}
],
"action": "enable",
"priority": 10
},
{
"id": "rule2",
"name": "10% rollout",
"conditions": [
{"type": "percentage", "percentage": 10, "seed": "new_checkout_flow"}
],
"action": "enable",
"priority": 5
}
],
"cleanup_policy": {
"max_age_days": 180,
"max_unused_days": 60,
"auto_delete": False
}
}, created_by="admin@example.com")
# Create an experiment flag
experiment_flag = service.create_flag({
"key": "button_color_experiment",
"name": "Button Color Experiment",
"description": "Test blue vs green CTA buttons",
"flag_type": "experiment",
"variations": [
{"id": "control", "value": {"color": "blue"}, "weight": 0.5},
{"id": "treatment", "value": {"color": "green"}, "weight": 0.5}
],
"rules": [
{
"id": "experiment_rule",
"conditions": [
{"type": "percentage", "percentage": 100, "seed": "button_color_exp"}
],
"action": "assign_variation",
"variation_id": None # Will be assigned dynamically based on hash
}
],
"experiment_id": "exp_001",
"experiment_hooks": ["checkout_completion", "revenue"],
"cleanup_policy": {
"max_age_days": 90,
"auto_delete": True
}
}, created_by="data-science@example.com")
# Evaluate flag for different users
user1 = {"user_id": "123", "user_type": "beta"}
result1, value1 = service.evaluate_flag("new_checkout_flow", user1)
print(f"User 1 (beta): {result1.value}, {value1}")
user2 = {"user_id": "456", "user_type": "regular"}
result2, value2 = service.evaluate_flag("new_checkout_flow", user2)
print(f"User 2 (regular): {result2.value}, {value2}")
# Get experiment variation
variation = service.get_experiment_allocation("button_color_experiment", user1)
print(f"User 1 experiment variation: {variation.id if variation else None}")
# Toggle kill switch
service.toggle_kill_switch("new_checkout_flow", False, "emergency@example.com")
result3, value3 = service.evaluate_flag("new_checkout_flow", user1)
print(f"After kill switch: {result3.value}, {value3}")
# Run cleanup
deleted = service.run_cleanup_policy()
print(f"Cleaned up flags: {deleted}")
# ==================== Admin Dashboard Utilities ====================
class FlagDashboard:
"""Utilities for admin dashboard"""
@staticmethod
def get_flag_health_report(service: FeatureFlagService) -> Dict[str, Any]:
"""Generate health report for all flags"""
all_flags = service.storage.get_all_flags()
report = {
"total_flags": len(all_flags),
"active_flags": sum(1 for f in all_flags if f.is_active),
"killed_flags": sum(1 for f in all_flags if not f.is_active),
"experiment_flags": sum(1 for f in all_flags if f.flag_type == FlagType.EXPERIMENT),
"flags_by_age": defaultdict(int),
"unused_flags": [],
"high_traffic_flags": []
}
now = datetime.utcnow()
for flag in all_flags:
# Age bucket
age_days = (now - flag.created_at).days
if age_days < 30:
report["flags_by_age"]["<30d"] += 1
elif age_days < 90:
report["flags_by_age"]["30-90d"] += 1
elif age_days < 365:
report["flags_by_age"]["90-365d"] += 1
else:
report["flags_by_age"][">365d"] += 1
# Unused flags (not evaluated in 30 days but active)
if (flag.is_active and flag.last_evaluated_at and
(now - flag.last_evaluated_at).days > 30):
report["unused_flags"].append({
"key": flag.key,
"days_unused": (now - flag.last_evaluated_at).days,
"evaluation_count": flag.evaluation_count
})
# High traffic flags (evaluated > 10000 times)
if flag.evaluation_count > 10000:
report["high_traffic_flags"].append({
"key": flag.key,
"evaluations": flag.evaluation_count
})
return report
@staticmethod
def get_experiment_summary(service: FeatureFlagService, experiment_id: str) -> Dict:
"""Get summary of experiment including conversion rates"""
# This would integrate with ExperimentTracker
return {
"experiment_id": experiment_id,
"status": "running", # Would come from experiment management system
"total_participants": 0,
"variations": [],
"conversion_rates": {}
}
# ==================== Main Execution ====================
if __name__ == "__main__":
# Run example
example_usage()
# Generate health report
storage = InMemoryStorage()
service = FeatureFlagService(storage)
report = FlagDashboard.get_flag_health_report(service)
print(f"Health Report: {json.dumps(report, indent=2)}")