Sub topic 16
Testing with Failure Injection and Operating the Cluster
This chapter assumes you know the pieces built in earlier chapters: quorums (R + W > N), sloppy quorums with hinted handoff, read repair, Merkle-tree anti-entropy, gossip-based failure detection, and the WAL and SSTable storage engine. Here we ask whether the assembled system keeps its promises when things break, and how to run it afterward.
Why ordinary tests are not enough
Unit tests show that each component works when everything else works. A distributed store fails in the gaps between components, for example when a node crashes after the WAL write but before the acknowledgment, or when a partition heals while hints are still queued. These interleavings almost never occur in a healthy test environment, so you have to cause them on purpose.
Failure injection means deliberately introducing faults while a workload runs and checking that the system's guarantees still hold. The method has four steps:
- Write down the guarantee as an invariant. Example: "Any write acknowledged at W=2 is visible to every successful read at R=2."
- Run a workload and record every operation, its start and end time, and its result.
- Inject faults.
- Check the recorded history against the invariant.
Fault classes to cover
| Fault | How to inject it | What it exercises |
|---|---|---|
| Process crash (kill -9) | Kill the node at a random point | WAL replay, memtable recovery |
| Crash mid-write | Kill after a partial WAL append | Checksums, truncated-tail handling |
| Network partition | Firewall rules between node groups | Quorum behavior, sloppy quorums, hint creation |
| Slow node | Add latency or throttle disk I/O | Timeouts, failure-detector accuracy, tail latency |
| Packet loss and reordering | Drop or delay messages | Retries, idempotent writes, version comparison |
| Clock skew | Shift one node's clock | Last-write-wins conflicts, TTL, tombstone expiry |
| Disk full or corrupt | Fill the volume or flip bits in an SSTable | Error handling, checksum detection, repair |
| Node replacement | Wipe a node and rejoin it | Streaming, bootstrap, anti-entropy |
Test combinations as well as single faults. The worst bugs tend to need two faults, such as a crash during a partition.
A deterministic fault-injection harness
You can test replication logic in-process before touching real networks. The simulation below has three replicas, drops 20% of messages at random, and applies random crashes, restarts, and partitions. After every successful read it checks the invariant above. Because the random generators are seeded, a failure can be replayed exactly.
import random
class Replica:
def __init__(self, name):
self.name = name
self.up = True
self.data = {} # key -> (version, value)
class Cluster:
def __init__(self, names, w, r, seed):
self.replicas = {n: Replica(n) for n in names}
self.w, self.r = w, r
self.rng = random.Random(seed)
self.version = 0
self.cut = set() # replicas unreachable from the coordinator
def reachable(self):
return [
rep for rep in self.replicas.values()
if rep.up and rep.name not in self.cut
]
def put(self, key, value):
self.version += 1
acks = 0
for rep in self.reachable():
if self.rng.random() < 0.2: # message lost
continue
rep.data[key] = (self.version, value)
acks += 1
return acks >= self.w
def get(self, key):
responses = [
rep.data.get(key, (0, None))
for rep in self.reachable()
if self.rng.random() >= 0.2
]
if len(responses) < self.r:
return None # read quorum not reached
return max(responses)
def run(w, r, seed, steps=2000):
cluster = Cluster(["a", "b", "c"], w, r, seed)
rng = random.Random(seed + 1)
last_acked = 0
violations = 0
for _ in range(steps):
action = rng.choice(["put", "get", "crash", "restart", "cut", "heal"])
name = rng.choice(list(cluster.replicas))
if action == "crash":
cluster.replicas[name].up = False
elif action == "restart":
cluster.replicas[name].up = True # data survives: WAL replay
elif action == "cut":
cluster.cut.add(name)
elif action == "heal":
cluster.cut.discard(name)
elif action == "put":
if cluster.put("k", f"v{cluster.version + 1}"):
last_acked = cluster.version
else:
got = cluster.get("k")
if got is not None and got[0] < last_acked:
violations += 1 # stale read after an acknowledged write
return violations
print("W=2, R=2:", sum(run(2, 2, s) for s in range(20)))
print("W=1, R=1:", sum(run(1, 1, s) for s in range(20)))With W=2 and R=2 the count is 0, because every read quorum overlaps every acknowledged write quorum. With W=1 and R=1 the count is above zero, because a write acknowledged by one replica can be missed by a read that reaches another. The harness finds the violation, and the seed lets you replay it.
This model has limits. It uses a single writer, never recovers lost data, and does not check linearizability, so passing it proves little about the real system. Its value is the workflow: generate random faults, check an invariant, and keep the seed.
The test loop
Two kinds of check are needed:
- History checks validate what clients saw during the faults. Linearizability checkers such as Knossos or Porcupine take a recorded history and decide whether any valid ordering explains it. A leaderless store with R + W > N will fail a linearizability check under concurrent writes. Check against the model the store actually promises, not a stronger one.
- Convergence checks run after faults heal. Once hints are delivered and anti-entropy has run, all replicas of each key should hold the same data or the same set of siblings. If they do not, a repair path is broken.
Run these with many seeds, then repeat on a real cluster using tools such as Jepsen, tc netem, iptables rules, or a chaos tool. Begin with small clusters and short runs. Log every injected fault with a timestamp so you can line it up with client errors.
Operating the cluster
What to monitor
- Latency percentiles per operation: p50 hides problems. Watch p99 and p99.9, since a coordinator waiting for the slowest of R or W replicas feels every slow node.
- Hint queue size and age: a growing queue means a node has been down too long or is not draining.
- Repair backlog: the time since each range last finished anti-entropy.
- Compaction pending bytes and SSTable count per read: a growing count predicts read latency spikes.
- Disk usage with headroom: compaction can temporarily need extra space, so alert well before full.
- Gossip view disagreement: nodes that disagree about who is alive suggest partitions or an overloaded failure detector.
- Stale or sibling rates: a rising sibling count means conflicting concurrent writes that clients are not resolving.
Membership changes
Adding a node follows a fixed order. It joins the ring, receives its virtual-node ranges, streams the data for those ranges from current owners, and only then serves reads. Streaming consumes disk and network, so throttle it and add one node at a time. Removing a node works in reverse: decommission it so its data streams to the new owners before it leaves. A node that is simply killed leaves ranges under-replicated until repair restores the replication factor.
Rolling upgrades and backups
Upgrade one node at a time. Drain it, restart it, wait for it to rejoin and for hints to clear, then move on. Keep the version of the on-disk format and the wire protocol compatible across adjacent releases, or a mixed-version cluster will fail mid-upgrade. Take backups as snapshots of immutable SSTables, which are cheap because files never change after being written. Test restoring, because an untested backup is only a guess.
Capacity and incident practice
Plan so that losing one node, or one zone, still leaves enough disk and CPU for the remaining nodes to absorb its load and stay within the replication factor. Write runbooks for the common events: node down, disk full, slow node, and a failed upgrade. Rehearse them in game days where you inject a fault in a staging cluster and have the on-call engineer respond without prior notice.
Summary of practices
- State each guarantee as a checkable invariant before testing.
- Use seeded random fault schedules so failures replay.
- Check histories during faults and convergence after faults.
- Test fault combinations, not only single faults.
- Monitor tail latency, hints, repair age, and compaction.
- Change membership one node at a time, and repair within the tombstone window.
Exercise
In the harness, change the cluster to N=3 with W=2 and R=1. Predict whether the stale-read count will be zero, and explain why.
Show answer
It will not be zero. R + W = 3, which is not greater than N = 3, so a read quorum of one replica can reach a replica that missed the latest acknowledged write. The harness would report violations for some seeds.
Exercise
A test passes with 50 seeds, but in production a deleted key sometimes reappears days later. Name one fault scenario your test is missing and the production setting you should check.
Show answer
The test never lets a replica miss a delete and stay out of repair past the tombstone retention period. Add a scenario that keeps a replica down or partitioned longer than that period, then brings it back. In production, check that the repair interval is shorter than the tombstone retention time.