Design a hierarchical configuration system layering defaults, environment overrides, and…
- User
Design a hierarchical configuration system layering defaults, environment overrides, and secrets.
Assistant
Design a hierarchical configuration system layering defaults, environment overrides, and secrets.
The user wants a design for a hierarchical configuration system. The system needs to handle three distinct layers:
The design needs to be "hierarchical," meaning there's a specific order of precedence (merging strategy).
Key Considerations & Steps:
Define the Layers and Precedence:
Data Structure:
Formats:
The "Design" Components:
config.Get("key").Implementation Strategy (Language Agnostic, but maybe pseudo-code or Python/Go style):
Detailed Layer Analysis:
config.yaml. overrides Layer 0.Handling Complex Keys (Flattening vs. Nesting):
DB_HOST). Config files are nested (database: host: ...).DATABASE_HOST -> database.host).Security Aspects:
Drafting the Solution Structure:
load method.Refining the Secrets Part:
password, and the loader knows to look that up in Vault if a specific placeholder is used (e.g., ${VAULT:secret/data/db:password}).Self-Correction/Review during drafting:
Final Output Structure:
Let's write this out.
sm://path/to/secret/key.This looks solid. I will produce the response based on this structure. Designing a robust configuration system requires moving beyond simple property files to a layered overlay model. This approach ensures that default behaviors are maintained, developers can override settings locally, and sensitive data is injected securely at runtime without hardcoding.
Below is a comprehensive design for a hierarchical configuration system.
The system is built on the principle of precedence. Configuration sources are stacked in a specific order. When a specific configuration key (e.g., db.password) is requested, the system checks the highest-priority source first. If the key exists there, it returns the value; if not, it falls back to the next layer down.
.yaml, .json, or .toml files checked into version control (e.g., config.prod.yaml).Instead of a loose bag of keys, the configuration should map to a strictly typed object/struct in code. This prevents runtime errors caused by typos.
Example Structure (YAML Representation):
server:
port: 8080 # Integer
read_timeout_ms: 5000 # Integer
database:
host: "localhost" # String
name: "app_db" # String
user: "admin" # String
password: null # String (To be injected by Secrets Layer)
features:
new_ui_enabled: false # Boolean
The configuration loader must execute a specific sequence at application startup:
PRODUCTION). Load config.production.yaml. Perform a Deep Merge (overwrite existing keys, keep missing keys).APP_SERVER_PORT).APP_SERVER_PORT -> server.port).${SECRET:db_password}) or known sensitive keys.null values exist for mandatory fields.Here is a simplified implementation demonstrating the hierarchical merging logic.
import os
import yaml
import json
class ConfigManager:
def __init__(self, schema_defaults):
self.config = schema_defaults
def load_file_config(self, file_path):
"""Layer 1: Load from YAML/JSON"""
if os.path.exists(file_path):
with open(file_path, 'r') as f:
data = yaml.safe_load(f)
self._deep_merge(self.config, data)
def load_env_overrides(self, prefix="APP"):
"""Layer 2: Load from Environment Variables"""
for env_key, value in os.environ.items():
if env_key.startswith(prefix):
# Convert APP_SERVER_PORT -> server.port
keys_path = env_key[len(prefix)+1:].lower().split('_')
self._set_nested(self.config, keys_path, value)
def resolve_secrets(self, secret_provider):
"""Layer 3: Fetch secrets (Mock logic)"""
# In a real app, you might look for keys ending in _PATH or specific tags
# Here we assume we know 'db_password' needs to be fetched
if self.config.get('database', {}).get('password') == "FETCH_ME":
# Simulate calling AWS Secrets Manager / Vault
real_password = secret_provider.get_secret("db_creds")
self.config['database']['password'] = real_password
# --- Utility Methods ---
def _deep_merge(self, base, override):
"""Recursively merges override dict into base dict."""
for key, value in override.items():
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
self._deep_merge(base[key], value)
else:
base[key] = value
def _set_nested(self, d, keys, value):
"""Sets a value in a nested dict using a list of keys."""
for key in keys[:-1]:
d = d.setdefault(key, {})
# Automatic type casting (simple version)
final_key = keys[-1]
if value.isdigit():
value = int(value)
elif value.lower() in ['true', 'false']:
value = value.lower() == 'true'
d[final_key] = value
# --- Usage ---
# Layer 0: Defaults
defaults = {
"server": {"port": 8000, "timeout": 30},
"database": {"host": "localhost", "password": None}
}
manager = ConfigManager(defaults)
# Layer 1: File overrides
# config.yaml contains: { server: { port: 8080 } }
manager.load_file_config("config.yaml")
# Layer 2: Env overrides
# Environment: APP_DATABASE_HOST=prod-db.aws.com
manager.load_env_overrides()
# Layer 3: Secrets
manager.resolve_secrets(MySecretProvider())
The handling of secrets requires stricter rules than standard configuration.
The configuration file does not contain the secret, but a path to the secret.
db_password: "arn:aws:secretsmanager:region:123:secret:db-pass"The orchestration platform mounts a secret volume at runtime (e.g., /var/secrets/db_password).
db_password is /var/secrets/db_password, the loader reads the file content.Starting server with config: { "db_password": "*****" }is_production = false).server.port is read as "8080", it must be converted to 8080 or the app should fail fast.