Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 1

Injecting latency and failures into a call chain

Run three Python services in a chain, inject 2 s of latency into the last one and watch the cascade reach an endpoint that never calls it, then contain it with a bulkhead, timeouts with a deadline and a retry budget, and a circuit breaker with a fallback, and count retries exactly.

Contentsand lesson path

What you will learn

  • Set timeouts and retry policies (exponential backoff, jitter, retry budgets) that do not amplify an outage.
  • Apply circuit breakers, bulkheads, load shedding and graceful degradation to contain failures.
  • Trace how a cascading failure spreads through a call graph and identify where each pattern stops it.

01. Goal and setup

You will build the call chain from lesson 1, edge to catalog to stock, as three small Python services. You will inject 2 s of latency into the stock service and watch the slowdown spread until an endpoint that never touches stock fails too. Then you will add patterns one at a time and see where each stops the spread: a bulkhead at the edge, timeouts with a propagated deadline and a retry budget, and a circuit breaker with a fallback. Last, you will count exactly how many calls reach a failing service under three retry policies.

You need a Linux or macOS shell (on Windows, use WSL), curl, and Python 3.10 or newer. The lab was run with Python 3.12.13 and uses only the standard library. Everything listens on 127.0.0.1: the edge on port 18301, the catalog on 18302 and stock on 18303. Each service also has a control port 10 higher (18311 to 18313) for changing settings and reading counters. Here the fault switch is built into the stock service. When you cannot change the service under test, a fault-injecting proxy such as Toxiproxy can sit between two services and add latency, errors or dropped connections instead.

Terminal · create the lab folder
mkdir resilience-lab
cd resilience-lab

02. Step 1: Check Python

Terminal · resilience-lab/
python3 --version
Expected output (3.10 or newer is fine)
Python 3.12.13

03. Step 2: Write the three services

Save this as chain.py. One file plays all three roles, and the first argument picks the role. What matters for the lab:

  • Edge and catalog each run a fixed pool of 4 worker threads, and extra requests wait in a queue, as in most thread-pool servers. Stock has 64 workers, so only its latency matters, not its capacity.
  • /admin on the control port changes settings while the service runs. On stock it sets delay in seconds and fail (1 means answer 503 at once). On the other two it sets the policy for calling the next service: timeout, retries, budget, breaker, fallback and bulkhead. Every /admin call also resets the breaker and the retry budget. /stats reports busy and queued workers and call counts.
  • call_next applies the policy: a per-try timeout capped by the deadline in the X-Deadline-Ms header, retries with full jitter only for 5xx answers and timeouts, a budget like gRPC's, and a breaker that opens after N failures in a row for 10 s, then lets one probe through. This breaker is simpler than the window-based one in lesson 4.
  • guarded_call is the bulkhead: a semaphore that rejects at once when it is full. With fallback=1, the catalog answers a failed stock call with the product marked degraded.
Python · resilience-lab/chain.py
"""One file, three roles: edge -> catalog -> stock. Python 3.12, standard library."""
import json
import random
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler, HTTPServer, ThreadingHTTPServer
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlparse
from urllib.request import Request, urlopen

ROLE, PORT = sys.argv[1], int(sys.argv[2])     # e.g. "catalog 18302"
NEXT = {"edge": 18302, "catalog": 18303}.get(ROLE)
WORKERS = 4 if ROLE != "stock" else 64           # small fixed pools, like real servers
lock = threading.Lock()
stats = {"busy": 0, "queued": 0, "calls_in": 0, "calls_out": 0, "rejected": 0}
fault = {"delay": 0.0, "fail": 0}                # stock only: injected faults
policy = {"timeout": 0.0, "retries": 0, "budget": 0, "breaker": 0,
          "fallback": 0, "bulkhead": 0}          # how this service calls NEXT
state = {"tokens": 10.0, "fails": 0, "open_until": 0.0,
         "slots": threading.BoundedSemaphore(1)}


