We are going to design a kill switch framework for risky features with drills.
The idea is to have a way to quickly disable a feature (kill switch) and also to have drills (practice runs) to test the kill switch.
Requirements:
- We need a way to register a feature with a kill switch.
- The kill switch should be configurable (e.g., via environment variable, config file, or feature flag service) and allow for immediate disable.
- We should have a way to simulate a kill switch trigger (drill) to test the system without actually disabling the feature for real users.
- We might want to have different levels of kill (e.g., hard kill vs soft kill, or gradual rollback).
Let's break it down:
- Kill Switch Registry: A central place to manage kill switches for features.
- Configuration: The kill switches can be set to ON or OFF (or more states). We'll use a simple boolean for now, but can extend.
- Drill Mode: A way to run a drill that simulates the kill switch being triggered, but without affecting the real state? Or maybe we want to test the actual kill switch in a controlled environment (like staging) without affecting production.
However, note: the requirement says "with drills", meaning we want to practice the kill switch procedure.
We can think of two modes:
- Real mode: the kill switch actually disables the feature.
- Drill mode: we simulate the kill switch, but the feature is not actually disabled. Instead, we log that we would have disabled it, or we run a mock.
But note: sometimes we want to test the actual kill switch in a non-production environment. So maybe:
We have a configuration that says:
- In production, we have a real kill switch (backed by config or feature flag service).
- In staging, we can run drills that use the same mechanism but in a safe way.
Alternatively, we can have:
A kill switch service that:
- Has a method to check if a feature is killed.
- The method can be overridden in test/drill mode to return a simulated state.
However, the requirement is to build a framework, so we want to make it easy for developers to use.
Let's design:
-
KillSwitchManager:
- register(feature_name, default_state=False, ...)
- is_killed(feature_name) -> bool
- kill(feature_name) # turn off
- revive(feature_name) # turn on
-
Configuration: The manager reads from a configuration source (like a file, environment, or remote config) to set the state.
-
Drill Support:
We can have a drill mode that when enabled, the is_killed method returns a simulated state (maybe from a drill configuration) without affecting the real configuration.
But note: the drill might be to test the entire flow, including the side effects of killing the feature (like cleaning up resources, showing alternative UI, etc.). So we might want the feature code to be aware of the drill and then run in a special mode.
Alternatively, we can have:
In drill mode, we set a flag that the kill switch is in drill mode. Then, when the feature checks is_killed, it returns the drill state (which could be the same as the real state or a simulated one). But the feature code might have side effects that we don't want to run in drill mode.
So maybe we need two things:
a) A way to simulate the kill switch state (so that the feature code runs as if killed, but without actually killing it for real users). This is for testing the code paths.
b) A way to practice the operational procedure of killing the feature (which might involve more than just setting a flag, like notifying teams, updating dashboards, etc.)
Since the requirement says "framework", let's focus on the code-level kill switch and drill.
Proposed:
We have a KillSwitchManager that is initialized with a configuration source.
We also have a DrillManager that can be turned on (maybe via environment variable) and then overrides the KillSwitchManager's state for certain features.
However, note: we don't want to accidentally leave drill mode on in production.
Alternatively, we can have:
KillSwitchManager has two modes: normal and drill.
In drill mode, it uses a separate configuration (maybe in-memory) for the drill state.
How to trigger drill? We can have an environment variable or a special endpoint (if it's a web service) to start a drill.
But note: the drill should be time-bound and safe.
Let's design the KillSwitchManager:
class KillSwitchManager:
def __init__(self, config_source, drill_mode=False, drill_config_source=None):
self.config_source = config_source
self.drill_mode = drill_mode
self.drill_config_source = drill_config_source or {}
self.registry = {} # feature_name -> metadata (like default_state, etc.)
def register(self, feature_name, default_state=False, **kwargs):
# register a feature, maybe with some metadata
self.registry[feature_name] = {'default': default_state, **kwargs}
def is_killed(self, feature_name):
# If in drill mode, check drill_config_source for the feature, else check config_source.
if self.drill_mode:
# drill_config_source could be a dict or another config source
# If the feature is in drill_config_source, use that, else use the real config?
# But in drill mode, we might want to simulate a kill for a feature even if it's not killed in reality?
# Let's say: in drill mode, we have a separate set of states for features (the drill states).
# We can have a drill config that says: for feature X, in drill we want to simulate it being killed.
# But note: the drill might be to test the kill switch for a feature that is not currently killed.
# So we want to be able to set any state in drill mode, independent of the real state.
# How about: in drill mode, we look up the feature in the drill_config_source (which could be a dict or another config source).
# If not found, then we fall back to the real state? Or we don't allow fallback and require explicit drill config for each feature we want to drill?
# Since drill is for testing, we probably want to test the kill switch for a specific feature. So we only want to drill features that are registered.
# Let's do: in drill mode, if the feature is in drill_config_source, then return the drill state (which is a boolean). If not, then return the real state?
# But then the drill might not be isolated? We might accidentally affect other features.
# Alternatively, in drill mode, we only look at the drill_config_source and if the feature is not there, we treat it as not killed (or as the default?).
# However, the drill is for a specific feature. So we might want to drill only that feature and leave others alone.
# Let's define: drill mode means we are simulating a kill for a set of features (the ones we are drilling). For other features, we use the real state.
# So:
# if feature_name in self.drill_config_source:
# return self.drill_config_source[feature_name]
# else:
# return self._get_real_state(feature_name)
pass
else:
return self._get_real_state(feature_name)
def _get_real_state(self, feature_name):
# get from config_source, if not found, use default from registry, if not registered, raise?
pass
But wait, we might want to have the drill affect the entire system? Maybe we want to drill the kill switch for a feature and have the entire system behave as if it's killed, but without actually turning it off for real users.
However, note: if we are in drill mode and we set a feature to killed, then the feature code will run the killed path. But if the feature is not registered, we might not want to kill it? Or we might want to kill it if the drill config says so, even if not registered? But then we don't have a default.
Let's change: we don't require registration for kill switches? We can have ad-hoc kill switches? But then we lose the metadata.
Alternatively, we can have:
The kill switch manager can check any feature, but if it's not registered, it returns False (or the default from config) and logs a warning.
But for drills, we might want to drill any feature, even if not registered? That could be dangerous because we might kill a feature that we don't have a recovery plan for.
So let's require registration for features that we want to have kill switches. Then, in drill mode, we only drill registered features? Or we allow drilling any feature but then we log an error if it's not registered?
I think for safety, we should only allow killing (and drilling) registered features.
Revised:
class KillSwitchManager:
def __init__(self, config_source, drill_mode=False, drill_config_source=None):
self.config_source = config_source
self.drill_mode = drill_mode
self.drill_config_source = drill_config_source or {}
self.registry = {} # feature_name -> metadata
def register(self, feature_name, default_state=False, **kwargs):
if feature_name in self.registry:
raise ValueError(f"Feature {feature_name} already registered")
self.registry[feature_name] = {'default': default_state, **kwargs}
def is_killed(self, feature_name):
if feature_name not in self.registry:
# We can log a warning and return False? Or raise?
# For safety, we don't kill unregistered features.
return False
if self.drill_mode:
# In drill mode, we use the drill_config_source if the feature is present, else use the real state.
if feature_name in self.drill_config_source:
return self.drill_config_source[feature_name]
else:
return self._get_real_state(feature_name)
else:
return self._get_real_state(feature_name)
def _get_real_state(self, feature_name):
# Try to get from config_source, then from registry default.
# config_source could be a dict, or an object with a get method.
# We assume config_source has a method get(feature_name, default=None)
state = self.config_source.get(feature_name)
if state is None:
state = self.registry[feature_name]['default']
return state
But note: the config_source might be a remote config that can change. We are not caching? We are reading every time? That might be slow and also we might get inconsistent states.
We might want to cache the state? But then if the config changes, we need to update. This is getting complex.
Alternatively, we can have the config_source be a callable that returns the current state for a feature.
Let's change:
config_source: a function that takes feature_name and returns state (or None if not set).
Similarly, drill_config_source: a function or a dict? We can make it consistent.
But for simplicity, let's assume config_source is an object with a get method.
Now, for drills:
We can have a separate drill config source. We can set the drill mode by setting an environment variable, and then the drill config source can be from a file or in-memory.
How to run a drill?
We set the environment variable DRILL_MODE=true and set DRILL_CONFIG (maybe a JSON file) that maps feature names to boolean.
Then, when the app starts, it reads the environment and sets up the KillSwitchManager accordingly.
But note: we might want to start a drill without restarting the app? So we need a way to change the drill mode and drill config at runtime.
We can have:
The KillSwitchManager can be updated at runtime? We can have:
set_drill_mode(drill_mode, drill_config_source=None)
But then we need to make sure the manager is a singleton and thread-safe.
Alternatively, we can have the KillSwitchManager be stateless and rely on the config_source and drill_config_source to be动态.
But then the config_source and drill_config_source must be thread-safe and updated appropriately.
Given the complexity, let's assume we are going to have a process that runs for a long time and we want to be able to change the kill switch state without restarting.
We can design:
The KillSwitchManager holds references to config_source and drill_config_source, which are objects that can be updated.
Example:
class ConfigSource:
def get(self, feature_name):
# read from a file, or from memory, or from a remote service.
pass
We can have a file-based config source that watches a file and reloads when changed.
But for simplicity in the example, we'll assume the config_source is a dictionary that can be updated.
However, note: we are building a framework, so we want to be flexible.
Let's define interfaces:
class ConfigSource(Protocol):
def get(self, feature_name: str) -> Optional[bool]:
...
Then we can have:
class DictConfigSource:
def __init__(self, initial_config=None):
self.config = initial_config or {}
def get(self, feature_name):
return self.config.get(feature_name)
def update(self, feature_name, value):
self.config[feature_name] = value
Similarly for drill config.
Then the KillSwitchManager:
class KillSwitchManager:
def __init__(self, config_source: ConfigSource, drill_mode: bool = False, drill_config_source: ConfigSource = None):
self.config_source = config_source
self.drill_mode = drill_mode
self.drill_config_source = drill_config_source or DictConfigSource({})
self.registry = {}
... as above ...
def set_drill_mode(self, drill_mode: bool, drill_config_source: ConfigSource = None):
self.drill_mode = drill_mode
if drill_config_source is not None:
self.drill_config_source = drill_config_source
Now, for the drill, we can have:
In production, we set drill_mode to False.
In staging, we can set up a drill by:
setting drill_mode to True and providing a drill_config_source that has the feature we want to drill set to True (killed).
Then, when we run the system in staging, the kill switch manager will return the drill state for the features in the drill config, and the real state for others.
This way, we can test the kill switch behavior for a feature without actually killing it in the real config.
But note: what if we want to drill a feature that is not killed in the real config? We set it to killed in the drill config, and then the feature code will run the killed path. That's what we want.
What if we want to drill a feature that is already killed in the real config? Then in drill mode, we would get the real state (killed) and that's fine.
However, note: the drill config might not have the feature, so we fall back to real state. That's okay.
But wait: what if we are in drill mode and we want to drill a feature that is not registered? We are not allowing that because we require registration.
So we must register the feature first.
Steps for a drill:
1. Register the feature (if not already) with a default state (say False).
2. Set up drill config for that feature to True (if we want to simulate a kill) or False (to simulate not killed).
3. Enable drill mode.
Then the feature code that uses:
if kill_switch_manager.is_killed("feature_x"):
# do alternative
else:
# normal
will behave according to the drill state.
But note: the drill is only for the code that checks the kill switch. What about other side effects? We might want to test the entire process of killing, including alerts, logs, etc.
We can have:
When a feature is killed (either by real kill switch or drill), we log an alert and maybe do some cleanup.
But in drill mode, we might not want to send real alerts? So we need to have a way to distinguish between a real kill and a drill kill.
We can change:
is_killed returns a tuple? (is_killed, is_drill) ?
Or we can have a separate method to check if we are in drill mode?
Alternatively, we can have:
class KillSwitchManager:
...
def is_drill(self):
return self.drill_mode
def is_killed(self, feature_name):
# ... as before ...
# but we don't know if the returned state is from drill or real?
# Actually, we do: if in drill mode and the feature is in drill_config_source, then it's a drill state. Otherwise, it's real.
# But the caller might not care. They just want to know if the feature is killed.
# However, for logging, we might want to know if it's a drill.
# We can have:
# state = ... as before ...
# if self.drill_mode and feature_name in self.drill_config_source:
# return state, True # drill
# else:
# return state, False # real
# But that changes the interface.
# Alternatively, we can have:
# get_kill_state(feature_name) -> KillState:
# which has .is_killed and .is_drill
# But that would break existing code that uses is_killed.
# Since we are building a framework, we can design the interface as we want.
# Let's change the interface to return a KillState object.
class KillState:
def __init__(self, is_killed, is_drill):
self.is_killed = is_killed
self.is_drill = is_drill
Then:
def get_kill_state(self, feature_name) -> KillState:
if self.drill_mode and feature_name in self.drill_config_source:
return KillState(self.drill_config_source.get(feature_name), True)
else:
return KillState(self._get_real_state(feature_name), False)
And then we can have:
def is_killed(self, feature_name):
return self.get_kill_state(feature_name).is_killed
But then we lose the drill information in the simple call.
Alternatively, we keep both:
def is_killed(self, feature_name, include_drill_info=False):
state = self.get_kill_state(feature_name)
if include_drill_info:
return state
else:
return state.is_killed
But that might be confusing.
Since the requirement is for a kill switch framework with drills, we want to be able to run drills and see the effect. So we might want to log when we are in a drill.
So let's change the interface to return a KillState. Then the user can check:
kill_state = manager.get_kill_state("feature_x")
if kill_state.is_killed:
if kill_state.is_drill:
log.info("Feature x is killed in drill mode")
else:
log.warning("Feature x is killed in production!")
But that puts the burden on the user to check the drill flag.
Alternatively, we can have the manager log automatically when a feature is killed, and in the log we can indicate if it's a drill.
We can have:
def get_kill_state(self, feature_name):
state = ... as before ...
if state.is_killed:
if state.is_drill:
log.info(f"Kill switch for {feature_name} is ON (drill)")
else:
log.warning(f"Kill switch for {feature_name} is ON (real)")
return state
But then we are logging every time we check? That might be too noisy.
We can log only when the state changes? But we don't track previous state.
Given the complexity, let's stick to the simple interface for now and let the user decide how to log.
We can provide a helper method that logs the state:
def log_kill_state(self, feature_name):
state = self.get_kill_state(feature_name)
if state.is_killed:
if state.is_drill:
log.info(f"Kill switch for {feature_name} is ON (drill)")
else:
log.warning(f"Kill switch for {feature_name} is ON (real)")
else:
log.debug(f"Kill switch for {feature_name} is OFF")
Then the user can call this method when they check the kill switch.
But note: the user might not want to log every time. So we can leave it to the user.
Given the time, let's stick to the simple is_killed that returns a boolean, and then we can have:
def is_drill(self):
return self.drill_mode
Then the user can log:
if kill_switch_manager.is_killed("feature_x"):
if kill_switch_manager.is_drill():
log.info("Drill: feature_x is killed")
else:
log.warning("Real: feature_x is killed")
But wait: what if the feature is killed in drill mode but the real state is also killed? Then we would log "Real" even though we are in drill mode? No, because in drill mode we return the drill state, but we don't know if the real state is also killed.
So the above logging would be:
if kill_switch_manager.is_killed("feature_x"):
if kill_switch_manager.drill_mode and "feature_x" in kill_switch_manager.drill_config_source:
log.info("Drill: feature_x is killed")
else:
log.warning("Real: feature_x is killed")
That's a bit messy.
Alternatively, we can have:
def get_kill_state(self, feature_name):
# returns (is_killed, is_drill) as a tuple
if feature_name not in self.registry:
return (False, False)
if self.drill_mode and feature_name in self.drill_config_source:
return (self.drill_config_source.get(feature_name), True)
else:
return (self._get_real_state(feature_name), False)
Then the user can do:
is_killed, is_drill = manager.get_kill_state("feature_x")
if is_killed:
if is_drill:
log.info("Drill: feature_x is killed")
else:
log.warning("Real: feature_x is killed")
This is clearer.
Let's change the interface to:
get_kill_state(feature_name) -> (bool, bool) # (is_killed, is_drill)
And then we can have:
is_killed(feature_name) -> bool # just the state, without drill info.
But then we have two methods. We can deprecate is_killed? Or keep both.
Since we are building a framework, we can provide both.
Let's do:
class KillSwitchManager:
...
def is_killed(self, feature_name):
state, _ = self.get_kill_state(feature_name)
return state
def get_kill_state(self, feature_name):
... returns (is_killed, is_drill)
Now, for the drill, we need a way to set the drill mode and drill config at runtime.
We can have:
enable_drill(drill_config_source=None)
disable_drill()
But note: the drill_config_source might be large and we don't want to set it every time.
Alternatively, we can set the drill mode and drill config at initialization and then change only the mode.
We can have:
set_drill_mode(drill_mode, drill_config_source=None)
If drill_config_source is provided, we update the drill_config_source.
Implementation:
class KillSwitchManager:
def __init__(self, config_source, drill_mode=False, drill_config_source=None):
self.config_source = config_source
self.drill_mode = drill_mode
self.drill_config_source = drill_config_source or DictConfigSource({})
self.registry = {}
def set_drill_mode(self, drill_mode, drill_config_source=None):
self.drill_mode = drill_mode
if drill_config_source is not None:
self.drill_config_source = drill_config_source
def get_kill_state(self, feature_name):
if feature_name not in self.registry:
return (False, False)
if self.drill_mode and feature_name in self.drill_config_source.get_all_features():
# We need a way to get all features in drill_config_source? Or we can just try to get and check if it's None?
# Let's change: drill_config_source.get(feature_name) returns None if not present.
drill_state = self.drill_config_source.get(feature_name)
if drill_state is not None:
return (drill_state, True)
# Either not in drill mode, or feature not in drill_config_source, or drill_config_source returns None for the feature.
real_state = self._get_real_state(feature_name)
return (real_state, False)
But wait: what if we are in drill mode and the feature is in the drill_config_source but set to the same as real? Then we return (state, True) and the user will think it's a drill? Yes, because we are in drill mode and we have a drill config for that feature.
That's okay because we are in drill mode and we have explicitly set the drill state for that feature.
However, note: if we are in drill mode and the drill_config_source doesn't have the feature, we return the real state with is_drill=False. That means for that feature, we are not drilling.
That's the intended behavior.
Now, how to update the drill_config_source at runtime? We can have the drill_config_source be an object that we can update.
Example:
drill_config = DictConfigSource({"feature_x": True})
manager = KillSwitchManager(real_config, drill_mode=False, drill_config_source=drill_config)
Then, to start a drill for feature_x:
manager.set_drill_mode(True, drill_config_source=drill_config) # but we already passed it, so we can just do:
manager.set_drill_mode(True)
And then if we want to change the drill state for feature_x:
drill_config.update("feature_x", False) # stop drilling feature_x
But note: the drill_config_source we passed might be shared. So we can update it.
Alternatively, we can have the manager hold a reference to the drill_config_source and we update that object.
So we don't need to set the drill_config_source again in set_drill_mode if we are just updating the state in the same config source.
We can have:
def set_drill_mode(self, drill_mode):
self.drill_mode = drill_mode
And then we update the drill_config_source separately.
But then we need to have a way to get the drill_config_source? We can have:
def get_drill_config_source(self):
return self.drill_config_source
But that might break encapsulation.
Alternatively, we can have:
The drill_config_source is set at init and then we don't change it, but we change its internal state.
So:
drill_config = DictConfigSource(...)
manager = KillSwitchManager(real_config, drill_mode=False, drill_config_source=drill_config)
Then, to change the drill state for a feature:
drill_config.update(feature_name, new_state)
And to turn on drill mode:
manager.set_drill_mode(True)
To turn off:
manager.set_drill_mode(False)
This seems clean.
Now, let's code accordingly.
We'll define:
class ConfigSource(ABC):
@abstractmethod
def get(self, feature_name: str) -> Optional[bool]:
pass
class DictConfigSource:
def __init__(self, config_dict=None):
self.config = config_dict or {}
def get(self, feature_name):
return self.config.get(feature_name)
def update(self, feature_name, value):
self.config[feature_name] = value
def set_all(self, new_config):
self.config = new_config
But note: we might have a config source that reads from a file and watches for changes. So we don't want to force a dict.
We'll keep ConfigSource as an abstract base class.
Now, the KillSwitchManager:
class KillSwitchManager:
def __init__(self, config_source: ConfigSource, drill_mode: bool = False, drill_config_source: ConfigSource = None):
self.config_source = config_source
self.drill_mode = drill_mode
self.drill_config_source = drill_config_source or DictConfigSource({})
self.registry = {} # feature_name -> metadata
def register(self, feature_name, default_state=False, **kwargs):
if feature_name in self.registry:
raise ValueError(f"Feature {feature_name} already registered")
self.registry[feature_name] = {'default': default_state, **kwargs}
def set_drill_mode(self, drill_mode: bool):
self.drill_mode = drill_mode
def get_drill_config_source(self):
return self.drill_config_source
def get_kill_state(self, feature_name):
if feature_name not in self.registry:
# For unregistered features, we return (False, False) but log a warning?
# Let's log a warning once per feature? We can use a set to track warned features.
# But for now, just return (False, False)
return (False, False)
if self.drill_mode:
drill_state = self.drill_config_source.get(feature_name)
if drill_state is not None:
return (drill_state, True)
real_state = self._get_real_state(feature_name)
return (real_state, False)
def _get_real_state(self, feature_name):
state = self.config_source.get(feature_name)
if state is None:
state = self.registry[feature_name]['default']
return state
Now, how do we use this?
# Create config sources
real_config = DictConfigSource({"feature_x": False}) # feature_x is not killed by default
drill_config = DictConfigSource({"feature_x": True}) # in drill, we want to simulate feature_x being killed
manager = KillSwitchManager(real_config, drill_mode=False, drill_config_source=drill_config)
manager.register("feature_x", default_state=False)
# Normal operation:
print(manager.is_killed("feature_x")) # False
# Start drill:
manager.set_drill_mode(True)
print(manager.is_killed("feature_x")) # True (from drill_config)
# Stop drill:
manager.set_drill_mode(False)
print(manager.is_killed("feature_x")) # False (from real_config)
But note: what if we want to drill a feature that is not in the drill_config? Then we fall back to real state.
Example:
drill_config = DictConfigSource({}) # empty
manager = KillSwitchManager(real_config, drill_mode=True, drill_config_source=drill_config)
manager.register("feature_x", default_state=False)
print(manager.is_killed("feature_x")) # False (from real_config, and not a drill because not in drill_config)
That's correct.
Now, what about the default state? We are using the registry default if the config_source doesn't have the feature.
But note: the real_config might not have the feature, then we use the default.
This is good.
However, what if we want to kill a feature that is not registered? We return (False, False). That's safe.
We might want to log a warning for unregistered features. We can do:
if feature_name not in self.registry:
logger.warning(f"Kill switch checked for unregistered feature: {feature_name}")
return (False, False)
But we don't want to log every time. We can use a set to track which unregistered features we have warned about.
Let's add:
self._warned_unregistered = set()
def get_kill_state(self, feature_name):
if feature_name not in self.registry:
if feature_name not in self._warned_unregistered:
logger.warning(f"Kill switch checked for unregistered feature: {feature_name}")
self._warned_unregistered.add(feature_name)
return (False, False)
Now, what about the drill? We might want to warn if we are in drill mode and the feature is not registered? But then we are already warning for unregistered.
That's okay.
Now, let's think about thread safety. We are updating the registry and the config sources. The config sources might be updated from multiple threads? We need to make sure the get method is thread-safe.
For DictConfigSource, we can use a lock. But for simplicity, we assume that the config sources are thread-safe or that we are in a single-threaded environment.
Given the complexity, we'll leave thread safety as an exercise.
Now, let's write the code accordingly.
We'll also provide a way to get the current drill mode and the current drill config.
But note: the drill config might be large, so we don't want to expose the whole thing? We can have:
def get_drill_config(self):
# return a copy of the drill config? Or we can return the drill_config_source?
# Since the drill_config_source is an object, we can return it and let the user call get on it?
# But then the user can modify it? We are already allowing update via drill_config_source.update.
# So we can just return the drill_config_source.
But then the user can do:
drill_config = manager.get_drill_config_source()
drill_config.update("feature_x", True)
That's okay.
Alternatively, we can have:
def set_drill_config_for_feature(self, feature_name, state):
self.drill_config_source.update(feature_name, state)
But then we are tied to a config source that has update. We can require that the drill_config_source has an update method? But our ConfigSource interface only has get.
We can change the ConfigSource to have set? But then the real config source might not be writable.
So we leave it: the user can pass a drill_config_source that is writable (like DictConfigSource) and then update it directly.
We can document that.
Now, let's code.
We'll also provide a global manager? Or let the user create their own? We can have a default manager that uses environment variables and a file for drill config.
But that might be too much.
We'll just provide the class and let the user decide.
Let's code the classes.
Note: We are using ABC for ConfigSource, but we don't have to. We can just define the interface.
We'll do:
from abc import ABC, abstractmethod
class ConfigSource(ABC):
@abstractmethod
def get(self, feature_name: str) -> Optional[bool]:
pass
class DictConfigSource(ConfigSource):
def __init__(self, config_dict=None):
self.config = config_dict or {}
def get(self, feature_name):
return self.config.get(feature_name)
def update(self, feature_name, value):
self.config[feature_name] = value
def set_all(self, new_config):
self.config = new_config
Then the KillSwitchManager as above.
But note: the real config source might be read-only. So we don't require update on ConfigSource.
For the drill config source, we are going to update it, so we require that it has an update method? But we are not going to call update from the manager, we are going to let the user call update on the drill_config_source.
So we don't need to change ConfigSource.
However, we are checking if a feature is in the drill_config_source by calling get and checking for None. That's okay.
Now, let's write the KillSwitchManager.
We'll also add a method to get the list of registered features? Maybe not necessary.
Let's code.
I'll design a comprehensive Kill Switch Framework for risky features with drill support. This framework provides safe feature management with emergency shutdown capabilities and regular resilience testing.
Kill Switch Framework Architecture
"""
Kill Switch Framework - Safe Feature Management with Drills
"""
import asyncio
import logging
from datetime import datetime, timedelta
from enum import Enum
from typing import Dict, List, Optional, Callable, Any
from dataclasses import dataclass, field
from contextlib import contextmanager
import threading
import json
from abc import ABC, abstractmethod
# ==================== Core Enums & Dataclasses ====================
class KillSwitchState(Enum):
"""States of a kill switch"""
ACTIVE = "active" # Feature is enabled
KILLED = "killed" # Feature is disabled by kill switch
DRILL = "drill" # Feature is disabled in drill mode
GRADUAL = "gradual" # Gradual rollout/rollback in progress
class KillSwitchSeverity(Enum):
"""Severity levels for kill switches"""
CRITICAL = "critical" # Immediate kill required
HIGH = "high" # Kill within minutes
MEDIUM = "medium" # Kill within hours
LOW = "low" # Kill within days
@dataclass
class KillSwitchConfig:
"""Configuration for a kill switch"""
feature_name: str
severity: KillSwitchSeverity
rollout_percentage: int = 100 # For gradual rollouts
cooldown_period: int = 300 # Seconds before auto-recovery allowed
max_drill_duration: int = 3600 # Max drill duration in seconds
auto_recovery: bool = False # Auto-reenable after cooldown
dependencies: List[str] = field(default_factory=list)
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class KillEvent:
"""Record of a kill switch activation"""
feature_name: str
timestamp: datetime
state: KillSwitchState
triggered_by: str
reason: str
drill_mode: bool = False
affected_users: Optional[int] = None
metadata: Dict[str, Any] = field(default_factory=dict)
# ==================== Storage & Notification Interfaces ====================
class StorageBackend(ABC):
"""Abstract storage backend for kill switch state"""
@abstractmethod
def save_state(self, feature: str, state: KillSwitchState, metadata: Dict):
pass
@abstractmethod
def get_state(self, feature: str) -> Optional[KillSwitchState]:
pass
@abstractmethod
def get_history(self, feature: str, hours: int = 24) -> List[KillEvent]:
pass
class NotificationBackend(ABC):
"""Abstract notification backend"""
@abstractmethod
async def send_alert(self, event: KillEvent, recipients: List[str]):
pass
# ==================== Implementations ====================
class InMemoryStorage(StorageBackend):
"""In-memory storage for development/testing"""
def __init__(self):
self.states: Dict[str, KillSwitchState] = {}
self.history: List[KillEvent] = []
self.lock = threading.RLock()
def save_state(self, feature: str, state: KillSwitchState, metadata: Dict):
with self.lock:
self.states[feature] = state
event = KillEvent(
feature_name=feature,
timestamp=datetime.utcnow(),
state=state,
triggered_by="system",
reason="state_change",
metadata=metadata
)
self.history.append(event)
def get_state(self, feature: str) -> Optional[KillSwitchState]:
with self.lock:
return self.states.get(feature)
def get_history(self, feature: str, hours: int = 24) -> List[KillEvent]:
cutoff = datetime.utcnow() - timedelta(hours=hours)
with self.lock:
return [e for e in self.history
if e.feature_name == feature and e.timestamp > cutoff]
class ConsoleNotification(NotificationBackend):
"""Console notification for development"""
async def send_alert(self, event: KillEvent, recipients: List[str]):
print(f"\n🚨 KILL SWITCH ALERT 🚨")
print(f"Feature: {event.feature_name}")
print(f"State: {event.state.value}")
print(f"Triggered by: {event.triggered_by}")
print(f"Reason: {event.reason}")
print(f"Time: {event.timestamp}")
if event.drill_mode:
print("⚠️ DRILL MODE - No real users affected")
print(f"Recipients: {', '.join(recipients)}\n")
# ==================== Main Kill Switch Manager ====================
class KillSwitchFramework:
"""
Main kill switch framework with drill support
"""
def __init__(
self,
storage: StorageBackend,
notification: Optional[NotificationBackend] = None,
auto_refresh_interval: int = 30
):
self.storage = storage
self.notification = notification
self.auto_refresh_interval = auto_refresh_interval
self._configs: Dict[str, KillSwitchConfig] = {}
self._callbacks: Dict[str, List[Callable]] = {}
self._lock = threading.RLock()
self._monitor_task: Optional[asyncio.Task] = None
self._drill_active: Dict[str, bool] = {}
self.logger = logging.getLogger("KillSwitchFramework")
# Start monitoring
self._start_monitor()
def register_feature(
self,
feature_name: str,
config: KillSwitchConfig,
callback: Optional[Callable[[KillSwitchState], None]] = None
):
"""Register a feature with kill switch capabilities"""
with self._lock:
if feature_name in self._configs:
raise ValueError(f"Feature {feature_name} already registered")
self._configs[feature_name] = config
if callback:
self._callbacks.setdefault(feature_name, []).append(callback)
# Initialize state
current_state = self.storage.get_state(feature_name)
if current_state is None:
self._set_state_internal(feature_name, KillSwitchState.ACTIVE, "initialization")
self.logger.info(f"Registered feature: {feature_name} with severity {config.severity.value}")
def kill(
self,
feature_name: str,
reason: str,
triggered_by: str = "operator",
drill_mode: bool = False,
gradual_percentage: Optional[int] = None
) -> bool:
"""
Kill a feature immediately or gradually
Args:
feature_name: Name of feature to kill
reason: Reason for killing
triggered_by: Who triggered the kill
drill_mode: If True, runs in drill mode (no real impact)
gradual_percentage: For gradual rollout (0-100)
Returns:
bool: Success status
"""
with self._lock:
if feature_name not in self._configs:
self.logger.error(f"Feature {feature_name} not registered")
return False
config = self._configs[feature_name]
# Check dependencies
for dep in config.dependencies:
dep_state = self.storage.get_state(dep)
if dep_state not in [KillSwitchState.ACTIVE, None]:
self.logger.warning(f"Dependency {dep} is not active, killing {feature_name} anyway")
# Determine state
if drill_mode:
state = KillSwitchState.DRILL
self._drill_active[feature_name] = True
elif gradual_percentage is not None:
state = KillSwitchState.GRADUAL
config.rollout_percentage = gradual_percentage
else:
state = KillSwitchState.KILLED
# Save state
metadata = {
"reason": reason,
"triggered_by": triggered_by,
"severity": config.severity.value,
"gradual_percentage": gradual_percentage,
"drill_mode": drill_mode
}
success = self._set_state_internal(feature_name, state, reason, metadata)
if success and self.notification:
event = KillEvent(
feature_name=feature_name,
timestamp=datetime.utcnow(),
state=state,
triggered_by=triggered_by,
reason=reason,
drill_mode=drill_mode,
metadata=metadata
)
# Get recipients from config or use default
recipients = config.metadata.get("alert_recipients", ["ops-team@example.com"])
asyncio.create_task(self.notification.send_alert(event, recipients))
return success
def revive(
self,
feature_name: str,
reason: str,
triggered_by: str = "operator",
gradual_percentage: int = 100
) -> bool:
"""Revive a killed feature"""
with self._lock:
if feature_name not in self._configs:
return False
config = self._configs[feature_name]
# Check cooldown
if config.auto_recovery:
last_kill = self._get_last_kill_time(feature_name)
if last_kill and (datetime.utcnow() - last_kill).total_seconds() < config.cooldown_period:
self.logger.warning(f"Cooldown period active for {feature_name}")
return False
state = KillSwitchState.GRADUAL if gradual_percentage < 100 else KillSwitchState.ACTIVE
config.rollout_percentage = gradual_percentage
metadata = {
"reason": reason,
"triggered_by": triggered_by,
"gradual_percentage": gradual_percentage
}
success = self._set_state_internal(feature_name, state, reason, metadata)
# Clear drill flag if reviving
if feature_name in self._drill_active:
del self._drill_active[feature_name]
return success
def get_state(self, feature_name: str) -> KillSwitchState:
"""Get current state of a feature"""
with self._lock:
state = self.storage.get_state(feature_name)
if feature_name in self._drill_active:
# Override with drill state if active
return KillSwitchState.DRILL
return state or KillSwitchState.ACTIVE
def is_killed(self, feature_name: str) -> bool:
"""Check if feature is killed (including drills)"""
state = self.get_state(feature_name)
return state in [KillSwitchState.KILLED, KillSwitchState.DRILL, KillSwitchState.GRADUAL]
def start_drill(
self,
feature_name: str,
duration_seconds: int,
participants: List[str] = None
) -> bool:
"""
Start a scheduled drill for a feature
Args:
feature_name: Feature to drill
duration_seconds: How long drill should last
participants: Who should be notified
Returns:
bool: Success
"""
if feature_name not in self._configs:
return False
config = self._configs[feature_name]
if duration_seconds > config.max_drill_duration:
self.logger.warning(f"Drill duration exceeds max for {feature_name}")
return False
# Start drill
success = self.kill(
feature_name=feature_name,
reason="Scheduled resilience drill",
triggered_by="drill-scheduler",
drill_mode=True
)
if success and participants:
# Schedule auto-revival
asyncio.create_task(self._schedule_drill_end(feature_name, duration_seconds))
self.logger.info(f"Drill started for {feature_name}, lasting {duration_seconds}s")
return success
async def _schedule_drill_end(self, feature_name: str, duration: int):
"""Auto-end drill after duration"""
await asyncio.sleep(duration)
self.end_drill(feature_name, "Scheduled drill completion")
def end_drill(self, feature_name: str, reason: str = "Manual drill end"):
"""End an active drill"""
with self._lock:
if feature_name in self._drill_active:
# Revive to previous state (simplified - in reality would restore pre-drill state)
self.revive(
feature_name=feature_name,
reason=reason,
triggered_by="drill-coordinator"
)
self.logger.info(f"Drill ended for {feature_name}")
def get_drill_status(self) -> Dict[str, Any]:
"""Get status of all active drills"""
with self._lock:
return {
"active_drills": list(self._drill_active.keys()),
"drill_details": {
f: {
"started": self._get_last_kill_time(f),
"config": self._configs[f].metadata if f in self._configs else {}
}
for f in self._drill_active
}
}
def _set_state_internal(
self,
feature_name: str,
state: KillSwitchState,
reason: str,
metadata: Dict
) -> bool:
"""Internal state setter with callbacks"""
try:
# Save to storage
self.storage.save_state(feature_name, state, metadata)
# Execute callbacks
if feature_name in self._callbacks:
for callback in self._callbacks[feature_name]:
try:
callback(state)
except Exception as e:
self.logger.error(f"Callback error for {feature_name}: {e}")
self.logger.info(f"State changed: {feature_name} -> {state.value}")
return True
except Exception as e:
self.logger.error(f"Failed to set state for {feature_name}: {e}")
return False
def _get_last_kill_time(self, feature_name: str) -> Optional[datetime]:
"""Get timestamp of last kill event"""
history = self.storage.get_history(feature_name, hours=1)
kills = [e for e in history if e.state == KillSwitchState.KILLED]
return kills[0].timestamp if kills else None
def _start_monitor(self):
"""Start background monitoring task"""
async def monitor():
while True:
try:
await self._check_auto_recovery()
await asyncio.sleep(self.auto_refresh_interval)
except Exception as e:
self.logger.error(f"Monitor error: {e}")
try:
loop = asyncio.get_event_loop()
self._monitor_task = loop.create_task(monitor())
except RuntimeError:
# No event loop, skip monitoring
pass
async def _check_auto_recovery(self):
"""Check for features that should auto-recover"""
with self._lock:
for feature_name, config in self._configs.items():
if not config.auto_recovery:
continue
current_state = self.storage.get_state(feature_name)
if current_state == KillSwitchState.KILLED:
last_kill = self._get_last_kill_time(feature_name)
if last_kill and (datetime.utcnow() - last_kill).total_seconds() >= config.cooldown_period:
self.logger.info(f"Auto-reviving {feature_name} after cooldown")
self.revive(feature_name, "Auto-recovery after cooldown")
def shutdown(self):
"""Clean shutdown"""
if self._monitor_task:
self._monitor_task.cancel()
# ==================== Feature Integration Helper ====================
class FeatureGuard:
"""
Decorator/context manager for wrapping risky features
Usage:
@feature_guard("payment_processing")
def process_payment(...):
...
"""
def __init__(self, kill_switch: KillSwitchFramework, feature_name: str):
self.kill_switch = kill_switch
self.feature_name = feature_name
self._original_func = None
def __call__(self, func):
self._original_func = func
return self._wrapped
def _wrapped(self, *args, **kwargs):
if self.kill_switch.is_killed(self.feature_name):
state = self.kill_switch.get_state(self.feature_name)
if state == KillSwitchState.DRILL:
# In drill mode, we might want to simulate the feature
return self._simulate_execution(*args, **kwargs)
else:
raise FeatureKilledError(
f"Feature {self.feature_name} is killed. "
f"State: {state.value}"
)
return self._original_func(*args, **kwargs)
def _simulate_execution(self, *args, **kwargs):
"""Simulate feature execution during drill"""
# Implement mock behavior or return safe defaults
return None
@contextmanager
def guard(self):
"""Context manager version"""
if self.kill_switch.is_killed(self.feature_name):
raise FeatureKilledError(f"Feature {self.feature_name} is killed")
yield
class FeatureKilledError(Exception):
"""Raised when attempting to use a killed feature"""
pass
# ==================== Dashboard/API Interface ====================
class KillSwitchDashboard:
"""Dashboard interface for operators"""
def __init__(self, kill_switch: KillSwitchFramework):
self.kill_switch = kill_switch
def get_all_features_status(self) -> Dict[str, Dict]:
"""Get status of all registered features"""
status = {}
for feature_name, config in self.kill_switch._configs.items():
state = self.kill_switch.get_state(feature_name)
history = self.kill_switch.storage.get_history(feature_name, hours=24)
status[feature_name] = {
"state": state.value,
"severity": config.severity.value,
"rollout_percentage": config.rollout_percentage,
"last_24h_kills": len([e for e in history if e.state == KillSwitchState.KILLED]),
"dependencies": config.dependencies,
"auto_recovery": config.auto_recovery,
"in_drill": feature_name in self.kill_switch._drill_active
}
return status
def execute_emergency_kill(self, feature_name: str, reason: str):
"""Emergency kill bypassing normal checks"""
self.kill_switch.kill(
feature_name=feature_name,
reason=f"EMERGENCY: {reason}",
triggered_by=" emergency-response"
)
def run_scheduled_drill(
self,
feature_name: str,
duration_minutes: int = 15,
participants: List[str] = None
):
"""Schedule a drill"""
self.kill_switch.start_drill(
feature_name=feature_name,
duration_seconds=duration_minutes * 60,
participants=participants or []
)
# ==================== Configuration Example ====================
def create_production_framework() -> KillSwitchFramework:
"""Create production-ready framework with real backends"""
# In production, use persistent storage (Redis, DB, etc.)
storage = InMemoryStorage() # Replace with RedisStorage, PostgresStorage, etc.
# Use real notification (Slack, PagerDuty, email)
notification = ConsoleNotification() # Replace with SlackNotification, etc.
framework = KillSwitchFramework(
storage=storage,
notification=notification,
auto_refresh_interval=30
)
# Register features
features = [
("payment_processing", KillSwitchConfig(
feature_name="payment_processing",
severity=KillSwitchSeverity.CRITICAL,
cooldown_period=600,
dependencies=["user_service", "fraud_detection"],
metadata={"alert_recipients": ["payments-team@example.com"]}
)),
("new_ui_checkout", KillSwitchConfig(
feature_name="new_ui_checkout",
severity=KillSwitchSeverity.HIGH,
rollout_percentage=10, # Start with 10%
auto_recovery=False
)),
("recommendation_engine", KillSwitchConfig(
feature_name="recommendation_engine",
severity=KillSwitchSeverity.MEDIUM,
cooldown_period=300
))
]
for name, config in features:
framework.register_feature(name, config)
return framework
# ==================== Usage Examples ====================
# Example 1: Basic usage
def example_basic():
framework = create_production_framework()
dashboard = KillSwitchDashboard(framework)
# Check feature status
status = dashboard.get_all_features_status()
print(f"Payment processing state: {status['payment_processing']['state']}")
# Kill a feature
framework.kill(
"new_ui_checkout",
reason="High error rate detected",
triggered_by="alerts@monitoring",
gradual_percentage=0 # Immediate kill
)
# Use with guard
guard = FeatureGuard(framework, "payment_processing")
try:
with guard.guard():
process_payment() # Will raise if killed
except FeatureKilledError as e:
print(f"Feature unavailable: {e}")
# Example 2: Drills
def example_drills():
framework = create_production_framework()
# Schedule weekly drill
framework.start_drill(
feature_name="recommendation_engine",
duration_seconds=300, # 5 minutes
participants=["team@example.com"]
)
# Check drill status
drill_status = framework.get_drill_status()
print(f"Active drills: {drill_status['active_drills']}")
# Manually end drill early
framework.end_drill("recommendation_engine", "Completed early")
# Example 3: Gradual rollout
def example_gradual():
framework = create_production_framework()
# Gradual rollout
for percentage in [10, 25, 50, 100]:
framework.revive(
"new_ui_checkout",
reason=f"Gradual rollout to {percentage}%",
gradual_percentage=percentage
)
# Monitor metrics, wait for stability, then continue
asyncio.sleep(3600) # Wait 1 hour between steps
# Example 4: Decorator usage
@FeatureGuard(create_production_framework(), "payment_processing")
def process_payment(user_id: str, amount: float):
"""Process payment - automatically protected by kill switch"""
# Implementation
return {"status": "processed", "transaction_id": "123"}
# ==================== Production Considerations ====================
"""
PRODUCTION DEPLOYMENT CHECKLIST:
1. **Storage Backends**:
- Use persistent storage (Redis, PostgreSQL, DynamoDB)
- Implement TTL for temporary states
- Backup/restore procedures
2. **Notification Systems**:
- Integrate with PagerDuty/Opsgenie for critical kills
- Slack/Teams for team notifications
- SMS for emergency contacts
3. **Monitoring & Metrics**:
- Track kill switch activations per feature
- Measure MTTR (Mean Time To Recover)
- Drill success/failure rates
- Dashboard with Grafana/Prometheus
4. **Access Control**:
- RBAC for kill switch operations
- Audit logging of all changes
- Multi-person approval for critical features
5. **Drill Automation**:
- Schedule regular drills (weekly/monthly)
- Automatic drill reporting
- Integration with Chaos Engineering tools
6. **Gradual Rollout Support**:
- Percentage-based rollout
- User segment targeting
- Real-time metric monitoring during rollout
7. **Dependency Management**:
- Automatic dependency kill cascade
- Circular dependency detection
- Dependency impact analysis
8. **Compliance & Safety**:
- PCI-DSS compliance for payment features
- SOX controls for financial features
- GDPR considerations for user data features
9. **Testing**:
- Unit tests for all kill switch logic
- Integration tests with real storage
- End-to-end drill tests in staging
- Chaos testing in production-like environments
10. **Documentation**:
- Runbooks for each feature's kill procedure
- Post-mortem templates for incidents
- Training materials for on-call teams
"""
if __name__ == "__main__":
# Quick demo
framework = create_production_framework()
dashboard = KillSwitchDashboard(framework)
print("=== Initial Status ===")
print(json.dumps(dashboard.get_all_features_status(), indent=2))
print("\n=== Starting Drill ===")
framework.start_drill("recommendation_engine", 60)
print(f"Drill status: {framework.get_drill_status()}")
print("\n=== After Kill ===")
framework.kill("recommendation_engine", "Test kill", drill_mode=True)
print(f"Recommendation engine state: {framework.get_state('recommendation_engine')}")
Key Features Implemented:
1. Core Kill Switch Functionality
- Immediate kill/revive operations
- State persistence via storage backend
- Severity levels with different response requirements
- Dependency management
2. Drill Support
- Drill Mode: Simulates kills without affecting real users
- Scheduled Drills: Time-boxed drill execution
- Drill Monitoring: Track active drills and participants
- Auto-completion: Drills end automatically after duration
3. Gradual Rollout
- Percentage-based rollout/rollback
- State progression tracking
- Safe migration patterns
4. Safety Mechanisms
- Cooldown periods: Prevent flapping
- Auto-recovery: Optional automatic revival
- Dependency checks: Kill cascades safely
- Unregistered feature protection: Default safe behavior
5. Observability
- Complete event history
- Dashboard API for monitoring
- Callback system for custom reactions
- Audit trail with metadata
6. Production Features
- Pluggable storage backends
- Multiple notification channels
- Access control ready (RBAC hooks)
- Monitoring/metrics integration points
Deployment Strategy:
Phase 1: Registration
- Identify risky features (payment processing, new UI, ML models, etc.)
- Register each with appropriate severity and dependencies
- Define recovery procedures in metadata
Phase 2: Drill Schedule
- Weekly: Low-severity features (5-min drills)
- Monthly: Medium-severity features (15-min drills)
- Quarterly: Critical features (30-min full drills)
- Always: On-call rotation drills
Phase 3: Monitoring
- Alert on any kill switch activation
- Track drill completion rates
- Monitor MTTR (Mean Time To Recover)
- Dashboard for real-time visibility
Phase 4: Chaos Integration
- Integrate with Chaos Mesh/Gremlin
- Random feature kills during low-traffic periods
- Automated drill scenarios
Best Practices:
- Always register features before deployment
- Test drills in staging before production
- Document recovery procedures per feature
- Monitor during drills - watch system metrics
- Post-drill analysis - what broke, what worked
- Gradual rollout for new features (start with 1%)
- Regularly update dependency matrices
- Train on-call teams on kill switch procedures
- Include in incident response playbooks
- Review drill results in sprint retrospectives
Emergency Procedures:
# Emergency Response Playbook:
# 1. Identify affected feature
affected = dashboard.get_all_features_status()["payment_processing"]
# 2. Immediate kill if not already
if affected["state"] != "killed":
dashboard.execute_emergency_kill(
"payment_processing",
"Critical error rate > 5%"
)
# 3. Notify stakeholders
# (Automatic via notification backend)
# 4. Investigate while feature is killed
# ... investigation ...
# 5. Partial recovery if possible
framework.revive(
"payment_processing",
"Hotfix deployed",
gradual_percentage=10 # 10% traffic first
)
# 6. Monitor and gradually increase
for pct in [25, 50, 75, 100]:
framework.revive(
"payment_processing",
f"Gradual rollout to {pct}%",
gradual_percentage=pct
)
monitor_for_errors(minutes=30)
This framework provides defense-in-depth for risky features with:
- ✅ Immediate emergency kill capability
- ✅ Regular resilience testing via drills
- ✅ Safe gradual rollouts
- ✅ Complete observability
- ✅ Production-ready architecture
- ✅ Compliance-ready audit trails
Remember: A kill switch is only as good as your演练 (drills). Test it regularly!