← Learning guides

Worked tutorial · about 40 minutes

Simulate a bounded retry budget without sending requests

Trace seven invented jobs through capped backoff, per-job attempt limits and a shared retry allowance, then compare two finite budgets.

Original editorial exercise · fictional practice data · checked 25 October 2026

Retrying can rescue a transient failure while spending more attempts on the same work. In this exercise, you will trace scripted outcomes and account for every attempt and wait. The Python program adds virtual milliseconds; it makes no network requests and never sleeps. All outcomes and durations are invented.

1. Download the scripted jobs

Scripted outcome sequences, consumed only when an attempt occurs
JobPossible successive outcomes
R1ok
R2transient → ok
R3permanent → ok
R4transient → transient → transient → transient
R5transient → transient → ok
R6transient → transient → ok
R7transient → ok

The words transient and permanent are exercise labels. They are not a classification of particular HTTP status codes. Unreached outcomes stay unused: R3's later ok does not override its first permanent failure.

2. Apply the policy in a fixed order

  1. Process jobs R1 through R7 one at a time. Always allow the initial attempt. Every attempt adds 50 virtual ms.
  2. Stop immediately on ok, recording success. Stop on permanent, recording permanent_error.
  3. After a transient outcome, stop with attempt_limit if the job has already made four total attempts. Four attempts include the initial attempt and at most three retries.
  4. Otherwise, stop with retry_budget if the shared batch allowance is empty. Start with seven retry tokens; they never refill. Initial attempts use no token.
  5. If a token remains, consume one and retry after a wait. For local retry number k, the wait is min(100 × 2^(k − 1), 250) virtual ms: 100, then 200, then 250. Repeat until the job stops.

Count waiting time only when a retry will actually occur. Do not spend a token or add a wait after success, a permanent failure, or a stopping limit. This finite batch allowance is an exercise policy, with no time-based refill.

Before running code, trace attempts, remaining tokens and stop reasons in the worksheet. Then reset the scenario and repeat with nine tokens, keeping the per-job limit and delays unchanged.

3. Compare the seven-token answer

Show every job's attempts, waits and stop reason
Seven shared retry tokens; all elapsed times are virtual milliseconds
JobAttempts / retriesWaitsElapsedStopTokens left
R11 / 0none50success7
R22 / 1100200success6
R31 / 0none50permanent_error6
R44 / 3100 + 200 + 250750attempt_limit3
R53 / 2100 + 200450success1
R62 / 1100200retry_budget0
R71 / 0none50retry_budget0

There are 14 attempts: 7 initial attempts plus 7 retries. Backoff totals 1,050 ms. Attempt time is 14 × 50 = 700 ms, so total serial virtual elapsed time is 1,750 ms. Three jobs succeed, one stops on a permanent failure, one reaches the attempt limit, and two stop on the retry budget.

R4 shows why the cap matters: its third retry waits 250 ms rather than 400 ms. Its fourth transient outcome stops at the attempt limit without spending another token.

4. Compare the reference budget and run the simulator

Show the nine-token comparison

R6 now reaches its third attempt and succeeds. R7 gets its second attempt and succeeds. The reference run uses 16 attempts and 9 retries, with 1,350 ms of waits and 2,150 ms of serial virtual time. It produces 5 successes; R3 still stops on permanent_error and R4 still stops on attempt_limit. Two extra tokens add two attempts and 400 virtual ms under these scripted outcomes.

Save all downloads in one folder and use Python 3.10 or later:

python simulate_retries.py scenario.json
python simulate_retries.py scenario.json --check answer_key.json

The output contains both complete traces. The answer check exits with status 0 on an exact match. There are no third-party dependencies, credentials, HTTP clients or timers.

Show the complete simulator
"""Deterministic offline retry accounting. Python 3.10+, stdlib only; no requests or sleeps."""
import argparse
import json
from pathlib import Path

STOPS = ("success", "permanent_error", "attempt_limit", "retry_budget")