def bump(name: str, by: int = 1) -> None:
    with lock:
        stats[name] += by


def breaker_allows() -> bool:      # open after N failures in a row, for 10 s
    if not policy["breaker"]:
        return True
    with lock:
        if time.monotonic() < state["open_until"]:
            return False
        if state["fails"] >= policy["breaker"]:  # half-open: let one probe through
            state["open_until"] = time.monotonic() + 10
        return True


def record(ok: bool) -> None:
    with lock:
        state["fails"] = 0 if ok else state["fails"] + 1
        if ok:
            state["open_until"] = 0.0
        elif policy["breaker"] and state["fails"] >= policy["breaker"]:
            state["open_until"] = time.monotonic() + 10
        delta = 0.1 if ok else -1.0                  # retry budget, as in lesson 2
        state["tokens"] = min(10.0, max(0.0, state["tokens"] + delta))


def call_next(path: str, deadline: float | None) -> tuple[int, bytes]:
    attempt = 0
    while True:
        attempt += 1
        if not breaker_allows():
            return 503, b'{"error":"circuit open"}'
        timeout = policy["timeout"] or None
        headers = {}
        if deadline is not None:
            left = deadline - time.monotonic()
            if left <= 0.01:
                return 504, b'{"error":"deadline exceeded"}'
            timeout = min(timeout or left, left)
            headers["X-Deadline-Ms"] = str(int(left * 1000))
        bump("calls_out")
        try:
            req = Request(f"http://127.0.0.1:{NEXT}{path}", headers=headers)
            with urlopen(req, timeout=timeout) as resp:
                body = resp.read()
            record(True)
            return 200, body
        except HTTPError as err:
            code, body = err.code, err.read()
            if code < 500:
                return code, body                    # a real answer: no retry
        except OSError:                              # timeout or connection error
            code, body = 504, b'{"error":"no answer in time"}'
        record(False)
        if attempt > policy["retries"]:
            return code, body
        if policy["budget"] and state["tokens"] <= 5.0:
            return code, body                        # budget spent: no retry
        time.sleep(random.uniform(0, 0.05 * 2 ** (attempt - 1)))  # full jitter


def guarded_call(path: str, deadline: float | None) -> tuple[int, bytes]:
    if policy["bulkhead"] and not state["slots"].acquire(blocking=False):
        bump("rejected")
        return 503, b'{"error":"bulkhead full: too many calls in flight"}'
    try:
        return call_next(path, deadline)
    finally:
        if policy["bulkhead"]:
            state["slots"].release()


class App(BaseHTTPRequestHandler):
    def do_GET(self):
        bump("calls_in")
        url = urlparse(self.path)
        if ROLE == "stock":
            time.sleep(fault["delay"])
            if fault["fail"]:
                return self.reply(503, b'{"error":"stock unavailable"}')
            return self.reply(200, b'{"sku":7,"stock":42}')
        if ROLE == "edge" and url.path == "/about":  # never touches NEXT
            return self.reply(200, b'{"service":"edge","status":"ok"}')
        deadline = None
        if "X-Deadline-Ms" in self.headers:          # propagate the caller's deadline
            deadline = time.monotonic() + int(self.headers["X-Deadline-Ms"]) / 1000
        elif policy["timeout"]:
            deadline = time.monotonic() + policy["timeout"]
        code, body = guarded_call("/product" if ROLE == "edge" else "/item", deadline)
        if ROLE == "catalog" and code == 200:
            stock = json.loads(body)["stock"]
            body = json.dumps({"product": 7, "stock": stock}).encode()
        elif ROLE == "catalog" and policy["fallback"]:
            code, body = 200, b'{"product": 7, "stock": null, "degraded": true}'
        self.reply(code, body)

    def reply(self, code: int, body: bytes) -> None:
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):  # keep the terminal quiet
        pass


def num(text: str) -> int | float:
    value = float(text)
    return int(value) if value.is_integer() else value


