People hear “chaos engineering” and picture a script that SSHes into a box and kills a process. That is the demo. The hard part is not injecting the failure; injecting failure is easy and, frankly, anyone can kill -9. The hard part is doing it in production, on purpose, without taking production down, and being able to prove - mechanically, not by a human watching a dashboard - that the moment the experiment starts hurting real users, it stops.
A chaos engineering platform is a safety system wearing a sabotage system’s clothes. Netflix’s Chaos Monkey terminates instances; that is the famous one-liner. But the thing that makes it shippable to a real company is everything around the kill: the blast radius controls that say “only 5% of one service in one region,” the steady-state hypothesis that defines what “healthy” means before you break anything, and above all the automated abort - a control loop watching live error-rate and latency metrics that can halt and roll back the experiment in seconds, before a human has even read the alert.
So the core problem I am actually designing is this: run a controlled failure injection against a blast-radius-limited slice of production, continuously evaluate real-time reliability metrics against a predefined threshold, and if the threshold is crossed, abort and roll back every injected fault automatically and fast, independent of the human who scheduled the experiment. Everything else - the fault types, the scheduler, the UI - hangs off that control loop. Let me do it properly.
Functional Requirements (FR)
In scope:
- Define an experiment. An engineer declares a steady-state hypothesis (“checkout success rate stays above 99.5%, p99 latency under 400ms”), a target selector (which services, pods, regions), a fault to inject, a blast radius (what percentage of the target), a duration, and abort conditions (the metric thresholds that halt it).
- Inject faults. The platform supports a catalog of fault types: latency injection (add N ms of delay to a percentage of requests), error injection (return 5xx / inject exceptions for a percentage of calls), packet loss / network partition (drop or delay packets between services), resource stress (CPU, memory, disk fill), and pod/instance termination (kill a fraction of replicas). These run against staging or production.
- Limit blast radius. Every experiment targets a bounded slice: a percentage of traffic, a specific set of pods, one availability zone, or a subset of users. The platform enforces the bound; the user cannot inject into “everything” by accident.
- Automated rollback / abort (the hard part). A control loop watches real-time metrics (error rate, latency, saturation) for the blast-radius slice and for global health. If any abort condition crosses its threshold, the experiment is halted immediately and all injected faults are reverted, before the scheduled end time, without human action.
- Schedule and run experiments. On demand or on a recurring schedule (the Chaos Monkey model: randomly terminate an instance during business hours). Concurrency limits prevent two overlapping experiments from compounding.
- Observe and report. Live view of an in-flight experiment (what is injected, current metrics vs thresholds), and a durable post-run report: hypothesis, what was injected, what broke, whether it aborted, and the metric timeline.
- Guardrails and governance. Global kill switch, allowlists of what can be targeted, business-hours windows, required approvals for production experiments, and a hard cap on simultaneous blast radius across all running experiments.
Explicitly out of scope (state this to bound the problem):
- The fault-mitigation itself. We expose weaknesses; we do not auto-fix the service under test. Remediation is the service team’s job.
- Full observability/metrics pipeline. We consume a metrics system (Prometheus-style time series, or a streaming metrics bus). We do not design the metrics store from scratch, though the abort loop’s read path is in scope and is a deep dive.
- Load generation. Some experiments need traffic to be meaningful, but a load-testing system is a separate component we trigger, not build.
- CI/CD and deployment. We hook into deploys (block a deploy if a chaos gate fails) but do not design the pipeline.
- Auth/identity. Assume an authenticated
user_idwith resolved RBAC reaches the control plane.
The decision that drives everything: the fault injection and the abort loop must be able to run even when the central control plane is degraded. If chaos could only be stopped by a healthy central brain, then a chaos experiment that damages the network could sever the very path used to stop it. So abort authority is pushed close to the fault, with a dead-man’s-switch default. More on that below - it is the crux.
Non-Functional Requirements (NFR)
- Scale: a large engineering org. Thousands of services, tens of thousands of hosts/pods, hundreds of teams. The platform itself is low-QPS on the control plane (experiments are defined by humans, maybe thousands per day across the org) but the data plane - the injection agents and the metric evaluation - runs on every targeted host and reads metrics at high frequency. Assume up to a few thousand concurrent experiments at peak across the fleet, each touching from a handful to a few hundred pods.
- Latency (the number that matters): time-to-abort. From the moment a metric crosses threshold to the moment faults are fully reverted must be single-digit seconds, ideally under ~3-5s end to end. This is the whole product. A rollback that takes 30s is a rollback that let 30s of a production incident through.
- Availability: the abort path must be more available than the thing it protects. Target 99.99%+ for abort, and critically, fail-safe: if the control plane is unreachable, running experiments abort themselves rather than continue blind.
- Consistency: experiment definitions and state transitions (scheduled -> running -> aborted/completed) must be strongly consistent and have a single source of truth - you cannot have two components disagreeing about whether an experiment is live. The metric reads that drive abort are best-effort and recent; we use windows and quorums, not exactly-once.
- Durability: experiment definitions, run history, and audit logs are durable (compliance and post-mortems depend on them). Live injected-fault state must be durably recoverable: if an agent crashes mid-experiment, the fault must be reverted on restart, never left stuck on.
- Safety over completeness: when in doubt, abort. A false abort (stopping a healthy experiment) costs an engineer a re-run. A missed abort (letting a bad experiment ride) costs a production outage. The system is deliberately biased toward the cheap failure.
Back-of-the-Envelope Estimation (BoE)
This system is not QPS-heavy on its control plane; it is fan-out heavy on injection and read-heavy on metrics evaluation. Let me ground it.
Fleet and experiments:
Services: ~3,000
Hosts / pods: ~50,000
Teams: ~300
Experiments defined per day: ~2,000 (mostly scheduled + CI-gated)
Peak concurrent experiments: ~1,000-3,000
Avg pods touched per experiment: ~20 (blast radius keeps this small)
Peak pods under active injection: 3,000 experiments * 20 ≈ 60,000 pod-faults
(overlapping; a pod can be in >1 experiment only if guardrails allow,
usually they do not - so realistically bounded by the 50K fleet)
Injection agents (the data plane):
One lightweight agent per host/pod (DaemonSet on Kubernetes).
50,000 agents, each idle most of the time.
Each agent holds the local fault state for experiments touching its pod.
Heartbeat to control plane: every ~1-2s (this doubles as the dead-man's-switch;
see deep dive). 50,000 agents / 2s ≈ 25,000 heartbeats/sec. Small, fixed.
Metric evaluation (the abort loop) - this is the hot read path:
Each running experiment defines ~3-5 abort conditions (error rate, p99, saturation).
3,000 experiments * 4 conditions = ~12,000 metric queries in flight.
Evaluate each condition every ~1s (we need second-level abort).
-> ~12,000 metric evaluations/sec sustained.
Each evaluation reads a short recent window (last 30-60s) of a time series,
or better, consumes a pushed metric stream. Pull-per-second at 12K/sec hammers
the metrics store; this pushes us to a streaming / local-eval design. (Deep dive.)
Control-plane writes:
Experiment create/update: ~2,000/day ≈ negligible (<1/sec avg, bursty)
State transitions + audit events: a few per experiment lifecycle, ~10K/day
Live metric snapshots for the UI: sampled, not every tick
Storage:
Experiment definitions: ~2K/day * ~4 KB ≈ 8 MB/day -> ~3 GB/year. Tiny.
Run reports + metric timelines: each run stores a downsampled metric series,
say ~200 KB/run. 2K/day * 200 KB = 400 MB/day ≈ 150 GB/year. Modest.
Audit log (immutable): append-only, ~10K events/day * 1 KB ≈ 10 MB/day.
Bandwidth:
Control plane: trivial (KB-scale messages, 25K heartbeats/sec of ~200 bytes
≈ 5 MB/sec aggregate). Nothing.
The real "bandwidth" cost is metric evaluation load on the observability system,
which is why we move evaluation to the edge rather than centralizing it.
The numbers say the interesting problems are not throughput. They are: (1) a fan-out injection plane that reliably sets and reliably reverts fault state on tens of thousands of agents, (2) a 12K/sec metric evaluation loop that must be fast enough to abort in seconds without melting the metrics backend, and (3) a fail-safe abort architecture where the stopping mechanism survives the very failures it injects. Everything below serves those three.
High-Level Design (HLD)
The platform splits into a control plane (defines experiments, orchestrates, is the source of truth) and a data plane (agents on every host that actually inject faults and evaluate abort conditions locally). The single most important architectural decision is that abort authority lives in the data plane, not the control plane. The control plane starts experiments and can command aborts, but it cannot be the only thing that can stop one. Each agent independently enforces a lease and local abort rules, so a network partition or a dead control plane results in experiments stopping, not continuing.
┌───────────────────────────────────────────────────────────────────────┐
│ Users: engineers (UI / CLI / API), CI pipelines, schedulers │
└───────────────────────────────┬───────────────────────────────────────┘
│ REST/gRPC (authenticated, RBAC)
▼
┌───────────────────────────────────────────────────────────────────────┐
│ CONTROL PLANE │
│ │
│ ┌──────────────┐ ┌───────────────┐ ┌──────────────────────────┐ │
│ │ Experiment │ │ Scheduler & │ │ Guardrail / Policy │ │
│ │ API + Store │◄─►│ Orchestrator │◄─►│ Engine (blast radius cap,│ │
│ │ (Postgres) │ │ (state m/c) │ │ allowlist, approvals, │ │
│ └──────────────┘ └──────┬────────┘ │ global kill switch) │ │
│ ▲ │ └──────────────────────────┘ │
│ │ │ issue lease + fault spec │
│ ┌──────┴───────┐ ┌──────▼─────────────────────────────────────────┐ │
│ │ Audit Log │ │ Abort Controller (central safety net): │ │
│ │ (append-only)│ │ watches global/aggregate metrics, can command │ │
│ └──────────────┘ │ abort of any experiment; also detects dead │ │
│ │ agents and marks experiments failed-safe │ │
│ └──────┬──────────────────────────────────────────┘ │
└────────────────────────────┼────────────────────────────────────────────┘
│ lease (TTL) + fault spec + abort rules
▼ heartbeat + local status (every 1-2s)
┌───────────────────────────────────────────────────────────────────────┐
│ DATA PLANE │
│ per host/pod: ┌──────────────────────────────────────────────┐ │
│ │ CHAOS AGENT (DaemonSet / sidecar) │ │
│ │ - holds active fault state + lease │ │
│ │ - injects via: tc/netem, iptables, eBPF, │ │
│ │ service-mesh (Envoy) filters, k8s API │ │
│ │ - LOCAL abort evaluator: reads nearby │ │
│ │ metrics, enforces thresholds + lease TTL │ │
│ │ - reverts faults on: abort cmd, threshold, │ │
│ │ lease expiry, or process restart │ │
│ └───────────────┬──────────────────────────────┘ │
└───────────────────────────────────┼─────────────────────────────────────┘
│ reads
▼
┌───────────────────────────────────────────────────────────────────────┐
│ OBSERVABILITY: metrics (Prometheus/TSDB), streaming metric bus, │
│ tracing, logs. Both the agent (local eval) and the central Abort │
│ Controller (aggregate eval) read from here. │
└───────────────────────────────────────────────────────────────────────┘
Request flow for a single experiment, end to end:
- Define. Engineer (or CI, or scheduler) POSTs an experiment spec: steady-state hypothesis, target selector, fault type + params, blast radius, duration, abort conditions. The Experiment API validates and stores it as
scheduled. - Admit. The Orchestrator picks it up. The Guardrail Engine checks: is the target on the allowlist? Is the current time in an allowed window? Does adding this experiment’s blast radius keep the org under the global simultaneous-blast-radius cap? Is approval required and present? Is the global kill switch off? If any check fails, the experiment is rejected or queued; it never silently runs.
- Record steady state. Before injecting, the Orchestrator samples the abort-condition metrics for the target to confirm the system is currently healthy. You never start chaos on an already-sick system - that corrupts the result and is dangerous. If steady state is not met, abort before starting.
- Resolve blast radius. The target selector resolves to a concrete set of agents/pods (e.g. “5% of
checkout-svcpods inus-east-1b” -> a specific list of 12 pods). The Orchestrator issues each selected agent a lease: a fault spec, the abort rules (local thresholds), and a short TTL (say 10s) it must renew. - Inject. Each agent applies the fault locally (adds latency via
tc netem, drops packets viaiptables, injects 5xx via the Envoy sidecar filter, or terminates the pod via the k8s API) and reportsinjected. The experiment moves torunning. - Watch (the control loop). Two loops run in parallel. Each agent’s local abort evaluator reads nearby metrics every ~1s and checks its local thresholds. The central Abort Controller watches aggregate and global health (things no single agent can see, like total checkout success rate). The agent also renews its lease each heartbeat.
- Abort or complete. The experiment ends one of several ways: (a) the scheduled duration elapses cleanly ->
completed; (b) an agent’s local threshold is crossed -> that agent reverts immediately and signals the controller, which aborts the whole experiment; (c) the central controller sees aggregate threshold crossed -> commands all agents to revert; (d) the lease expires (agent lost contact with control plane, or control plane died) -> agent reverts on its own. Every path ends in faults reverted. - Report. The Orchestrator writes the run report: hypothesis, injected faults, metric timeline, outcome (pass / fail / aborted and why), and emits audit events. Weaknesses discovered become tickets for the owning team.
The two loops in step 6 are the heart of the system, and step 7(d) - the lease expiry path - is what makes it safe to run in production. The deep dives are about making those correct and fast.
Component Deep Dive
1. Fault injection: from kill -9 to a reversible, mesh-aware fault plane
Naive approach. The first version everyone writes: a central service with a list of hosts; to inject latency, it SSHes to the box and runs tc qdisc add dev eth0 root netem delay 200ms. To kill a pod, it calls the k8s API and deletes it. To abort, it SSHes back and runs tc qdisc del.
Where it breaks.
- Reversal is not guaranteed. If the SSH to revert fails (network blip - which your own latency injection may have caused), the fault is stuck on. The central service has no way to force revert, and the box stays degraded. This is the cardinal sin: an injected fault that outlives the experiment.
- No local authority. Abort depends entirely on the central service reaching the box. Inject a network partition and you have severed your own abort path. You cannot stop the experiment that broke the network.
- Coarse blast radius.
tc netemoneth0hits all traffic on the host, not “5% of requests to checkout.” You wanted to degrade one dependency; you degraded everything, including the agent’s own metrics reporting. - No safety on crash. If the host reboots with the qdisc rule persisted, or the central service forgets the experiment, the fault leaks.
The evolved design: a local agent with reversible, scoped faults and a lease.
Put a lightweight chaos agent on every host (a Kubernetes DaemonSet, so one per node, or a sidecar for per-pod granularity). The agent, not a central SSH loop, owns the fault. This changes everything:
- Reversibility is local and idempotent. The agent records the exact fault it applied (the precise
tc/iptablesrule, the mesh filter config) in local durable state. Revert is a single local operation it can always perform, even fully partitioned from the control plane. On process restart, the agent’s first action is to reconcile: if its durable state says “fault X active” but no valid lease exists, it reverts X. Faults cannot leak. - The lease is the safety primitive. The control plane issues a lease with a short TTL (e.g. 10s). The agent must renew it via heartbeat. If the agent cannot renew - control plane down, network partitioned, the agent itself wedged - the lease expires and the agent reverts the fault automatically. This is a dead-man’s switch. The default state of the system is “no chaos”; chaos requires a continuously renewed lease to persist. Sever any part of the control path and chaos stops, which is exactly the fail-safe property we want.
- Scoped injection via the right mechanism. The agent chooses the injection mechanism to match the requested scope:
| Fault | Mechanism | Scoping |
|---|---|---|
| Latency on a dependency | Service-mesh (Envoy) fault filter, or eBPF | Per-route, per-% of requests to that upstream |
| Error / 5xx injection | Envoy fault filter / app-level hook | Per-route, per-% of calls |
| Packet loss / partition | tc netem loss, iptables DROP on specific CIDRs/ports | Scoped to specific peer services, not all traffic |
| CPU / memory / disk stress | stress-ng in a cgroup the agent controls | Bounded by cgroup limits; cannot starve the agent itself |
| Pod / instance termination | Kubernetes API delete, respecting PodDisruptionBudgets | A fixed count/% of replicas |
The mesh-based injection is what gives real blast-radius control: “add 300ms to 10% of requests from checkout to payments” is a one-line Envoy filter, far more surgical than a host-wide qdisc. For the kill case, respecting PodDisruptionBudgets means Kubernetes itself refuses to let chaos take a service below its minimum healthy count - a second, independent guardrail.
- The agent protects itself. Resource-stress faults run in a separate cgroup so they cannot starve the agent’s own evaluation loop or its heartbeat. If the agent dies, the lease expires and the fault reverts anyway. The agent’s own control traffic (heartbeat, metric reads) is exempted from any network fault it injects, so injecting packet loss never blinds the thing that must observe and abort.
2. The abort control loop: aborting in seconds without melting the metrics store
This is the hard part the whole design exists for. We must detect that an experiment is hurting real users and revert all faults in single-digit seconds.
Naive approach. A central loop: for each running experiment, every second, query the metrics store (error_rate{service="checkout"} over last 60s), compare to the threshold, and if exceeded, loop over the agents and tell them to revert.
Where it breaks.
- Metrics-store overload. 3,000 experiments * 4 conditions * 1 query/sec = 12,000 PromQL-style range queries per second, each scanning a recent window. A Prometheus setup falls over; you have turned your safety system into a load test against your observability system, degrading the very metrics you need to make the abort decision. The abort loop starves itself.
- Query latency eats the budget. If each central query takes 500ms-2s under load, and you then have to round-trip revert commands to 20 agents, you have blown the 3-5s abort budget before you started.
- The central controller is a single point of failure for safety. If it is down or partitioned, nothing aborts. Worse, a chaos experiment can cause the condition that takes it down.
- Metric lag. Scrape-based metrics are often 15-30s behind reality. Deciding to abort on data that is 30s stale means you let 30s of damage through and may abort after the damage already peaked.
The evolved design: a two-tier evaluation with local-first abort and a central aggregate net.
Split evaluation by what can only be seen where.
Tier 1 - local evaluation at the agent (fast path, the common case). Most abort conditions are observable locally or near-locally: the error rate of the injected pod’s own responses, its latency, its saturation. The agent already sits next to these signals. Instead of the central loop polling the TSDB, the agent evaluates its local thresholds directly against:
- metrics it can read from the local Envoy sidecar / app
/metricsendpoint (RED metrics for exactly the routes it is faulting), and - a pushed, pre-aggregated metric stream rather than pull queries. The observability side exposes a lightweight stream (or the agent subscribes to a rollup) of the specific series this experiment cares about, at 1s resolution. The agent compares the latest window to its threshold with no range-query cost.
When a local threshold is crossed, the agent reverts its own fault immediately - no round trip to the control plane needed for the critical revert - and then reports “I aborted locally, reason X” to the controller, which propagates the abort to the experiment’s other agents. The critical action (stop hurting things) happens at the edge in well under a second; the coordination happens after. This is the key latency win: revert first, coordinate second.
Tier 2 - central aggregate evaluation (the net for what no agent can see). Some conditions are genuinely global: “overall checkout success rate across the whole fleet,” “total 5xx seen at the edge load balancer,” “a downstream service three hops away is now erroring.” No single agent sees these. The central Abort Controller evaluates these aggregate conditions, but at manageable cost:
- It subscribes to a streaming aggregate (a handful of pre-computed org-level SLO series updated every 1-5s via a streaming pipeline like a metrics aggregator), not thousands of ad-hoc range queries. The number of series it watches is proportional to the number of distinct global SLOs, not the number of experiments.
- When an aggregate condition breaches, it commands abort of every experiment plausibly contributing (or, for a severe global breach, trips the global kill switch and aborts all running experiments at once).
The dead-man’s switch ties it together. Even if both evaluation tiers somehow miss, the lease TTL is the backstop: an experiment that loses contact with the control plane reverts within the TTL (10s), and the scheduled duration is itself a hard upper bound enforced locally by the agent. There is no single component whose failure leaves chaos running. Abort can be triggered by (a) local threshold, (b) central aggregate threshold, (c) global kill switch, (d) lease expiry, (e) scheduled-duration expiry - and (a), (d), (e) all execute at the agent with no dependency on a healthy control plane.
Numerically: local threshold crossed -> agent detects within its ~1s eval tick -> local revert in <200ms (just removing an Envoy filter / tc rule) -> other agents notified and revert within ~1-2s. Total time-to-full-revert: ~1-3s. The metrics store sees a bounded, pre-aggregated streaming load instead of 12K range queries/sec.
3. Blast radius enforcement: making “5%” actually mean 5%, globally
Naive approach. Each experiment specifies a percentage; the Orchestrator resolves it to pods and injects. Done.
Where it breaks. Blast radius is not a per-experiment property; it is a global property. Three teams each run a “safe” 5% experiment on overlapping dependencies and collectively degrade 15% of a shared downstream, or the same pod gets selected by two experiments and runs with compounded faults. Percentages also lie: 5% of a 4-replica service is 0 or 1 pod (rounding), and killing 1 of 4 is 25%, not 5%. And “5% of requests” is meaningless if traffic is uneven across pods.
The evolved design.
- A global blast-radius budget, enforced by the Guardrail Engine at admission. The org has a cap on total simultaneous disruption (e.g. “no more than X% of any single service, and no more than N concurrent experiments touching shared tier-0 dependencies”). Admission is transactional: an experiment is admitted only if, atomically, adding its resolved blast radius keeps every affected service and shared dependency under its cap. This requires a consistent view of currently-running experiments - hence the single-source-of-truth state store and a serialized admission step (below).
- Resolve to concrete targets and sanity-check the arithmetic. “5% of checkout” resolves to a concrete pod list; if that rounds to 0, reject with a clear message; if the service has too few replicas for a safe percentage, require explicit override. Killing respects PodDisruptionBudgets so the cluster scheduler independently refuses to breach minimum healthy counts.
- Mutual exclusion on targets. By default a pod/route can be in at most one active experiment; the admission step holds a short lock over the target set so two experiments cannot both claim the same pods. Overlap is only allowed with explicit intent (a “compound failure” experiment that is itself a single bounded unit).
- Progressive blast radius (canary-style chaos). For high-risk experiments, don’t start at the full 5%. Start at one pod / 1% of traffic, hold, verify steady state still holds, then ramp. If any ramp step breaches, abort. This bounds worst-case damage to the smallest increment.
- Start narrow in the fault domain too. Default to staging; promote to production only with approval; within production, default to a single availability zone and a non-peak window unless overridden. The platform’s defaults are conservative; widening blast radius requires explicit, audited action.
API Design & Data Schema
The control plane is a straightforward CRUD + orchestration API; the interesting constraints are the state machine and the admission transaction.
API (REST/gRPC, authenticated, RBAC-scoped):
POST /v1/experiments
Body: {
name, description,
target: { service, region?, zone?, selector: {labels}, scope: "staging"|"prod" },
fault: { type: "latency"|"error"|"packet_loss"|"stress"|"pod_kill",
params: { latency_ms?, error_rate_pct?, loss_pct?, ... } },
blast_radius: { kind: "percent"|"count", value: 5, ramp?: [1,5,10] },
hypothesis: { steady_state: [ {metric, comparator, value} ] },
abort: { conditions: [ {metric, comparator, threshold, window_s} ],
local: [...], aggregate: [...] },
duration_s: 300,
schedule?: { cron | "now" }
}
-> 201 { experiment_id, state: "scheduled" }
(Guardrail checks run here or at admission; may return 409 if blast cap exceeded)
GET /v1/experiments/{id} -> full spec + current state + live metrics snapshot
POST /v1/experiments/{id}/start -> admit + run (if not auto-scheduled)
POST /v1/experiments/{id}/abort -> manual abort (operator)
GET /v1/experiments/{id}/report -> post-run report: timeline, outcome, weaknesses
GET /v1/experiments?state=running -> list (for dashboards)
POST /v1/kill-switch { scope: "global"|"service:X", enabled: true }
-> immediately aborts all matching running experiments and blocks new ones
# Data-plane (agent <-> control plane), gRPC, mutually authenticated:
rpc Heartbeat(AgentStatus) returns (LeaseUpdate) # every 1-2s; renews leases,
# carries local abort reports,
# returns abort commands
rpc FetchFaultSpec(LeaseId) returns (FaultSpec) # on lease grant
Data stores. The source of truth for experiment definitions and state is a relational store (Postgres) - this is the right call because the data is low-volume, highly relational (experiments -> targets -> runs -> audit), and, critically, the admission step needs transactional, strongly-consistent guarantees to enforce the global blast-radius budget and target mutual exclusion. A SELECT ... FOR UPDATE over the relevant counters plus a serializable transaction is exactly how you prevent two experiments from both admitting past the cap. NoSQL’s eventual consistency would let two concurrent admissions each see “budget available” and both proceed - the classic double-spend, except the currency is production stability.
Run reports with downsampled metric timelines are high-write, append-mostly, and queried by range - those go to a time-series or columnar store (or object storage for the raw timeline blobs, with Postgres holding the report metadata). The audit log is append-only and immutable (compliance), ideally a separate write-once store.
-- Source of truth: strongly consistent, transactional admission.
CREATE TABLE experiments (
id UUID PRIMARY KEY,
name TEXT NOT NULL,
owner_id UUID NOT NULL,
scope TEXT NOT NULL, -- 'staging' | 'prod'
spec JSONB NOT NULL, -- target, fault, blast_radius, abort
state TEXT NOT NULL, -- scheduled|admitted|running|completed|aborted|rejected
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
started_at TIMESTAMPTZ,
ended_at TIMESTAMPTZ,
abort_reason TEXT, -- null unless aborted
CHECK (state IN ('scheduled','admitted','running','completed','aborted','rejected'))
);
CREATE INDEX idx_exp_state ON experiments (state) WHERE state = 'running';
CREATE INDEX idx_exp_owner ON experiments (owner_id, created_at DESC);
-- Resolved targets per running experiment: drives mutual exclusion + blast budget.
CREATE TABLE experiment_targets (
experiment_id UUID REFERENCES experiments(id),
service TEXT NOT NULL,
pod_id TEXT NOT NULL,
zone TEXT,
lease_id UUID NOT NULL,
lease_expires_at TIMESTAMPTZ NOT NULL, -- dead-man's switch deadline
fault_applied JSONB, -- exact revert instructions
PRIMARY KEY (experiment_id, pod_id),
UNIQUE (pod_id) -- enforces: a pod in at most one experiment
);
CREATE INDEX idx_tgt_service ON experiment_targets (service); -- blast budget sums
-- Live blast-radius accounting, kept consistent with targets in the same txn.
CREATE TABLE blast_budget (
service TEXT PRIMARY KEY,
total_replicas INT NOT NULL,
disrupted_count INT NOT NULL DEFAULT 0, -- updated transactionally on admit/end
max_pct INT NOT NULL -- cap, e.g. 10
);
-- Append-only audit (immutable).
CREATE TABLE audit_log (
id BIGSERIAL PRIMARY KEY,
experiment_id UUID,
actor TEXT NOT NULL,
action TEXT NOT NULL, -- created|admitted|injected|aborted|reverted|kill_switch
detail JSONB,
at TIMESTAMPTZ NOT NULL DEFAULT now()
);
The UNIQUE (pod_id) on experiment_targets is doing real work: it is the database enforcing target mutual exclusion. The admission transaction inserts target rows and increments blast_budget.disrupted_count, checking disrupted_count <= total_replicas * max_pct / 100 in the same serializable transaction. If two experiments race, one commits and the other hits the unique constraint or the budget check and is rejected. The lease_expires_at column makes the dead-man’s switch durable: a sweeper can find and force-revert any lease whose deadline has passed and whose agent went silent.
Run reports and metric timelines (schematically, in the TSDB/object store):
report:{experiment_id} -> {
hypothesis, outcome: "pass"|"fail"|"aborted",
abort_reason, injected_faults[],
timeline: [ {t, error_rate, p99_ms, saturation, injected:bool} ], # downsampled
weaknesses[] # derived findings -> tickets
}
Bottlenecks & Scaling
Where it breaks first: the metric evaluation load. A naive central poll loop is the first thing to melt the system, as covered. The fix is the two-tier design: push local evaluation to the agent against pushed/streamed metrics, and keep the central controller watching only a small, fixed set of pre-aggregated global SLO series. Evaluation cost then scales with distinct SLOs, not experiments x conditions x poll frequency. This also removes the metrics store as a single point of failure on the abort path - the critical local abort needs no central query at all.
Single point of failure on the control plane. The control plane is the source of truth, so it must be HA: Postgres with synchronous replication and automatic failover, stateless API/Orchestrator replicas behind a load balancer. But the real protection is architectural: the abort path does not depend on the control plane being up. The lease dead-man’s switch means a total control-plane outage causes all running experiments to self-abort within one TTL. That is the correct failure mode - losing the brain stops chaos rather than letting it run blind.
Sharding. The control plane is low-volume and does not need sharding for load. If the fleet is enormous, shard the agent/heartbeat plane by region or cluster: a regional orchestrator handles the agents in its region, so 50K heartbeats/sec is split across regions and a regional failure is contained. The natural shard key is region/cluster, because blast radius and latency-to-abort are both regional concerns - you want the agent, its orchestrator, and its metrics in the same failure domain so the abort loop stays fast and local even when a region is partitioned from the rest.
Replication and consistency. Experiment state and the blast-radius budget are strongly consistent (single Postgres primary, serializable admission transaction) because correctness here is a safety property, not a performance one. Metric reads driving abort are deliberately eventually-consistent and recent - we use short windows and accept that we might act on data that is 1-2s old, which is fine because the fault itself is the thing generating that data in near real time. We never try to make abort decisions exactly-once or transactional; we make them fast and fail-safe.
Async processing. Report generation, weakness analysis, and ticket creation happen off the hot path, after the run, from the durable timeline. The hot path (inject, evaluate, revert, heartbeat) is kept lean. Audit events are written synchronously (they are a compliance requirement) but to an append-only store that is cheap to write.
Hot keys / hot targets. A shared tier-0 dependency (auth, a core database proxy) is a hot target: many experiments may want to fault services that depend on it, compounding real-user impact. The blast-budget table keys on service and the global budget caps total disruption on any shared dependency; tier-0 dependencies get a lower cap and mandatory approval. The Guardrail Engine is the chokepoint that prevents a hot shared dependency from being collectively overwhelmed by independently-“safe” experiments.
The failure mode that must never happen: a stuck fault. Every layer defends against it. The agent stores exact revert instructions durably and reconciles on restart; the lease expires without renewal; a central sweeper force-reverts any lease past its deadline whose agent is silent; lease_expires_at is persisted so even a full control-plane restart can find and clean up orphaned faults. Defense in depth, because a leaked production fault is the one outcome that turns a reliability tool into an outage generator.
Wrap-Up
The trade-offs that define this design:
- Abort authority at the edge, not the center. We accept a more complex agent (local metric evaluation, durable fault state, lease renewal) in exchange for the one property that makes production chaos acceptable: the stopping mechanism survives the failures being injected. Centralizing abort would be simpler and would be wrong.
- Fail-safe over fail-operational. The default state is no chaos; chaos requires a continuously renewed lease to persist. We bias every ambiguous case toward aborting, accepting occasional needless re-runs to never miss a real abort.
- Strong consistency where it is a safety property (admission, blast budget, experiment state), eventual consistency where speed matters (metric reads). Postgres and serializable admission for the former; pushed/streamed local evaluation for the latter.
- Blast radius as a global, transactionally-enforced budget, not a per-experiment honor system, with progressive ramp, target mutual exclusion, PodDisruptionBudget backstops, and conservative defaults (staging first, one zone, off-peak, approvals for prod).
One-line summary: a control plane that is the strongly-consistent source of truth for experiment definitions and blast-radius budgets, and a data plane of per-host agents that inject reversible, scoped faults under a short-lived lease and evaluate abort conditions locally, so that any experiment reverts in single-digit seconds the moment it crosses a reliability threshold - or the moment it loses contact with the control plane at all.
Comments