def simulate(data, retry_tokens):
    limit = data["max_attempts_per_job"]
    duration = data["attempt_duration_ms"]
    base, cap = data["backoff_base_ms"], data["backoff_cap_ms"]
    if type(limit) is not int or limit < 1:
        raise ValueError("max_attempts_per_job must be a positive integer")
    if any(type(value) is not int or value < 0 for value in (retry_tokens, duration, base, cap)):
        raise ValueError("Budgets and virtual durations must be nonnegative integers")
    remaining, jobs = retry_tokens, []
    for job in data["jobs"]:
        outcomes = job["outcomes"]
        if not outcomes or any(value not in ("ok", "transient", "permanent") for value in outcomes):
            raise ValueError("Each job needs a nonempty list of known outcomes")
        attempts, elapsed, waits, attempted = 0, 0, [], []
        while True:
            if attempts >= len(outcomes):
                raise ValueError("Missing scripted outcome for " + job["id"])
            outcome = outcomes[attempts]
            attempts += 1
            elapsed += duration
            attempted.append(outcome)
            if outcome == "ok":
                stop = "success"
                break
            if outcome == "permanent":
                stop = "permanent_error"
                break
            if attempts >= limit:
                stop = "attempt_limit"
                break
            if remaining == 0:
                stop = "retry_budget"
                break
            remaining -= 1
            wait = min(base * 2 ** (attempts - 1), cap)
            waits.append(wait)
            elapsed += wait
        jobs.append({"id": job["id"], "attempted_outcomes": attempted, "attempts": attempts,
                     "retries": attempts - 1, "waits_ms": waits, "elapsed_ms": elapsed,
                     "stop": stop, "retry_tokens_remaining": remaining})
    return {"initial_retry_tokens": retry_tokens, "retry_tokens_remaining": remaining,
            "total_attempts": sum(job["attempts"] for job in jobs),
            "total_retries": sum(job["retries"] for job in jobs),
            "total_backoff_ms": sum(sum(job["waits_ms"]) for job in jobs),
            "total_virtual_elapsed_ms": sum(job["elapsed_ms"] for job in jobs),
            "stop_counts": {stop: sum(job["stop"] == stop for job in jobs) for stop in STOPS},
            "jobs": jobs}


def calculate(data):
    return {"budgeted": simulate(data, data["batch_retry_tokens"]),
            "reference": simulate(data, data["reference_batch_retry_tokens"])}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("--check", type=Path)
    args = parser.parse_args()
    result = calculate(json.loads(args.input.read_text(encoding="utf-8")))
    print(json.dumps(result, indent=2))
    if args.check and result != json.loads(args.check.read_text(encoding="utf-8")):
        parser.exit(1, "Answer mismatch: compare the printed values with your answer.\n")


if __name__ == "__main__":
    main()

5. Test order sensitivity and state the limits

Reverse the job array in a copy, keep seven retry tokens, and run without the original answer key. Predict which jobs receive the scarce retries before inspecting the result.

Show the reversed-order result

R7, R6 and R5 consume 1, 2 and 2 retry tokens and succeed, leaving two for R4. R4 stops on retry_budget after three attempts; R3 stops on permanent_error; R2 has no token and stops after its initial transient outcome; R1 succeeds immediately. There are 4 successes: R7, R6, R5 and R1. The same seven-token budget still permits only 14 total attempts. This policy distributes retries by input order rather than by job importance.

The AWS Builders' Library discussion of retries and backoff explains retry load, capped backoff, attempt limits and jitter. It also explains why operations with side effects need idempotency considerations. This worksheet uses deterministic waits to make arithmetic repeatable; it does not implement jitter, an AWS SDK retry policy or a replenishing token bucket.

The simulation establishes accounting under its declared rules. It leaves actual failure probabilities, request safety, deadlines, concurrency, fairness and service recovery unmeasured. More retries happen to reach more scripted successes in the reference run; that is not evidence that extra retries would improve an overloaded real service.

For a separate timing calculation, try the latency percentile lab. For a budget based on invented token rates, use the token planning exercise.

Sources and scope

All jobs, classifications, limits, timings and answer traces are original editorial practice material. The AWS source supports the retry concepts; the exact batch policy is defined here. Source checked 25 October 2026.