class Control(App):  # control port: /admin and /stats never wait for the pool
    def do_GET(self):
        url = urlparse(self.path)
        query = {k: num(v[0]) for k, v in parse_qs(url.query).items()}
        with lock:
            if url.path == "/admin":
                (fault if ROLE == "stock" else policy).update(query)
                state.update(tokens=10.0, fails=0, open_until=0.0, slots=(
                    threading.BoundedSemaphore(int(policy["bulkhead"]) or 1)))
                body = fault if ROLE == "stock" else policy
            else:
                body = dict(stats)
                if "reset" in query:
                    stats.update(calls_in=0, calls_out=0, rejected=0)
        self.reply(200, json.dumps(body).encode())


class PoolServer(HTTPServer):
    """A fixed pool of worker threads; extra connections wait in a queue."""

    def __init__(self) -> None:
        super().__init__(("127.0.0.1", PORT), App)
        self.pool = ThreadPoolExecutor(max_workers=WORKERS)

    def process_request(self, request, client_address):
        bump("queued")
        self.pool.submit(self.work, request, client_address)

    def work(self, request, client_address):
        bump("queued", -1)
        bump("busy")
        try:
            self.finish_request(request, client_address)
        except OSError:
            pass  # the client gave up and closed the socket
        finally:
            self.shutdown_request(request)
            bump("busy", -1)


control = ThreadingHTTPServer(("127.0.0.1", PORT + 10), Control)
threading.Thread(target=control.serve_forever, daemon=True).start()
print(f"{ROLE} on 127.0.0.1:{PORT} (control {PORT + 10}), {WORKERS} workers",
      flush=True)
PoolServer().serve_forever()

04. Step 3: Write the load generator

Save this as load.py. By default 8 clients each send 3 product requests one after another, with a 3 s client timeout, while a prober requests /about, which needs nothing downstream, 10 times with a 1 s timeout. After 1.5 s it prints how busy each pool is, and at the end it waits for queued work to finish and prints how many calls reached stock. In the summary, gave-up means the client's own timeout fired, http-503 and http-504 are error answers, and degraded is a 200 carrying the fallback.

Python · resilience-lab/load.py
"""Send a fixed set of requests to the edge and summarise what came back."""
import argparse
import json
import threading
import time
from collections import Counter
from urllib.error import HTTPError
from urllib.request import urlopen

ap = argparse.ArgumentParser()
ap.add_argument("--clients", type=int, default=8)
ap.add_argument("--requests", type=int, default=3, help="per client, one by one")
ap.add_argument("--probes", type=int, default=10, help="GET /about, 0.3 s apart")
ap.add_argument("--timing", action=argparse.BooleanOptionalAction, default=True)
args = ap.parse_args()
results: dict[str, list[tuple[str, float]]] = {"product": [], "about": []}
lock = threading.Lock()


def get(kind: str, path: str, timeout: float) -> None:
    start = time.monotonic()
    try:
        with urlopen(f"http://127.0.0.1:18301{path}", timeout=timeout) as resp:
            outcome = "degraded" if json.loads(resp.read()).get("degraded") else "ok"
    except HTTPError as err:
        outcome = f"http-{err.code}"
    except OSError:
        outcome = "gave-up"                      # the client's own timeout fired
    with lock:
        results[kind].append((outcome, time.monotonic() - start))


def client() -> None:
    for _ in range(args.requests):
        get("product", "/product", timeout=3.0)


def prober() -> None:
    for _ in range(args.probes):
        get("about", "/about", timeout=1.0)
        time.sleep(0.3)


def snapshot() -> None:                          # how full each pool is at 1.5 s
    time.sleep(1.5)
    for name, port in (("edge", 18311), ("catalog", 18312), ("stock", 18313)):
        s = stats(port)
        print(f"at 1.5 s: {name:<7} busy {s['busy']:2}, queued {s['queued']:3}")


