Back
+25 XP
Concept

Dynamic Configuration Reloading via SIGHUP & Inotify Watchers

Killing high-throughput services just to toggle a feature flag or rotate an API key terminates thousands of active client connections. POSIX daemons register signal handlers for `signal.SIGHUP` (Signal Hang Up) to reload configurations atomically in-place with zero downtime 🔄⚡🛡️.

python
import signal

class EngineConfig:
    def __init__(self, initial):
        self.state = initial
        signal.signal(signal.SIGHUP, self.on_sighup)

    def on_sighup(self, signum, frame):
        # Atomic swap of active configuration dictionary
        self.state = {"max_conns": 5000, "debug": False}
        print("Configuration reloaded via SIGHUP 🚀")

conf = EngineConfig({"max_conns": 1000, "debug": True})
print("Active Config:", conf.state)

# 96. Dynamic Configuration Reloading via SIGHUP & Inotify Watchers Restarting a distributed cluster because someone tweaked a rate-limit threshold or rotated an API key is operational suicide. Cold boots flush warm caches, trigger thundering herds on databases, and terminate in-flight HTTP connections 🛑. ```python # The Unix SIGHUP Tradition: # Historically sent when a serial terminal was hung up. # Modern convention: Daemon processes intercept SIGHUP to trigger safe in-memory reload: # $ kill -HUP <pid> ``` ### Hot-Reload Engineering Invariants 1. **Atomic Reference Swapping**: Never mutate individual keys in a shared configuration dictionary across multiple threads. Read the entire new config from disk/network, validate its schema, and atomically rebind the class attribute pointer: `self.config = validated_new_dict` 🛡️. 2. **Schema Validation Before Swap**: If a developer fat-fingers an invalid YAML or JSON syntax during an update, catch the parse error, log a critical warning, and keep running on the previous valid configuration without crashing. 3. **Signal Handlers Must Be Fast**: Python signal handlers run on the main interpreter thread. Do not run heavy synchronous blocking I/O inside the signal callback; set an event flag or push a token into an internal queue for asynchronous processing ⚡. --- ### Interactive Pop-Quiz 🧠 #### Why is an atomic dictionary reference swap (self.config = new_dict) safer than mutating keys in-place (self.config.update(new_dict)) during live reloads? - [ ] Atomic reference swaps guarantee concurrent reader threads never observe half-updated, inconsistent configuration states 🛡️ - [ ] Dictionary update creates circular memory leaks in Python - [ ] POSIX signals automatically disable all CPU caches - [ ] In-place mutation forces Python to recompile all functions --- ### Practical Challenge 🎯 Implement `HotReloader` holding a `config` dictionary and `version: int`. Provide `apply_update(new_config: dict)` that swaps `self.config` atomically and increments `version`. Provide `handle_sighup(signum, frame)` invoking `apply_update({'status': 'live', 'workers': 8})`. Initialize with `{'status': 'bootstrap', 'workers': 1}`, trigger the signal handler, assert updated values, and print the new configuration. <details> <summary>Solution</summary> ```python import signal class HotReloader: def __init__(self, initial_config: dict): self.config = initial_config self.version = 1 def apply_update(self, new_config: dict): # Atomic pointer swap: concurrent readers see complete old or new dict self.config = new_config self.version += 1 def handle_sighup(self, signum, frame): self.apply_update({"status": "live", "workers": 8}) reloader = HotReloader({"status": "bootstrap", "workers": 1}) assert reloader.config["workers"] == 1 assert reloader.version == 1 reloader.handle_sighup(signal.SIGHUP, None) assert reloader.config["status"] == "live" assert reloader.config["workers"] == 8 assert reloader.version == 2 print(f"Reloaded Config (v{reloader.version}): {reloader.config}") ``` </details>

Checkpoint

Why is an atomic dictionary reference swap (`self.config = new_dict`) safer than mutating keys in-place (`self.config.update(new_dict)`) during live reloads? 🧠

Practice

Implement `HotReloader` holding a `config` dictionary and `version: int`. Provide `apply_update(new_config: dict)` that swaps `self.config` atomically and increments `version`. Provide `handle_sighup(signum, frame)` invoking `apply_update({'status': 'live', 'workers': 8})`. Initialize with `{'status': 'bootstrap', 'workers': 1}`, trigger the signal handler, assert updated values, and print the new configuration. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks