The user wants a runtime configuration system. This is a broad topic, but typically involves several key components:
Schemas: Defining what the configuration looks like (data types, structure, constraints).
Validation: Ensuring that the configuration data adheres to the schema before it's applied.
Rollouts: Strategies for deploying configuration changes to services (e.g., canary, blue/green, percentage-based).
Audits: Tracking who changed what, when, and why (versioning, history).
I need to create a "system." Since I can't build a full-blown distributed software platform in a single response, I should provide a conceptual architecture and a code implementation that demonstrates these principles. A Python-based library or a CLI tool seems like a good practical demonstration.
Core Components & Design:
Storage: Where does the config live? Usually a database (SQL/NoSQL) or a file system (Git, S3). For this example, I'll simulate a versioned key-value store or just use JSON files with versioning logic.
Schema: JSON Schema is the industry standard for this. I should use a library like jsonschema.
Validation: A layer that takes raw data and validates it against the schema.
Rollout Engine: Logic to determine which version of a config a specific user/request gets.
Simple approach: Global flag.
Advanced approach: Percentage-based or attribute-based (e.g., user ID ends in '5').
Audit Log: A mechanism to record changes.
Step-by-Step Implementation Plan:
Schema Definition: Use Pydantic or JSON Schema. Pydantic is very Pythonic and handles validation elegantly. Let's go with Pydantic for code clarity, or JSON Schema for interoperability. Let's stick to standard JSON Schema for the "system" feel, and use a Python validator.
Config Manager: A class that handles loading, saving, and versioning.
Rollout Logic: A specific module to handle "Targeting".
Audit Trail: A simple logging mechanism or a list of events stored in a file/db.
Refining the Request:
The user asked for runtime configuration. This implies the application reads it while running, without necessarily restarting.
Proposed Architecture (Python Implementation):
ConfigSchema: The definition of the config structure.
ConfigStore: The backend storage (simulated in-memory with history).
RolloutManager: Handles rules like "10% traffic".
AuditLogger: Records changes.
Code Structure:
models.py: Pydantic models for Schema and Audit entries.
store.py: The storage logic.
rollout.py: The rollout logic.
system.py: The main controller.
Let's draft the code mentally.
Schema: Use pydantic. It's powerful.
Validation: Pydantic does this automatically on instantiation.
Rollout: I need a way to define rules. E.g., {"feature_x": {"enabled": True, "rollout_pct": 20}}.
Audit: A simple list of dictionaries: {timestamp, user, action, prev_value, new_value}.
Self-Correction/Refinement:
A full rollout system often involves context. Is this request for User A or User B? The rollout logic needs to accept a context (e.g., user_id) to decide if the flag is on.
Detailed Implementation Steps:
Schema: Define a base configuration schema using Pydantic.
Storage: Create a class that holds the config state. It needs to support get_config(context).
Validation: Ensure set_config validates against the schema.
Rollouts: Implement "Canary" logic. If rollout_percentage is 50, only half of contexts get the new value.
Audit: Decorator or wrapper around set_config to log changes.
Let's create a specific example scenario: A web service configuration.
Features:
max_connections (int)
maintenance_mode (bool)
new_feature_enabled (bool with rollout %)
The Code:
I will write a Python script that simulates this system. It will include:
Schema Definition: Using Pydantic for strong typing.
Validation Logic: Automatic via Pydantic.
Rollout Strategy: A class that hashes context IDs to determine if a feature is active.
Audit System: A centralized log of changes with diffs.
I should also explain the concepts clearly before diving into code.
Concept Breakdown:
Schema: The contract.
Validation: The gatekeeper.
Rollout: The delivery strategy.
Audit: The historian.
Drafting the Code Logic:
python
import hashlib
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, ValidationError
# 1. SCHEMA
class AppConfig(BaseModel):
dark_mode: bool = False
api_timeout: int = 30
feature_x_enabled: bool = False
feature_x_rollout_pct: int = 0 # 0 to 100
# 2. AUDIT
class AuditEntry(BaseModel):
timestamp: datetime
user: str
changes: dict
audit_log: List[AuditEntry] = []
# 3. ROLLOUT
def is_feature_active(context_id: str, pct: int) -> bool:
# Consistent hashing to ensure same user gets same result
val = int(hashlib.md5(context_id.encode()).hexdigest(), 16)
return (val % 100) < pct
# 4. SYSTEM
class ConfigSystem:
def __init__(self):
self._config = AppConfig()
self._history = []
def get(self, context_id: str = None):
# Deep copy to avoid mutation
cfg_copy = self._config.model_copy()
# Apply rollout logic
if not is_feature_active(context_id, cfg_copy.feature_x_rollout_pct):
cfg_copy.feature_x_enabled = False
return cfg_copy
def set(self, new_data: dict, user: str):
# Validation
try:
validated_config = AppConfig(**new_data)
except ValidationError as e:
raise ValueError(f"Validation Failed: {e}")
# Audit
old_val = self._config.model_dump()
new_val = validated_config.model_dump()
# Record diff
# ...
self._config = validated_config
This looks solid. I will expand on this to make it a complete, runnable example with explanations. I'll structure the response as a design document followed by the implementation.
Key considerations to highlight:
Atomic Updates: Ensuring reads don't see partial writes (Python's GIL handles this for in-memory, but in real systems, this requires locks/transactions).
Consistent Hashing: For rollouts, you don't want a user to see a feature flickering on and off. Using a hash of their user ID is standard practice.
Let's polish the Audit part. It should ideally show what changed (diff).
I'll use a simple dict comparison for the diff.
Final Structure:
Overview: Explain the 4 pillars.
Python Implementation: A complete, single-file script demonstrating the system.
Uses pydantic for Schema/Validation (standard best practice in Python).
Implements a percentage-based rollout.
Maintains an immutable audit log.
Usage Example: A script showing:
Admin updates config (success).
Admin updates config (fail validation).
User A (in rollout) sees feature.
User B (outside rollout) doesn't see feature.
Checking audit logs.
This covers all requirements: schemas, validation, rollouts, and audits.
One small detail: The "Rollout" usually applies to specific flags, not the whole config. I will separate the "Global Config" from "Feature Flags" in the schema to make it more realistic, or keep it simple and just treat specific fields as rollout-controlled. I'll stick to the latter for simplicity but mention the separation.
Actually, a cleaner way for rollout is having a specific FeatureFlags section in the config.
Schema:
General Settings
Feature Flags (map of flag_name -> {enabled, rollout_pct})
This allows the ConfigSystem to iterate over flags and apply logic.
Let's refine the Rollout logic. The system should check a specific context (e.g., a user object or ID) against the rollout percentage.
Okay, plan is set. I will write the response now.
This design outlines a robust Runtime Configuration System suitable for production environments. It uses Python with Pydantic for strong typing and validation, simulates a database with an in-memory store, and implements consistent hashing for rollout stability.
System Architecture
Schema & Validation: Uses pydantic to enforce types (e.g., timeouts must be integers) and custom rules (e.g., percentage must be 0-100).
Audit Trail: An immutable log recording every change (Who, What, When, Old Value vs. New Value).
Rollout Engine: Evaluates configuration context (e.g., User ID) against rules (e.g., Percentage, Whitelist) to determine which configuration variant to serve.
Config Manager: The facade that coordinates validation, storage, and audit logging.
Implementation
You will need pydantic installed (pip install pydantic).
python
Key Features Explained
1. Schema (Pydantic)
We define AppConfig and FeatureFlag. This ensures that rate_limit cannot be set to "hello" and rollout_percentage cannot be set to 110.
Why: Prevents "configuration drift" where invalid values crash the application runtime.
2. Validation
There are two layers of validation:
Structural: Field(ge=0, le=100) ensures the rollout is within bounds.
Logical: In load_config, we wrap the instantiation in a try/except block. If validation fails, the state is not updated, preventing the system from entering a broken state.
3. Rollouts (Consistent Hashing)
In RolloutEvaluator, we do not use random.randint.
Problem: If you use random logic, refreshing the page might toggle the feature on and off for the same user.
Solution: hash(flag_key + user_id) % 100. This deterministically maps a user to a number between 0 and 99. If rollout_percentage is 20, anyone mapping to 0-19 gets the feature. This mapping is permanent for that user.
4. Audits
Every change calls log_change.
This creates a "black box" recorder. In a real system, this would write to a database like PostgreSQL or an append-only log system (e.g., Kafka/S3).
It captures the old_value and new_value, which is critical for debugging "who broke the production API."
import hashlib
import json
from datetime import datetime
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, field_validator, ValidationError
# ==========================================
# 1. Schema & Validation Layer
# ==========================================
class FeatureFlag(BaseModel):
key: str
enabled: bool = False
rollout_percentage: int = Field(default=0, ge=0, le=100)
whitelist_user_ids: List[str] = []
@field_validator('whitelist_user_ids')
@classmethod
def check_unique_ids(cls, v):
if len(v) != len(set(v)):
raise ValueError("Whitelist IDs must be unique")
return v
class AppConfig(BaseModel):
version: str
feature_flags: Dict[str, FeatureFlag]
rate_limit: int = Field(default=100, description="Requests per minute")
# ==========================================
# 2. Audit System
# ==========================================
class AuditEntry(BaseModel):
timestamp: datetime
user: str
action: str # e.g., "UPDATE_FLAG", "ROLLBACK"
key_path: str
old_value: Optional[Any] = None
new_value: Optional[Any] = None
reason: Optional[str] = None
class AuditLog:
def __init__(self):
self._logs: List[AuditEntry] = []
def log_change(self, user: str, key_path: str, old_val: Any, new_val: Any, reason: str = None):
entry = AuditEntry(
timestamp=datetime.utcnow(),
user=user,
action="UPDATE",
key_path=key_path,
old_value=old_val,
new_value=new_val,
reason=reason
)
self._logs.append(entry)
print(f"[AUDIT] {entry.timestamp.isoformat()} | User: {user} | Changed '{key_path}'")
def get_history(self) -> List[Dict]:
return [log.model_dump() for log in self._logs]
# ==========================================
# 3. Rollout Engine
# ==========================================
class RolloutEvaluator:
@staticmethod
def is_enabled(flag: FeatureFlag, user_id: str) -> bool:
"""
Determines if a feature is enabled for a specific user based on:
1. Global Kill Switch (enabled=False)
2. Whitelist (Bypass percentage)
3. Percentage Rollout (Consistent Hashing)
"""
if not flag.enabled:
return False
# 1. Whitelist Check
if user_id in flag.whitelist_user_ids:
return True
# 2. Percentage Rollout (Consistent Hashing)
# We hash the combination of the flag key and user ID to ensure
# the same user always falls into the same bucket for this flag.
if flag.rollout_percentage == 100:
return True
if flag.rollout_percentage == 0:
return False
hash_input = f"{flag.key}:{user_id}"
# MD5 hexdigest -> integer
hash_val = int(hashlib.md5(hash_input.encode()).hexdigest(), 16)
# Normalize to 0-99
bucket = hash_val % 100
return bucket < flag.rollout_percentage
# ==========================================
# 4. Configuration Manager
# ==========================================
class ConfigManager:
def __init__(self):
self._config: Optional[AppConfig] = None
self.audit_log = AuditLog()
self.evaluator = RolloutEvaluator()
def load_config(self, config_dict: Dict, user: str = "system"):
"""Initial load or full replacement of config."""
try:
new_config = AppConfig(**config_dict)
old_config_json = self._config.model_dump_json() if self._config else None
self._config = new_config
# Audit the initialization
self.audit_log.log_change(
user=user,
key_path="root",
old_val=json.loads(old_config_json) if old_config_json else None,
new_val=config_dict,
reason="Initial Load or Full Update"
)
print("[SYSTEM] Configuration loaded successfully.")
except ValidationError as e:
print(f"[ERROR] Schema Validation Failed: {e}")
raise ValueError(f"Invalid Configuration Schema: {e}")
def get_raw_config(self) -> AppConfig:
"""Returns the current config object."""
if not self._config:
raise RuntimeError("Configuration not loaded")
return self._config
def evaluate_flag(self, flag_key: str, user_id: str) -> bool:
"""
Runtime evaluation: Returns True/False for a specific user context.
"""
config = self.get_raw_config()
if flag_key not in config.feature_flags:
return False # Default safe behavior
return self.evaluator.is_enabled(config.feature_flags[flag_key], user_id)
def update_flag_rollout(self, flag_key: str, new_percentage: int, actor: str):
"""
Partial update with strict validation and auditing.
"""
config = self.get_raw_config()
if flag_key not in config.feature_flags:
raise KeyError(f"Flag {flag_key} not found")
# Capture old state
old_flag = config.feature_flags[flag_key].model_copy()
# Update logic (Pydantic will validate the 0-100 constraint)
try:
config.feature_flags[flag_key].rollout_percentage = new_percentage
except ValidationError as e:
print(f"Validation Error: {e}")
return
# Record Audit
self.audit_log.log_change(
user=actor,
key_path=f"feature_flags.{flag_key}.rollout_percentage",
old_val=old_flag.rollout_percentage,
new_val=new_percentage,
reason="Gradual Rollout Increase"
)
# ==========================================
# 5. Usage Demonstration
# ==========================================
if __name__ == "__main__":
manager = ConfigManager()
# 1. Define Initial Schema Data
initial_config = {
"version": "1.0.0",
"feature_flags": {
"new_dashboard": {
"key": "new_dashboard",
"enabled": True,
"rollout_percentage": 0,
"whitelist_user_ids": ["admin_01"]
},
"dark_mode": {
"key": "dark_mode",
"enabled": True,
"rollout_percentage": 50,
"whitelist_user_ids": []
}
}
}
print("--- Loading Config ---")
manager.load_config(initial_config, user="admin_01")
# 2. Evaluate Flags (Runtime)
print("\n--- Evaluating Users ---")
user_admin = "admin_01"
user_test = "user_123" # Should fall in bucket 0-99 based on hash
# Admin is whitelisted, should be True
print(f"User '{user_admin}' sees 'new_dashboard': {manager.evaluate_flag('new_dashboard', user_admin)}")
# Regular user, rollout is 0%, should be False
print(f"User '{user_test}' sees 'new_dashboard': {manager.evaluate_flag('new_dashboard', user_test)}")
# Dark mode is 50%, check consistency
res1 = manager.evaluate_flag('dark_mode', user_test)
res2 = manager.evaluate_flag('dark_mode', user_test)
print(f"User '{user_test}' sees 'dark_mode': {res1} (Consistent? {res1 == res2})")
# 3. Update Rollout (Deployment)
print("\n--- Updating Rollout to 10% ---")
try:
manager.update_flag_rollout("new_dashboard", 10, actor="devops_bot")
except ValueError as e:
print(e)
# 4. Validation Failure Example
print("\n--- Attempting Invalid Config ---")
try:
manager.update_flag_rollout("new_dashboard", 150, actor="devops_bot")
except Exception as e:
print(f"Blocked update: {e}")
# 5. View Audit Trail
print("\n--- Audit Trail ---")
for entry in manager.audit_log.get_history():
print(f"- [{entry['timestamp']}] {entry['user']} changed {entry['key_path']} from {entry['old_value']} to {entry['new_value']}")