def stats(port: int, reset: bool = False) -> dict:
    url = f"http://127.0.0.1:{port}/stats" + ("?reset=1" if reset else "")
    with urlopen(url, timeout=1) as resp:
        return json.loads(resp.read())


for port in (18311, 18312, 18313):
    stats(port, reset=True)
threads = [threading.Thread(target=client) for _ in range(args.clients)]
threads.append(threading.Thread(target=prober))
if args.timing:
    threads.append(threading.Thread(target=snapshot))
for t in threads:
    t.start()
for t in threads:
    t.join()
for kind, rows in results.items():
    if not rows:
        continue
    tally = Counter(outcome for outcome, _ in rows)
    line = f"{kind:<7} sent {len(rows):2}: " + ", ".join(
        f"{k} {v}" for k, v in sorted(tally.items()))
    if args.timing:
        ms = sorted(seconds * 1000 for _, seconds in rows)
        line += f" | p50 {ms[len(ms) // 2]:.0f} ms, max {ms[-1]:.0f} ms"
    print(line)
for _ in range(60):                              # let queued work finish first
    if all(stats(p)["busy"] + stats(p)["queued"] == 0 for p in (18311, 18312)):
        break
    time.sleep(0.5)
print(f"stock received {stats(18313)['calls_in']} calls")

05. Step 4: Start the chain

Terminal · start three services in the background
python3 chain.py stock 18303 > stock.log 2>&1 & echo $! > stock.pid
python3 chain.py catalog 18302 > catalog.log 2>&1 & echo $! > catalog.pid
python3 chain.py edge 18301 > edge.log 2>&1 & echo $! > edge.pid
sleep 1; cat stock.log catalog.log edge.log
curl -s 127.0.0.1:18301/product; echo; curl -s 127.0.0.1:18301/about; echo
Expected output (an interactive shell also prints job numbers such as [1] 12345)
stock on 127.0.0.1:18303 (control 18313), 64 workers
catalog on 127.0.0.1:18302 (control 18312), 4 workers
edge on 127.0.0.1:18301 (control 18311), 4 workers
{"product": 7, "stock": 42}
{"service":"edge","status":"ok"}

06. Step 5: Measure a healthy baseline

Terminal
python3 load.py
Illustrative output (latencies and some counts vary from run to run)
at 1.5 s: edge    busy  0, queued   0
at 1.5 s: catalog busy  0, queued   0
at 1.5 s: stock   busy  0, queued   0
product sent 24: ok 24 | p50 6 ms, max 7 ms
about   sent 10: ok 10 | p50 1 ms, max 4 ms
stock received 24 calls

Every product request and every probe succeeds, no pool is busy at 1.5 s, and stock received one call per product request. Keep these numbers to compare with later steps.

07. Step 6: Inject 2 s of latency and watch the cascade

Terminal
curl -s "127.0.0.1:18313/admin?delay=2"; echo
python3 load.py
Illustrative output (latencies and some counts vary from run to run)
{"delay": 2, "fail": 0}
at 1.5 s: edge    busy  4, queued   6
at 1.5 s: catalog busy  4, queued   0
at 1.5 s: stock   busy  4, queued   0
product sent 24: gave-up 20, ok 4 | p50 3003 ms, max 3005 ms
about   sent 10: gave-up 9, ok 1 | p50 1001 ms, max 1001 ms
stock received 24 calls

At 1.5 s the catalog's 4 workers are all waiting on stock, and the edge's 4 workers are all waiting on the catalog, with 6 more requests queued behind them. Only 4 product requests came back in time. Worse, 9 of the 10 probes gave up although /about calls nothing: they queued behind product requests in the edge's only pool. Stock still received 24 calls and answered 20 of them after their clients had left, which is wasted work. This is the cascade from lesson 1, and nothing logged a single error.

08. Step 7: Contain it at the edge with a bulkhead

