Sub topic 11
Testing Fallbacks with Fault Injection
Prerequisites and scope
This chapter assumes you have read the earlier chapters on timeouts, retries, circuit breakers, and fallback strategies. You should also be able to read Python and write a basic pytest test. The examples reuse get_recommendations, call_with_retry, and CircuitBreaker from those chapters. Save them together in a file named degradation.py.
By the end you will be able to:
- Explain why fallback code needs deliberate failure tests.
- Build a small fault injector that simulates errors, slowness, and partial failure.
- Write tests that confirm cached, default, and degraded-flag behavior.
- Test retry and circuit breaker behavior without real sleeping.
- Plan fault experiments beyond unit tests, including staging and production.
Why fallbacks need their own tests
A fallback is code that runs only when something else is broken. In normal operation it never executes, so ordinary tests and ordinary traffic never exercise it. It can sit unused for months and then fail at the worst moment.
Typical ways an untested fallback breaks:
- It raises an exception because it assumes data that is missing (for example, a cache entry that was never written).
- It catches too few exception types, so an unexpected error escapes.
- It calls the same failing dependency, just through a different code path.
- It works, but nothing records that it ran, so nobody knows the service is degraded.
- It is correct for one failure and wrong for another. A fast error and a hung connection are different faults and often need different handling.
Fault injection means deliberately causing the failure you designed for, then checking that the system behaves as intended. The goal is to turn "we think the fallback works" into a repeatable check.
What to inject
Dependencies fail in several ways, and each one tests a different piece of your design. Start with the fault types in this table.
| Fault | What it simulates | What it tests |
|---|---|---|
| Immediate error | Connection refused, HTTP 503 | Exception handling, fallback selection |
| Added latency | Overloaded or hung dependency | Timeouts, thread or connection exhaustion |
| Intermittent errors | A fraction of calls fail | Retries, breaker thresholds |
| Total outage | Every call fails for a period | Breaker opening, cached or default data |
| Wrong data | Empty or malformed response | Input validation, safe defaults |
| Recovery | Failures stop | Breaker closing, return to normal mode |
The last row matters as much as the others. A system that degrades correctly but never returns to full function is still broken.
A small fault injector
The injector below wraps any dependency call. It can raise an error, simulate latency, or fail only a fraction of calls. It uses a seeded random generator so a "30% of calls fail" test gives the same result on every run.
For latency, the injector does not actually sleep. If the simulated latency is longer than the timeout the caller passed, it raises TimeoutError immediately. This keeps tests fast while still exercising the timeout path.
# fault_injection.py
import random
class FaultInjector:
"""Wrap a dependency call and make it fail on demand."""
def __init__(self, fn, error=None, latency=0.0, rate=1.0, seed=0):
self.fn = fn
self.error = error # exception class to raise, or None
self.latency = latency # simulated seconds of delay
self.rate = rate # fraction of calls that are faulted
self.rng = random.Random(seed)
self.calls = 0
self.faults = 0
def __call__(self, *args, **kwargs):
self.calls += 1
if self.rng.random() < self.rate:
self.faults += 1
if self.error is not None:
raise self.error("injected fault")
timeout = kwargs.get("timeout")
if timeout is not None and self.latency > timeout:
raise TimeoutError(f"simulated {self.latency}s latency")
return self.fn(*args, **kwargs)The calls and faults counters are useful. They let a test prove how many times the dependency was actually contacted, which is the only way to confirm that a circuit breaker stopped calling it.
Setting rate=0.0 makes the injector a pass-through, and the counters still work. You can flip the rate during a test to simulate an outage starting or ending.
Testing the fallback path
Start with the fallback function from earlier. Each test below encodes one sentence of the design: what the user should see when the dependency fails.
# test_degradation.py
import pytest
import degradation
from degradation import CircuitBreaker, call_with_retry, get_recommendations
from fault_injection import FaultInjector
def healthy_fetch(user_id, timeout):
return ["a", "b"]
@pytest.fixture(autouse=True)
def clear_cache():
degradation._cache.clear()
yield
degradation._cache.clear()
def test_healthy_path_is_not_degraded():
fetch = FaultInjector(healthy_fetch, rate=0.0)
result = get_recommendations("u1", fetch)
assert result == {"items": ["a", "b"], "degraded": False}
def test_cold_cache_returns_default():
fetch = FaultInjector(healthy_fetch, error=ConnectionError)
result = get_recommendations("u1", fetch)
assert result == {"items": [], "degraded": True, "source": "default"}
def test_warm_cache_serves_stale_data():
get_recommendations("u1", healthy_fetch) # populate the cache
fetch = FaultInjector(healthy_fetch, error=ConnectionError)
result = get_recommendations("u1", fetch)
assert result["items"] == ["a", "b"]
assert result["degraded"] is True
assert result["source"] == "cache"
def test_slow_dependency_is_cut_off():
fetch = FaultInjector(healthy_fetch, latency=5.0)
result = get_recommendations("u1", fetch, timeout=0.5)
assert result["degraded"] is True
def test_unexpected_error_is_not_swallowed():
fetch = FaultInjector(healthy_fetch, error=ValueError)
with pytest.raises(ValueError):
get_recommendations("u1", fetch)Run them with:
pip install pytest
pytest -qThe autouse fixture clears the module-level cache before and after each test. Without it, a test that fills the cache would change the result of a later test that expects a cold cache, and the suite would depend on test order.
The last test records a design decision. get_recommendations catches only TimeoutError and ConnectionError, so a ValueError (probably a bug) propagates instead of being hidden by a fallback. You may decide the opposite for your service. Either way, the test makes the choice explicit and guards it against accidental change.
Testing retries and circuit breakers
Retries and breakers involve time: sleeping between attempts and waiting out a cool-down. Tests must not actually wait. Replace the clock-dependent part, or move the state forward by hand.
For retries, replace time.sleep with a function that records the delay it was asked to wait. Then check both the number of attempts and the bound on each delay. Because jitter is random, test the bound (delay <= min(cap, base * 2 ** attempt)) instead of an exact value.
For the breaker, the sketch stores opened_at as a plain attribute. A test can move it back in time to simulate the cool-down passing.
def test_retry_gives_up_and_delays_stay_bounded(monkeypatch):
delays = []
monkeypatch.setattr(degradation.time, "sleep", delays.append)
fn = FaultInjector(lambda: "ok", error=TimeoutError)
with pytest.raises(TimeoutError):
call_with_retry(fn, attempts=3, base=0.1, cap=2.0)
assert fn.calls == 3
assert len(delays) == 2 # no sleep after the last attempt
assert delays[0] <= 0.1
assert delays[1] <= 0.2
def test_retry_succeeds_when_fault_clears(monkeypatch):
monkeypatch.setattr(degradation.time, "sleep", lambda s: None)
outcomes = iter([True, True, False]) # fail, fail, then succeed
fn = FaultInjector(lambda: "ok", error=ConnectionError)
original_random = fn.rng.random
fn.rng.random = lambda: 0.0 if next(outcomes) else 1.0
assert call_with_retry(fn, attempts=3) == "ok"
assert fn.calls == 3
fn.rng.random = original_random
def test_breaker_opens_then_recovers():
dep = FaultInjector(lambda: "live", error=ConnectionError)
breaker = CircuitBreaker(max_failures=3, reset_after=30.0)
for _ in range(3):
assert breaker.call(dep, lambda: "fallback") == "fallback"
assert dep.calls == 3
for _ in range(10): # breaker is open now
assert breaker.call(dep, lambda: "fallback") == "fallback"
assert dep.calls == 3 # dependency was not contacted
breaker.opened_at -= 31.0 # pretend the cool-down has passed
dep.rate = 0.0 # the dependency has recovered
assert breaker.call(dep, lambda: "fallback") == "live"
assert breaker.opened_at is NoneThe key assertion in the breaker test is dep.calls == 3 after ten more calls. It shows the breaker protects the dependency, which is the reason it exists. A test that only checked the returned value would pass even if the breaker never opened and every call still hit the failing service and fell back.
The experiment loop
Whether you work in a unit test or a staging environment, the process is the same. Treat each experiment as a small scientific test: state what you expect, break one thing, and compare.
Two details in this loop matter in practice:
- Define steady state first. If you do not know the normal error rate and latency, you cannot tell whether an experiment caused a change.
- Inject one fault at a time. If you slow the cache and kill the database together and something breaks, you will not know which fault caused it.
Checking that degraded state is visible
Earlier chapters said degraded behavior must be visible to operators and users. Fault tests are the place to confirm it. In each degradation test, assert on the signals, not only on the response body:
- The response carries the degraded flag, or the user-facing message changes.
- A metric such as
fallback_used_totalincreases by the expected amount. - A log line records which dependency failed and which fallback ran.
- The circuit breaker state, if exposed, shows
openduring the outage andclosedafterward.
If the fallback works but nothing records that it ran, the test should fail. An invisible fallback is how a service runs degraded for weeks without anyone noticing.
Beyond unit tests
Unit tests with an in-process injector are fast and run on every commit. They cannot reveal everything. They do not exercise real network behavior, real connection pools, or interactions between services. Add wider checks as your confidence and tooling grow.
- Integration tests with a fault proxy. Place a network proxy between your service and a real dependency in a test environment. Tools such as Toxiproxy can add latency, drop connections, or cut bandwidth on demand. This tests real timeouts and real client libraries.
- Staging experiments. Run the same faults against a full deployment under realistic load. Many problems appear only under concurrency, such as thread pool exhaustion or a retry storm.
- Game days. Schedule a session where the team deliberately breaks a dependency and watches dashboards, alerts, and runbooks. This tests people and tooling as well as code.
- Production experiments. Teams with mature monitoring inject small, controlled faults in production. Limit the blast radius (a small percentage of traffic, a short duration, an easy way to stop) and get agreement before starting.
Common mistakes
- Mocking the fallback away. If a test replaces the whole function with a mock, the real fallback code never runs. Fake the dependency, not the code under test.
- Testing only the fast error. An immediate
ConnectionErroris easy. A hung connection that exceeds the timeout is the case that exhausts workers, so test it separately. - Forgetting recovery. Always remove the fault and assert that normal behavior returns, including the breaker closing and the degraded flag clearing.
- Real sleeps in tests. A suite that waits 30 seconds for a breaker cool-down will be skipped. Control the clock or the state directly.
- Unseeded randomness. A test that fails 1 time in 50 is worse than no test. Seed the random generator or fix the sequence.
- Asserting on exact jitter values. Jitter is random by design. Assert bounds and counts.
- Testing one layer only. A timeout, retry, and breaker can each pass alone and still interact badly. For example, three retries with a one second timeout on each call can exceed the caller's own deadline. Include at least one test that checks total elapsed time across the combined policy.
Summary
Fallback code runs rarely, so it is the code most likely to be broken when needed. A seeded fault injector lets you simulate errors, slowness, and partial failure in fast tests. Assert on content, counts of dependency calls, and visibility signals, not just the absence of exceptions. Run one fault at a time, compare against a stated expectation, and always verify recovery. Then carry the same loop into integration tests, staging, and carefully scoped production experiments.
Exercise
In test_breaker_opens_then_recovers, the breaker has been open and the cool-down has passed, but the dependency is still down. Write down what a test for this situation should assert about the number of dependency calls, the returned value, and the breaker state.
Show answer
After moving opened_at back by 31 seconds with the injector still failing (rate left at 1.0), one call to breaker.call(dep, fallback) should do three things. It should contact the dependency exactly once (dep.calls goes up by 1), because the call acts as a trial request. It should return the fallback value, because the trial failed. It should leave the breaker open with a fresh opened_at (not None), because the failure count is already at or above max_failures. A further call right afterward should not contact the dependency at all.
Exercise
A teammate writes a test that sets FaultInjector(healthy_fetch, error=ConnectionError) and asserts only that get_recommendations("u1", fetch) does not raise. Name two faults in the fallback behavior that this test would miss and describe the assertion that would catch each.
Show answer
First, it would miss a fallback that returns wrong or empty data. Assert on the full result, for example {"items": [], "degraded": True, "source": "default"} for a cold cache. Second, it would miss a missing degraded signal, where the function returns data with degraded set to False or does not set it at all. Assert result["degraded"] is True, and in a service with metrics, also assert that the fallback counter increased. Asserting on source would also show whether cached or default data was served.
Exercise
Your service retries up to 3 times with a 1 second timeout on each attempt, and the caller of your service gives up after 2 seconds. Describe a fault injection test that would reveal the problem, and what it should assert.
Show answer
Inject latency greater than 1 second on every call (for example 5 seconds with a 1 second timeout) and measure the total time the combined retry policy takes with a controlled clock or with real, short timeouts scaled down proportionally. Three attempts at 1 second each take at least 3 seconds plus backoff delays, which is longer than the caller's 2 second deadline. The test should assert that the total elapsed time is at most 2 seconds, and it will fail. The fix is to reduce the attempts or timeout, or to pass a shared deadline so retries stop when the caller's budget is spent.