We are going to design a system that simulates incidents based on real production topology, dependency graphs, and failure modes.
Components:
Topology Representation:
We need a way to represent the production topology (servers, services, networks, etc.) and their dependencies.
This could be stored in a configuration file (YAML/JSON) or in a database. For simplicity, let's assume we use a YAML file.
Failure Modes:
A set of failure modes that can occur on each component (e.g., CPU high, memory leak, network latency, service crash, etc.).
Each failure mode may have:
Probability (how likely it is to occur in a given simulation run)
Impact (how it affects the component and downstream dependencies)
Symptoms (what metrics or logs would show)
Incident Simulation Generator:
Given the topology and a set of failure modes, the generator will produce a scenario (a sequence of events or a state) that represents an incident.
The scenario should be realistic, meaning that failures propagate according to the dependency graph.
Scenario Output:
The output should be a structured description of the incident, including:
Which component(s) failed and how (failure mode)
The timeline of events (if we are simulating over time)
The impact on the system (e.g., which services are degraded, which alerts would fire)
Possibly, the metrics and logs that would be generated.
Extensibility:
The system should be extensible to new failure modes and topology changes.
Design:
Let's define:
Node: A component in the topology (e.g., a server, a service, a database). Each node has:
id
type (e.g., 'web_server', 'database', 'cache')
dependencies (list of node ids that this node depends on)
dependents (list of node ids that depend on this node) [could be computed from dependencies]
FailureMode: A class that defines:
name
applicable_node_types (list of node types that this failure mode can apply to)
probability (for random selection)
symptoms: a dictionary of metric changes (e.g., 'cpu_usage': 'high', 'error_rate': 'increased')
propagation_effects: how this failure affects its dependents (e.g., if a database fails, then the services that depend on it might experience timeouts)
Scenario: A collection of one or more failures that occur in the system, possibly with a timeline.
Steps:
Load the topology (from a YAML file).
For each node, based on its type, we have a set of possible failure modes.
Randomly select one or more failure modes (with associated probability) to occur on one or more nodes.
We might want to start with a single root failure and then let it propagate.
Alternatively, we might have multiple concurrent failures.
Propagate failures through the dependency graph:
If a node fails in a way that affects its dependents, then the dependents may experience symptoms (and possibly fail themselves if the failure mode is severe enough).
Generate the scenario description:
Example:
Initial failure: Node A (database) experiences a 'disk_full' failure.
Symptoms on Node A: disk usage 100%, I/O wait high.
Propagation: Node B (web service) depends on Node A, so Node B experiences increased latency and timeouts.
Then, Node B might crash if the failure mode on Node A is catastrophic and Node B doesn't have retries.
Output:
We can output in a structured format (JSON) that includes:
Defines a set of failure modes (could be in a separate YAML or hard-coded for now).
Simulates an incident by selecting a random node and a random failure mode (or a set of them) and then propagates.
However, note: we want to generate training scenarios that are realistic. So we might want to control the incident to be of a certain type (e.g., cascading failure, single point of failure, etc.)
where scenario_type could be:
- 'random': completely random
- 'cascading': start with one failure and let it cascade
- 'single': single failure without propagation (if the failure mode doesn't propagate)
We need to model the propagation rules for each failure mode.
For example, a failure mode on node X might cause:
- For each dependent node Y:
- If the failure mode on X is 'timeout', then Y might experience 'increased_latency' and if above threshold, then Y might also fail (if Y doesn't have Circuit Breaker, etc.)
But note: we are not actually running the system, so we are simulating based on a model.
We can define for each failure mode:
code
propagation:
- target: dependent (the node that depends on the failed node)
condition: (optional) condition under which the dependent is affected (e.g., if the failure duration is more than X seconds)
effect: the failure mode that is induced on the dependent (could be a different failure mode, e.g., 'timeout' on the dependent because of 'disk_full' on the database)
Alternatively, we can have a more generic model:
code
Each failure mode has:
- direct_symptoms: on the node itself
- propagation_rules: list of rules that apply to dependents.
Rule:
- applies_to: 'direct_dependents' (or maybe all nodes that have a dependency on the failed node, and we can filter by type?)
- condition: (optional) condition based on the failed node's symptoms (e.g., if the latency is > 1000ms)
- induced_failure_mode: the failure mode that is triggered on the dependent (could be the same or different)
- probability: the chance that the dependent actually fails (because maybe the dependent has retries, etc.)
Then, when a node fails with 'disk_full', for each dependent we check the condition (on the failed node's symptoms) and with probability 0.9, the dependent gets the 'timeout' failure mode.
But note: the condition is on the failed node, but the failure mode on the dependent is 'timeout'. Then, the 'timeout' failure mode on the dependent might have its own propagation rules.
Implementation steps:
a. Load topology and build a graph (using networkx, for example, but we can also do without if the graph is small and we just have a list of nodes and dependencies).
b. For each node, we compute:
- dependents: nodes that depend on this node.
c. Select initial failure(s):
- Randomly choose a node (or nodes) and a failure mode that is applicable to that node.
d. For each initial failure, we create an event with:
- node_id
- failure_mode
- time (starting at 0, then incrementing for propagation steps)
- symptoms (from the failure mode definition)
e. Then, for each failure event, we look at its dependents and apply propagation rules of the failure mode.
code
For each dependent node:
- Check if the dependent already has a failure? (if yes, maybe we don't apply again, or we merge? Let's assume we don't apply if already failed, but we might want to have multiple failure modes on the same node? Probably not for simplicity.)
- For each propagation rule of the failure_mode:
- Check if the condition (on the failed node's symptoms) is met. (We have the symptoms of the failed node at the time of failure? But note: symptoms might change over time? We are simulating statically, so we assume the symptoms are static as per the failure mode definition.)
- With the given probability, induce the induced_failure_mode on the dependent.
- If we induce a failure on the dependent, then we schedule it at a later time (e.g., current time + propagation delay). We can have a propagation delay per rule.
We continue until no new failures are induced or until we reach a maximum time.
f. We then collect all failure events (with timestamps) and generate the scenario.
We also need to generate human-readable description and the impact.
Impact: list of services that are degraded (nodes that have at least one failure mode that affects their operation). We can define for each failure mode whether it makes the node unavailable or degraded.
Alternatively, we can say: if a node has a failure mode that causes it to not function properly, then it is impacted.
We can also compute the ripple effect: all nodes that are downstream of a failed node (if the failure propagates) are impacted.
Alerts: we can have a mapping from failure modes and symptoms to alerts. For example, if a node has 'disk_full', then alert "DiskSpaceCritical" would fire.
We can have a separate configuration for alerts, but for simplicity, we can generate alerts based on the symptoms.
Build a mapping from node id to node object, and also build a graph (using networkx or just a dict of dependents).
code
We can have:
node_dependents = {node_id: []}
for node in nodes:
for dep in node.dependencies:
node_dependents[dep].append(node.id)
Define failure modes:
code
We can have a dictionary:
FAILURE_MODES = {
'disk_full': {
'applicable_node_types': ['postgresql', 'mysql', ...],
'direct_symptoms': {
'disk_usage': 100,
'io_wait': 'high'
},
'propagation_rules': [
{
'applies_to': 'direct_dependents',
'condition': "io_wait > 80%", # we need to evaluate this condition on the failed node's symptoms
'induced_failure_mode': 'timeout',
'probability': 0.9,
'delay': 5 # seconds
}
]
},
'timeout': {
'applicable_node_types': ['web_server', 'api_service', ...],
'direct_symptoms': {
'latency': 'high',
'error_rate': 'increased'
},
'propagation_rules': [...]
}
}
But note: the condition in propagation_rules is a string. We can evaluate it in a context where we have the symptoms of the failed node.
Alternatively, we can have condition as a function that takes the symptoms and returns boolean.
Since we are in Python, we can define the failure modes as Python classes or dictionaries with callable conditions.
Implementation:
code
13. We'll also need to handle the case where a node has multiple dependencies and one of them fails. The propagation rule applies to direct dependents? Then if a node has two dependencies and one fails, it might get affected? But note: the rule says "direct_dependents", meaning the nodes that depend on this node. So if node A fails, then the nodes that depend on A (say B and C) are affected. But if B depends on both A and D, and A fails, then B might still work because of D? We are not modeling that. We are just saying: if a node you depend on fails, then you might be affected.
code
This is a simplification. In reality, if a node has multiple dependencies and one fails, it might degrade but not fail. But for our simulation, we are inducing a failure on the dependent if the condition is met. So we are modeling that the dependent fails because of the dependency failure.
Alternatively, we can have a rule that says: if the dependent has multiple dependencies and one fails, then we check the criticality of the dependency? That would be more complex.
For now, we assume that if a dependency fails (and the propagation rule condition is met), then the dependent gets the induced failure mode.
14. Let's code accordingly.
We also need to avoid infinite loops. If we have a cycle in the dependency graph, we might keep propagating. But in a typical service dependency, we don't have cycles (or if we do, they are through asynchronous calls and we don't want to model that). We'll assume the dependency graph is acyclic. If not, we can limit the propagation depth.
We'll also need to decide on the initial failures. For cascading scenario, we pick one node and one failure mode. For random, we pick multiple.
code
How to pick? We can have a weight for each node and failure mode.
code
Let's have:
node_weights: we can weight by the criticality of the node (e.g., if it's a database, higher weight). Or we can have a random choice.
For simplicity, we'll pick a random node and then a random failure mode that is applicable to that node.
For multiple initial failures, we can pick N random nodes and for each a random failure mode.
17. Let's code step by step.
We'll also want to generate a human-readable description.
We'll assume the topology and failure modes are provided in YAML.
We'll also need to handle the case where a propagation rule has a target that is not 'direct_dependents'. We can extend to 'all_dependents' (transitive) but for now, only direct.
We'll assume the propagation delay is in seconds.
We'll simulate in seconds.
We'll generate a scenario with a start time (we can use the current time or a fixed one). For simplicity, we'll set the initial events at time 0.
We'll use a priority queue (heapq) to process events in time order.
Code structure:
events = [] # list of (time, node_id, failure_mode, symptoms, caused_by)
We start by pushing the initial events.
Then:
while events and current_time <= max_time and event_count < max_events:
pop the next event (earliest time)
if the node already has a failure (with any failure mode) then skip?
But note: we might want to allow multiple failure modes? Let's not for now.
So we have a set of failed_nodes.
code
Then, for this event, we record it in the scenario.
Then, we call _propagate for this event, which may schedule new events.
We need to avoid scheduling the same failure mode on the same node multiple times? We are skipping if the node is already failed.
But what if we have two different failure modes on the same node? We are not allowing that because we mark the node as failed with one failure mode.
Alternatively, we can allow multiple failure modes on the same node? That would be more complex. Let's not.
Let's code accordingly.
We'll also generate the description:
For cascading:
"A <failure_mode> on <node_id> caused a cascade of failures affecting ."
For random:
"Multiple simultaneous failures: ..."
Let's code.
Due to the complexity, we'll write a simplified version that works for the cascading scenario.
We'll assume:
code
- The topology is a DAG.
- Each node can only have one failure mode at a time.
- Propagation only goes to direct dependents.
30. Let's code the simulator.
Note: This is a simulation for training scenarios, so we don't need to be 100% accurate, but we want it to be plausible.
We'll also need to handle the case where a node's failure mode might have multiple propagation rules? Yes, we loop through all rules.
We'll also need to handle the condition_operator. We can use a dictionary of operator functions.
Let's code.
I'll design a comprehensive incident simulation system that leverages real production topology to generate realistic training scenarios. This is a sophisticated system that requires multiple components working together.
Gradual Degradation: Slow-burn scenarios (memory leaks, disk fills)
Human Factor Injection: Add operator errors (bad deployments, config mistakes)
Correlated Failures: Simultaneous failures on unrelated services
Recovery Failure Scenarios: Failed recovery attempts making things worse
Integration Points
Monitoring Systems: Ingest Prometheus/Datadog metrics for realism validation
CI/CD Pipelines: Generate scenarios from deployment patterns
Postmortem Database: Learn from past incidents to improve realism
Chaos Engineering Platforms: Export scenarios to Chaos Mesh/Gremlin
Training Platforms: Export to platforms like OpsLevel, Rundeck
This system transforms static topology data into dynamic, realistic training scenarios that help teams prepare for actual production incidents while maintaining safety constraints (blast radius limits, exclude critical production systems, etc.).
We need to simulate over time? Not necessarily for a static scenario. We can just generate the end state or a timeline of propagation.
Let's assume we simulate until no more propagation occurs (or until a maximum depth).
We also might want to have multiple initial failures. We can randomly pick N initial nodes and failure modes.
We must avoid cycles in the dependency graph? Typically, dependencies are acyclic, but if there are cycles we must be careful to avoid infinite propagation.
However, for flexibility, let's define the condition as a string and then use a simple expression evaluator (like eval with a safe context) or we can define a mapping of condition names.
Alternatively, we can avoid string conditions and have the condition as a dictionary:
But note: the symptom might be a string like 'high' or a number. We need to convert.
Let's standardize symptoms as:
code
For each failure mode, we define a dictionary of symptoms with values that are either:
- a number (e.g., disk_usage: 100)
- a string that we can map to a number (e.g., 'high' -> 90, 'medium' -> 50) but that might be too vague.
Alternatively, we can have the condition in the propagation rule refer to the symptom by key and then we compare to a threshold.
Then, when we have the failed node's symptoms, we get the value of condition_metric and compare.
But note: the symptom value might be a string. We need to convert to a number. We can define:
code
For numeric symptoms: we have a number.
For categorical symptoms: we can map to a number? Or we can have a different condition type.
Alternatively, we can have the condition as a function that takes the symptoms and returns a boolean. Then we can define the failure modes in code.
Since we are building a simulator, we can define the failure modes in a Python module and not in YAML. But for flexibility, let's try to have them in YAML and then load.
Let's decide: We'll have the failure modes defined in a YAML file with the following structure:
But note: the condition_metric must be in the direct_symptoms of the failed node.
Simulation:
We'll maintain a list of events (each event: time, node_id, failure_mode, symptoms).
We start with initial failures.
Then we process events in time order (like a discrete event simulation).
For each event:
- Mark the node as failed with the failure mode (if not already failed, but if already failed, we might want to merge? Let's not induce if already failed, but we might want to record multiple failure modes? For simplicity, one node can have only one failure mode at a time. But in reality, a node can have multiple issues. However, for training scenarios, we might want to keep it simple.
code
- Then, for each propagation rule of the failure_mode:
- For each dependent of the node (according to the rule's target, e.g., direct_dependents):
- Check if the dependent already has a failure? If yes, skip.
- Check the condition on the failed node's symptoms (the event's symptoms).
- With probability, induce the induced_failure_mode on the dependent at time = current_time + delay.
We continue until we have no more events to process or until a max time.
After simulation, we have a list of failure events.
Then, we compute the impact:
code
For each node that has at least one failure event, it is impacted.
We can also compute the services that are unavailable: if a node is a service and it failed, then the service is down.
Alerts:
code
We can have a list of alert definitions:
alerts:
- name: "HighDiskUsage"
condition_node_type: ["postgresql", "mysql"]
condition_metric: "disk_usage"
condition_threshold: 90
condition_operator: ">"
Then, for each node that has a failure event, we check the node's symptoms (from the failure mode) and if the condition matches, then the alert fires.
But note: the alert might fire even if the node hasn't failed yet? In our simulation, we only have failure events, so we only consider the symptoms at the time of failure.
Alternatively, we can simulate metrics over time and then check alerts at each time step? That would be more complex.
For simplicity, we'll generate alerts that fire at the time of the failure event that caused the symptom.
Output:
code
We'll generate a JSON with:
{
"scenario_id": "uuid",
"description": "A cascading failure starting with a disk full on db-1 leading to timeouts on web-1",
"topology": { ... }, # we can include the topology nodes and dependencies
"failure_events": [
{
"time": 0,
"node_id": "db-1",
"failure_mode": "disk_full",
"symptoms": {"disk_usage": 100, "io_wait": 90}
},
{
"time": 5,
"node_id": "web-1",
"failure_mode": "timeout",
"symptoms": {"latency": "high", "error_rate": "increased"},
"caused_by": "db-1"
}
],
"impacted_nodes": ["db-1", "web-1"],
"alerts": [
{
"time": 0,
"alert_name": "HighDiskUsage",
"node_id": "db-1"
},
{
"time": 5,
"alert_name": "HighLatency",
"node_id": "web-1"
}
]
}
Let's code accordingly.
We'll also want to have the ability to generate multiple scenarios and maybe filter by scenario type.
We might want to have the initial failure selection weighted by the criticality of the node? Or by the failure mode probability.
We'll assume that the topology YAML and failure modes YAML are provided.
Let's create a class:
class IncidentSimulator:
def __init__(self, topology_file, failure_modes_file, alerts_file=None):
self.topology = self.load_topology(topology_file)
self.failure_modes = self.load_failure_modes(failure_modes_file)
self.alerts = self.load_alerts(alerts_file) if alerts_file else []
def load_topology(self, file):
# returns a dict with:
# nodes: list of dicts (id, type, dependencies)
# we also build a graph (dependents)
pass
def load_failure_modes(self, file):
# returns a dict: key=failure_mode_name, value=dict with:
# applicable_node_types, direct_symptoms, propagation_rules
pass
def load_alerts(self, file):
# returns a list of alert definitions
pass
def generate_scenario(self, scenario_type='random', max_time=300, max_events=100):
# scenario_type: 'random', 'cascading', etc.
# We'll implement:
# - cascading: pick one initial node and failure mode, then propagate until no more.
# - random: pick multiple initial nodes and failure modes, then propagate each independently (or together?).
# - single: pick one initial node and failure mode, and don't propagate (even if propagation rules exist?).
# We'll return a scenario dictionary.
def _propagate(self, event, current_time, events, node_failure_modes, dependents):
# For the given event (which has a failure mode and symptoms), look up the propagation rules.
# For each rule, for each dependent (based on rule target), check condition and probability.
# If condition met and random < probability, then schedule a new event for the dependent at current_time + delay.
pass
def _check_condition(self, condition_metric, condition_operator, condition_threshold, symptoms):
# symptoms is a dict of the failed node's symptoms.
# Get the value of condition_metric from symptoms.
# Compare using condition_operator (which can be '>', '<', '>=', '<=', '==', '!=').
pass
def _get_symptom_value(self, symptom_key, symptoms):
# Return the numeric value of the symptom. If it's a string, we might have a mapping?
# For now, we assume symptoms are numbers or strings that we can map?
# Let's assume we only use numbers for conditions.
pass
def _generate_alerts(self, events):
# For each event, check if any alert condition is met by the node's symptoms at that event.
# But note: the alert condition might be on a metric that is not in the failure mode's symptoms?
# We are only simulating failure modes, so we only have the symptoms from the failure mode.
# So we assume that the failure mode's symptoms are the ones that trigger alerts.
# Alternatively, we can have alerts that are triggered by the presence of a failure mode?
# Let's do: for each alert, we check if the node type matches and then if the symptom (by metric) matches the condition.
pass
# scenario_generator.py
import networkx as nx
from datetime import datetime, timedelta
from typing import List, Dict, Tuple
import random
class IncidentSimulator:
def __init__(self, topology, failure_library):
self.graph = self._build_graph(topology)
self.failure_library = failure_library
self.scenario_id = 0
def generate_scenario(self,
scenario_type: str = "cascading",
max_blast_radius: int = 5,
include_rare_failures: bool = False) -> Dict:
"""
Generate a realistic incident scenario
"""
self.scenario_id += 1
# 1. Select initial failure point based on criticality weighted random
initial_node = self._select_initial_node(scenario_type)
# 2. Select applicable failure mode
failure_mode = self._select_failure_mode(initial_node, include_rare_failures)
# 3. Build incident timeline
timeline = self._build_timeline(initial_node, failure_mode, max_blast_radius)
# 4. Calculate impact metrics
impact = self._calculate_impact(timeline)
# 5. Generate associated artifacts (logs, metrics, alerts)
artifacts = self._generate_artifacts(timeline)
return {
"scenario_id": f"INC-{self.scenario_id:04d}",
"timestamp": datetime.utcnow().isoformat(),
"scenario_type": scenario_type,
"topology_snapshot": self._get_topology_snapshot(timeline),
"timeline": timeline,
"impact_assessment": impact,
"artifacts": artifacts,
"training_objectives": self._extract_training_objectives(timeline),
"runbook_required": self._determine_runbook_need(timeline)
}
def _build_graph(self, topology) -> nx.DiGraph:
"""Convert topology to directed dependency graph"""
G = nx.DiGraph()
# Add service nodes
for service in topology['services']:
G.add_node(service['id'],
type='service',
criticality=service.get('criticality', 'P3'),
**service)
# Add dependency edges
for dep in service.get('dependencies', []):
G.add_edge(service['id'], dep, type='service_dependency')
# Add datastore nodes
for db in topology.get('datastores', []):
G.add_node(db['id'], type='datastore', **db)
# Add network dependencies
for net in topology.get('networks', []):
G.add_node(net['id'], type='network', **net)
return G
def _select_initial_node(self, scenario_type: str) -> str:
"""Select initial failure node based on scenario type"""
if scenario_type == "single_point_failure":
# Target highest criticality nodes
critical_nodes = [n for n, attr in self.graph.nodes(data=True)
if attr.get('criticality') == 'P1']
return random.choice(critical_nodes) if critical_nodes else random.choice(list(self.graph.nodes()))
elif scenario_type == "cascading":
# Select nodes with many dependents
nodes_with_dependents = [(n, self.graph.out_degree(n))
for n in self.graph.nodes()]
nodes_with_dependents.sort(key=lambda x: x[1], reverse=True)
return random.choice([n for n, _ in nodes_with_dependents[:10]])
else: # random
return random.choice(list(self.graph.nodes()))