Terminal · allow at most 2 catalog calls at once from the edge
curl -s "127.0.0.1:18311/admin?bulkhead=2"; echo
python3 load.py
Illustrative output (latencies and some counts vary from run to run)
{"timeout": 0.0, "retries": 0, "budget": 0, "breaker": 0, "fallback": 0, "bulkhead": 2}
at 1.5 s: edge    busy  2, queued   0
at 1.5 s: catalog busy  2, queued   0
at 1.5 s: stock   busy  2, queued   0
product sent 24: http-503 18, ok 6 | p50 4 ms, max 2006 ms
about   sent 10: ok 10 | p50 1 ms, max 4 ms
stock received 6 calls

The edge now refuses product requests it has no slot for with a fast 503, so 2 of its 4 workers always stay free: all 10 probes succeed. Only 6 calls reached stock. Product users still get errors, but the failure no longer spreads to the rest of the edge. The bulkhead stopped the cascade at the edge, without touching the catalog or stock.

09. Step 8: Add timeouts, a deadline and a retry budget

Terminal · bulkhead off, time limits on
curl -s "127.0.0.1:18311/admin?bulkhead=0&timeout=1"; echo
curl -s "127.0.0.1:18312/admin?timeout=0.3&retries=2&budget=1"; echo
python3 load.py
Illustrative output (latencies and some counts vary from run to run)
{"timeout": 1, "retries": 0, "budget": 0, "breaker": 0, "fallback": 0, "bulkhead": 0}
{"timeout": 0.3, "retries": 2, "budget": 1, "breaker": 0, "fallback": 0, "bulkhead": 0}
at 1.5 s: edge    busy  4, queued   5
at 1.5 s: catalog busy  4, queued   0
at 1.5 s: stock   busy 20, queued   0
product sent 24: http-504 24 | p50 604 ms, max 925 ms
about   sent 10: ok 10 | p50 1 ms, max 908 ms
stock received 28 calls

The edge gives each product request a 1 s deadline and passes the time left to the catalog in X-Deadline-Ms. The catalog waits at most 300 ms per try and retries only while its budget allows. Every product request now fails within about a second instead of three, so workers come free sooner and the probes succeed. The slowest probe waited about 0.9 s, close to its own 1 s limit, so on a slower machine one of them may still give up. Stock received 28 calls: 24 first tries and only 4 retries, because the budget ran out. Look at stock busy 20: stock keeps sleeping on calls whose caller gave up after 300 ms. It ignores the deadline header; a real service should check the time left before doing expensive work.

10. Step 9: Add a circuit breaker and a fallback

Terminal · open after 5 failures in a row, answer degraded meanwhile
curl -s "127.0.0.1:18312/admin?breaker=5&fallback=1"; echo
python3 load.py
Illustrative output (latencies and some counts vary from run to run)
{"timeout": 0.3, "retries": 2, "budget": 1, "breaker": 5, "fallback": 1, "bulkhead": 0}
at 1.5 s: edge    busy  0, queued   0
at 1.5 s: catalog busy  0, queued   0
at 1.5 s: stock   busy  8, queued   0
product sent 24: degraded 24 | p50 4 ms, max 654 ms
about   sent 10: ok 10 | p50 1 ms, max 618 ms
stock received 8 calls

Every product request now gets a degraded answer, most within milliseconds, and stock received only 8 calls: the 5 failures that opened the breaker plus a few already in flight. Users see the product without a stock level instead of an error, and the error rate at the edge is zero while stock is still slow. That is graceful degradation, made cheap by the breaker.

11. Step 10: Count calls exactly

Concurrency makes the counts above vary a little. To check the retry arithmetic exactly, make stock fail at once and send 20 requests one after another. Run the three blocks in order.

Terminal · 2 retries, no budget, no breaker
curl -s "127.0.0.1:18313/admin?delay=0&fail=1"; echo
curl -s "127.0.0.1:18312/admin?budget=0&breaker=0&fallback=0"; echo
python3 load.py --clients 1 --requests 20 --probes 0 --no-timing
Expected output
{"delay": 0, "fail": 1}
{"timeout": 0.3, "retries": 2, "budget": 0, "breaker": 0, "fallback": 0, "bulkhead": 0}
product sent 20: http-503 20
stock received 60 calls
Terminal · the same with the retry budget
curl -s "127.0.0.1:18312/admin?budget=1"; echo
python3 load.py --clients 1 --requests 20 --probes 0 --no-timing
Expected output
{"timeout": 0.3, "retries": 2, "budget": 1, "breaker": 0, "fallback": 0, "bulkhead": 0}
product sent 20: http-503 20
stock received 23 calls
Terminal · budget plus breaker and fallback
curl -s "127.0.0.1:18312/admin?breaker=5&fallback=1"; echo
python3 load.py --clients 1 --requests 20 --probes 0 --no-timing
Expected output
{"timeout": 0.3, "retries": 2, "budget": 1, "breaker": 5, "fallback": 1, "bulkhead": 0}
product sent 20: degraded 20
stock received 5 calls

Without a budget, each request makes 3 attempts: 60 calls. With the budget, the first request makes 3 attempts and the second makes 2; by then the tokens have fallen to the threshold, so every later request makes 1, and 3 + 2 + 18 = 23. With the breaker as well, the fifth failure in a row opens it during the second request, and the other 18 requests never reach stock: 5 calls, and every user got a degraded answer instead of an error. These counts do not depend on timing, so yours should match.

12. Step 11: Clean up

Terminal · stop exactly the processes you started
kill $(cat stock.pid catalog.pid edge.pid); sleep 1
curl -s -m 1 127.0.0.1:18301/about || echo "edge stopped"
Expected output (an interactive shell may also print three Terminated lines)
edge stopped

13. Before you inject faults anywhere shared

On your laptop a broken experiment costs nothing. On a shared staging or production system it can become the outage you were trying to prevent. The Principles of Chaos Engineering ask for two safeguards. First define a steady state, such as error rate and p99 at the edge, so you know what normal looks like, as step 5 did. Then minimise the blast radius: one service, a small share of its calls, a short time. Two more habits are common practice, though not on that page: agree a stop condition in advance, for example an error rate above 1% for one minute, with a quick way to remove the fault; and tell the teams who own the services and the alerts. Widen the experiment only when the small one behaves as you predicted.

14. Troubleshooting

15. Check your understanding

Practice check · 3 questions

Reading the experiment

Three questions about what the lab showed and how to run it safely elsewhere.

Q1. You set the catalog to retries=2, budget=0, breaker=4 and fallback=0, make stock fail every call at once, and send 10 requests one after another. How many calls reach stock?
Q2. In step 8 every product request still failed, yet all or nearly all of the /about probes succeeded, while in step 6 almost none did. What did the timeouts change?
Q3. You want to repeat this experiment on a shared staging environment that other teams use every day. Which plan is the safest first run?
Practice only: not graded, not saved, not evidence.

16. Apply it

Grow the lab into the skill's practice project:

  1. Make the stock service honour X-Deadline-Ms and stop work for callers that have left, then compare stock busy in step 8.
  2. Add queue-time load shedding to the catalog: reject a request that waited longer than its deadline before a worker took it.
  3. Add an idempotent POST /payments to the catalog with the design from lesson 3, drop the response after a successful mock payment, and retry through the chain with the same key and with a changed amount.
  4. Record each request's latency in load.py and report error rate and p99 before and after each change.
  5. Replace the built-in fault switch with Toxiproxy between catalog and stock, so the services under test need no fault code.

17. Review prompt

Without looking back, describe what you saw in step 6 and explain why /about failed although it calls nothing. For steps 7, 8 and 9, say where in the chain each pattern acted and what it did and did not fix. Then work out by hand the stock call counts of step 10 for 30 requests instead of 20.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check