Module: L3-M06 · Duration: ~120 minutes (estimate, including the independent exercise) · Previous: L01 (fault injection) · Next: L03
1. Introduction
L01 showed that safe recovers under every one-rule fault on t01. This lesson opens the box: how it recovers, and why retry_new_key both recovers from some faults and creates a worse failure: a duplicate side effect. The library records two loans for one book; the student receives two identical messages; the extra loan eats the borrowing limit, so the second book is blocked with LIMIT.
Three caller-side tools go together: a timeout (stop waiting after a while), retries with backoff (wait longer and longer between attempts) and jitter (add randomness to the wait). The AWS article on this topic states the problem with retries plainly: some calls have side effects, and if doing the effect several times is undesirable, "a best practice is designing APIs to be idempotent, meaning they can be safely retried" [R1]. The fourth tool therefore sits on the server side: the idempotency key (met in L3-M02-L04).
What the lesson produces: the retry policy lab/retry.py on a simulated clock, the side-effect ledger lab/ledger.py, which finds duplicate effects by their business meaning, the duplicate-side-effect tests in tests/test_l02_retries.py, and in §9 a duplicate check plus a retry policy you choose.
2. Learning objectives
- Explain timeouts, capped exponential backoff, jitter and Retry-After, and state why retries can make overload worse. Read: §4.1.
- Explain how an idempotency key prevents duplicate effects, and why the key must stay the same across every attempt of one operation. Read: §4.2, §5.2.
- Read a retry policy and compute its waits; choose a policy that meets a limit on attempts and on latency. Read: §5.1. Practice: §8.3, §9 (TODO 3).
- Write duplicate-side-effect tests that read the ledger, not the agent's words or the keys. Read: §6.1. Practice: §8.2 (parts B, C), §9 (TODO 1, TODO 2).
3. Prerequisites and tools
- L01 of this module (the fault-injection layer, seven outcomes, three configurations), L3-M02-L04 (idempotency keys in the tool layer, the effect log), L3-M04-L04 (redundant calls, retry after error as an efficiency flag). Code lab
code-labs/l3-m06. - Keep the meanings apart. An operation is one logical piece of work, such as "borrow B001 for S0107 at step 1"; an attempt is one sending of that operation to the tool. One operation can have several attempts. This lesson's ledger records the effects actually applied to the environment, one row per effect; it differs from the effect log of L3-M02-L04 (which records every call with the state before and after). In L3-M04-L04, "retry after error" was an efficiency flag for a reader to look at; here retrying is a mechanism that is designed and tested. Do not confuse the two
duplicates: theduplicatestatus of an attempt (L3-M02-L04) means the server recognised the key and returned the old result, a good thing; theduplicateoutcome of a run means an effect was applied twice, a bad thing. - Every time is in milliseconds on
SimClock; nothing really sleeps. The tools, keys and students are simulated and fictional.
4. Concept explanation
4.1 Timeouts, backoff, jitter, and the price of retrying
A timeout keeps the caller from hanging. The AWS article advises choosing the timeout from the measured latency of the downstream service: pick an acceptable rate of false timeouts (for example 0.1%) and take the matching percentile (p99.9) [R1].
Retries mask transient faults, but they multiply load. The same AWS article works through a stack of five service layers, each retrying three times: the load on the database "will increase 243x" (3^5), and it advises retrying at one point in the stack [R1]. Google's SRE book advises limiting retries per request (at most three [R4]) and says: "Don't retry permanent errors or malformed requests in a client, because neither will ever succeed" [R5].
Backoff spreads the attempts out: the wait grows exponentially, with a cap (capped exponential backoff) [R1]. Jitter adds randomness to the wait so that clients do not all retry at the same moment; the AWS Architecture Blog compares "Full Jitter", "Equal Jitter" and "Decorrelated Jitter" and calls exponential backoff without jitter "the clear loser" [R3]. The SRE book also writes "Always use randomized exponential backoff when scheduling retries" [R5]. When the server returns 429 with Retry-After (L01), the caller should wait at least that long. The Claude API's error documentation describes the official SDKs retrying transient errors "with exponential backoff, twice by default, honoring the retry-after header when present" [R7].
For a tester, these are checkable questions: which codes are retried, how many times, how long the waits are, whether there is a cap, whether there is jitter, whether Retry-After is honoured, and what the worst-case latency is.
4.2 Idempotency keys: same operation, same key
A timeout or a 500 does not say the effect has not happened (L01). If the caller retries as a new request, the server does the work again. The AWS article on idempotent APIs defines: "An idempotent operation is one where a request can be retransmitted or retried with no additional side effects", and describes how AWS does it: the caller sends a unique request identifier; when the server sees that identifier again, it knows the request is a duplicate [R2]. Three details from that article are three tests:
- Record the key and the effect together. Recording the idempotency token and every change must be one ACID operation, "all or nothing", so that the key is never recorded without the resource or the other way round [R2].
- Same key, different parameters is a validation error, "a parameter mismatch between idempotent requests" [R2].
- Answer with a semantically equivalent response. Returning
ResourceAlreadyExistsfor a retry creates no effect on the server, but according to the article it "has a side effect from the client's perspective": the caller thinks it failed [R2]. You will see exactly this in §8.2 part C, under the nameNONE_LEFT.
APIs differ in the details: with API v1, Stripe stores and returns even the first attempt's 500 response for the same key ("Retries with the same key return the saved response, including 500 errors") [R6]; the lab does not (§5.2). So read the documentation of the exact API you are testing; do not guess.
The most important point for the caller: the key belongs to the operation, not to the attempt. The AWS article tells how the SDK generates an identifier when the caller does not supply one, and then "This generated identifier is then reused in the event of a retry" [R2]. A client that generates a new key for every attempt has a key that does nothing.
5. Technical deep dive
5.1 lab/retry.py: policy, waits, timeout
A policy is a dict with exactly the fields of DEFAULT_POLICY: max_attempts (total attempts, including the first), base_ms, cap_ms, jitter (none or full), timeout_ms, retry_on (error codes worth retrying), honor_retry_after, reuse_key. DEFAULT_POLICY deliberately does not retry (max_attempts: 1): retrying is a decision, not a default. validate_policy returns error codes and does not raise; the code to remember is RETRIES_PERMANENT: putting a permanent error (LIMIT, NONE_LEFT, IDEMPOTENCY_CONFLICT, ...) into retry_on is rejected, exactly following the "don't retry permanent errors" advice in §4.1.
The wait after attempt a is min(cap_ms, base_ms * 2**(a-1)). With jitter: "full", that value is replaced by an integer drawn uniformly from [0, that value], seeded by (seed, trial, operation key, a): the same run always waits the same way, two different operations wait differently. After RATE_LIMITED, if honor_retry_after, the wait is max(backoff, retry_after_ms).
call(library, tool, args, policy, clock, injector, op_key) runs one operation. If an attempt exceeds timeout_ms, the clock advances only timeout_ms and the caller sees TIMEOUT, even though the server may already have written. ok or duplicate is success; a code outside retry_on, or running out of attempts, returns that error. The key sent is op_key if reuse_key, otherwise op_key#a<attempt>. retry_new_key tries 4 times, no jitter, does not honour Retry-After, a new key every time; safe tries 4 times, full jitter, honours Retry-After, keeps the key.
5.2 Keys on the server, the ledger, and duplicates by meaning
In lab/tools.py, a write tool's key is scoped by (tool name, key). The server stores the key together with the effect and the successful result (the lab's stand-in for the "ACID" of §4.2). Same key, same parameters: it returns the stored result with status duplicate and writes nothing. Same key, different parameters: IDEMPOTENCY_CONFLICT. A failed attempt stores no key, so it can be retried with the same key. This is the lab's choice, closer to AWS than to Stripe API v1: with partial_write, the lab treats the effect and the stored key as a "success", so a retry with the same key gets duplicate (success), not the 500 again. Library(honor_keys=False) is a broken server that ignores keys.
The ledger (Ledger) records each applied effect: effect, key, at_ms, attempt. ledger.duplicates(entries) groups by business identity (("borrow", student, book), ("return", ...), ("notice", student, text)), not by key: retry_new_key produces two rows with different keys (step1#a1, step1#a2) for the same loan, and a "are the keys duplicated?" check would say "no duplicate". check_end_state compares the ledger with the task's expect and returns missing, duplicate, unexpected. The docstring records two blind spots in opposite directions: two notices with the same text sent on purpose are flagged too (the lab's tasks do not require that); and a notice resent with different text (for example with "(retry 2)" added) is not a duplicate by identity, so duplicates() misses it and it only shows up in check_end_state(...)["unexpected"].
6. QA perspective
6.1 Duplicate-side-effect tests: read the ledger, not the agent's words
Part B of the demo (§8.2) is four runs of t05 under borrow_partial: the first borrow of B001 is written and then the server returns TRANSIENT. naive stops (the loan still exists). retry_new_key retries with a new key: the server writes a second loan, which takes B007's place in S0107's 3-book limit, and step 2 is blocked with LIMIT. safe retries with the same key, gets duplicate, and carries on. The last row is safe on a server that ignores keys: the caller does everything right and there are still two loans. A duplicate-side-effect test must catch this row too, so it reads the ledger, not how the client uses keys.
Part C is the opposite direction: t01 with borrow_timeout_after (the loan is written, the answer arrives after 5000 ms, the caller stops waiting at 3000 ms). B005 has only one copy, so retry_new_key's attempt with a new key is blocked by the server with NONE_LEFT: there is no duplicate effect, but the agent reports failure while the student does have the book. A business rule hides the duplicate and turns it into a false failure; this is exactly the ResourceAlreadyExists case the AWS article describes [R2].
From that, the list of duplicate-side-effect tests for each write tool:
- Partial write then retry (
partial_write) and late write then retry (timeoutwitheffect: "after"), with data where the business rules do not block the second write (the book has copies left, the student has limit left). If the data blocks it, you are testing the business rule, not idempotency. - Assert on the ledger:
ledger.duplicates(run["effects"]) == [],check_end_state(...)["duplicate"] == []andcheck_end_state(...)["unexpected"] == [](a resend with different text only shows up here). - Assert the same key across every attempt of one operation (read
attempts[*]["key"]), and that the same key with different parameters returnsIDEMPOTENCY_CONFLICT. - Once with a server that ignores keys, to be sure your test catches duplicates even when the client does the right thing.
- Do not retry permanent errors (
test_permanent_errors_are_not_retried) and honour Retry-After (part D).
Part E: 20 trials per task under flaky. Retrying raises the number of successes (63 to 70 and 82 out of 100) and the number of attempts (202, 231, 248). retry_new_key trades 7 successes for 4 runs with a duplicate effect; safe has none. L04 computes the cost and latency of retrying.
7. Real-world scenarios
Scenario 1 (fictional): "Two messages". A parent receives two "B004 returned. Thank you." messages three seconds apart. The log shows the first send hit the client's timeout, and then the client retried. The tester reproduces it with notice_partial and sees retry_new_key come out duplicate. The fix keeps the key across every attempt; the regression test asserts on the ledger, and runs once more with honor_keys=False to prove the test catches duplicates.
Scenario 2 (fictional): "Retry just to be sure". A team adds LIMIT to the list of retried codes "just to be sure". validate_policy returns RETRIES_PERMANENT. In a system without that validator, the result is four useless calls for every student who has hit the limit, right when the library is busiest.
8. Hands-on tutorial
8.1 Setup
cd academy-content/code-labs/l3-m06
python3 -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install -r requirements.txt
python -m pytest # 145 passed
8.2 Run the demo
python -m lab.demo l02
Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-05; both versions gave identical output). Every run is simulated:
A. backoff waits after attempts 1..3 (all TRANSIENT, no Retry-After)
no jitter, t05-s0-t0-step1: [200, 400, 800]
no jitter, t05-s0-t1-step1: [200, 400, 800]
full jitter, t05-s0-t0-step1: [37, 353, 273]
full jitter, t05-s0-t1-step1: [45, 339, 198]
B. t05 (S0107 borrows B001 then B007), borrow_partial: the first borrow is written, then the server answers TRANSIENT
naive (server honours keys): first borrow attempts=[('step1', 'TRANSIENT')]
effects=[['S0107', 'B001']] duplicates=[] outcome=loud_failure stop=tool_error:TRANSIENT
retry_new_key (server honours keys): first borrow attempts=[('step1#a1', 'TRANSIENT'), ('step1#a2', 'ok')]
effects=[['S0107', 'B001'], ['S0107', 'B001']] duplicates=[('B001', 2)] outcome=duplicate stop=tool_error:LIMIT
safe (server honours keys): first borrow attempts=[('step1', 'TRANSIENT'), ('step1', 'duplicate')]
effects=[['S0107', 'B001'], ['S0107', 'B007']] duplicates=[] outcome=recovered stop=final
safe (server IGNORES keys): first borrow attempts=[('step1', 'TRANSIENT'), ('step1', 'ok')]
effects=[['S0107', 'B001'], ['S0107', 'B001']] duplicates=[('B001', 2)] outcome=duplicate stop=tool_error:LIMIT
C. t01 (B005 has one copy), borrow_timeout_after: the loan is written, the answer comes after 5000 ms
naive: attempts=[('TIMEOUT', 3000)] claimed_success=False loans written=1 outcome=loud_failure
retry_new_key: attempts=[('TIMEOUT', 3000), ('NONE_LEFT', 250)] claimed_success=False loans written=1 outcome=loud_failure
safe: attempts=[('TIMEOUT', 3000), ('duplicate', 250)] claimed_success=True loans written=1 outcome=recovered
D. t01, borrow_rate_limit (retry_after_ms 1500): who waits long enough
retry_new_key: attempts (outcome, wait after)=[('RATE_LIMITED', 200), ('RATE_LIMITED', 400), ('RATE_LIMITED', 800), ('RATE_LIMITED', 0)] outcome=loud_failure
safe: attempts (outcome, wait after)=[('RATE_LIMITED', 1500), ('ok', 0)] outcome=recovered
E. 20 trials per task under the 'flaky' plan: attempts, duplicates and successes per config
naive: tool calls=202 attempts=202 runs with a duplicate=0 successes=63/100
retry_new_key: tool calls=208 attempts=231 runs with a duplicate=4 successes=70/100
safe: tool calls=220 attempts=248 runs with a duplicate=0 successes=82/100
Reading the output: part A: with full jitter, two different operations (trial 0 and trial 1, the same step 1) wait differently. Part B: in the attempts column, step1#a1 and step1#a2 are two different keys; step1 twice is the same key. Part C: TIMEOUT after exactly 3000 ms (the client's timeout), then the second attempt takes 250 ms; with all three configurations, the ledger has only one loan, but only safe tells the truth. Part D: 200 + 400 + 800 = 1400 ms of waiting still falls inside the 1500 ms window, so all four of retry_new_key's attempts are limited; safe waits 1500 ms once. Part E: §6.1.
8.3 Try it yourself
Save this as try_l02.py in the lab's root folder, run python try_l02.py, then delete the file:
from lab import retry as RT
from lab.clock import SimClock
from lab.tools import Library
pol = {**RT.DEFAULT_POLICY, "max_attempts": 5, "base_ms": 100, "cap_ms": 1000, "jitter": "full"}
print(RT.validate_policy(pol), RT.validate_policy({**pol, "retry_on": ["TRANSIENT", "LIMIT"]}))
print(RT.schedule({**pol, "jitter": "none"}), RT.schedule(pol, op_key="notice-1"))
lib, clock = Library(), SimClock()
args = {"student": "S0518", "text": "Your hold on B001 is ready."}
print(RT.call(lib, "send_notice", args, pol, clock, None, "notice-1")[0])
print(RT.call(lib, "send_notice", args, pol, clock, None, "notice-1")[0])
print(RT.call(lib, "send_notice", {**args, "text": "Your hold on B007 is ready."}, pol, clock, None, "notice-1")[0])
print(len(lib.ledger), lib.outbox, clock.now)
Output (Python 3.14.6 and 3.12.3, Linux, identical):
[] ['RETRIES_PERMANENT']
[100, 200, 400, 800] [10, 93, 8, 544]
{'status': 'ok', 'result': {'notice': 1}}
{'status': 'duplicate', 'result': {'notice': 1}}
{'status': 'error', 'code': 'IDEMPOTENCY_CONFLICT'}
1 [{'student': 'S0518', 'text': 'Your hold on B001 is ready.'}] 450
Reading: line 1: adding LIMIT to retry_on gives RETRIES_PERMANENT. Line 2: without jitter it is 100, 200, 400, 800 (the cap of 1000 is not reached yet); with jitter each number lies in [0, the matching value]. The next three lines call the tool through RT.call with no injector: the second call with the same key and the same text gets duplicate, the third with the same key and different text gets IDEMPOTENCY_CONFLICT. The last line: one effect, one message, the clock advanced 3 × 150 ms.
8.4 Run the lesson's tests
python -m pytest tests/test_l02_retries.py -v
Result: 30 passed. Read test_partial_write_table_of_the_lesson, test_late_write_with_a_new_key_becomes_a_false_failure and test_duplicates_are_found_by_business_identity_not_by_key.
8.5 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ValueError: invalid retry policy |
The policy is missing a field, has an extra field, or has a permanent code in retry_on |
Start from {**RT.DEFAULT_POLICY, ...}; read the error codes |
| No duplicate effect even with a new key every time | A business rule blocks the second write (NONE_LEFT, LIMIT, NOT_ON_LOAN) |
Use data where the second write is valid (t05 with B001; notices) |
Unexpected IDEMPOTENCY_CONFLICT |
The same op_key for two different operations |
A key belongs to one operation: it includes the task, seed, trial and step; it does not include the attempt |
| The jittered waits differ from your numbers | The seed includes the operation key | Call RT.schedule(pol, op_key=...) with the right key |
9. Independent exercise
Problem: Task t03 (S0315 borrows B002, then gets a notice) under four plans in exercises/ex_retry_l02.json, with the limits: at most 4 attempts per operation, at most 9000 ms per run.
Requirements: complete exercises/test_l02_retries.py:
- TODO 1:
DUPLICATES: for each plan, whetherretry_new_keyleaves a duplicate effect on t03 (True/False). - TODO 2: the function
has_duplicate(run)readsrun["effects"]and returnsTruewhen the same effect was applied more than once, whatever the keys and whatever the agent says. The test calls it on runs from whichend_stateandsuccesshave been removed. - TODO 3:
POLICY: a complete policy such thatA.run_task("t03", "naive", plan, policy=POLICY)isrecoveredfor every plan, within the attempt and latency limits.
Test data: exercises/ex_retry_l02.json.
Deliverable: the two variables and one function, in the file exercises/test_l02_retries.py itself.
Acceptance criteria: python -m pytest exercises/test_l02_retries.py passes (3 tests).
Hints: for TODO 1, ask for each plan: is the effect written before the caller sees the fault, and is the second write valid by the business rules? Look up data/books.json and data/students.json. For TODO 2, a write on the second attempt is not a second write. For TODO 3, DEFAULT_POLICY does not retry; read each plan and ask what the policy needs to get past it, then run and read run["calls"][i]["attempts"].
10. Knowledge check
0/10 done · Results are kept in this browser only.
P02 · True or false
P03 · Fill in the blank
P04 · Select all that apply
P05 · Put in order
P06 · Match
P07 · Spot the bug
This client code retries the send_notice call. It has a bug that can make the student receive two messages. Find the bug.
def send_with_retry(lib, args, clock, attempts=4):
for a in range(1, attempts + 1):
key = f"notice-{args['student']}-{clock.now}"
duration, resp = lib.invoke("send_notice", args, key, None, clock.now, attempt=a)
clock.advance(duration, "tool")
if resp["status"] in ("ok", "duplicate"):
return resp
if resp.get("code") not in ("TRANSIENT", "TIMEOUT", "RATE_LIMITED"):
return resp
clock.advance(200 * 2 ** (a - 1), "backoff")
return respP08 · Essay
In part C of the demo, retry_new_key stops with NONE_LEFT and the ledger has only one loan. Write three to five sentences: is this a duplicate effect, what does the student see, and why does a duplicate-side-effect test on this data not prove that the client is safe.
P10 · Recall
Lesson: L3-M06-L0111. Summary
- Concepts: timeouts, capped exponential backoff, jitter, Retry-After, retry amplification [R1][R3][R4][R5][R7]; idempotency keys, recording the key with the effect, parameter conflicts, equivalent responses [R2][R6].
- Skills: read and choose a retry policy; write duplicate-side-effect tests on the ledger; tell a duplicate effect from a false failure.
- Traps: a new key on every attempt; tests that check keys instead of effects; data where a business rule hides the duplicate; retrying permanent errors; not honouring Retry-After.
- You can now: prove that an agent retries without doing one thing twice, and show where it would do it twice if the server or the client were wrong.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | Timeouts, retries, and backoff with jitter | Amazon Builders' Library (AWS Builder Center) | https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/ | 2026-11-05 | Timeouts from latency percentiles; 243x amplification; retry at one point; idempotency for safe retries |
| R2 | Making retries safe with idempotent APIs | Amazon Builders' Library | https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/ | 2026-11-05 | Definition of idempotent; request identifiers; ACID; parameter mismatch; ResourceAlreadyExists; the SDK reuses the identifier |
| R3 | Exponential Backoff And Jitter | AWS Architecture Blog | https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ | 2026-11-05 | Full, Equal, Decorrelated Jitter; no jitter is "the clear loser" |
| R4 | Handling Overload (Site Reliability Engineering, ch. 21) | https://sre.google/sre-book/handling-overload/ | 2026-11-05 | Three attempts per request | |
| R5 | Addressing Cascading Failures (Site Reliability Engineering, ch. 22) | https://sre.google/sre-book/addressing-cascading-failures/ | 2026-11-05 | Randomized exponential backoff; do not retry permanent errors | |
| R6 | Idempotent requests | Stripe API Reference | https://docs.stripe.com/api/idempotent_requests | 2026-11-05 | Returns the saved response, including 500s (API v1) |
| R7 | Errors | Anthropic (Claude API documentation) | https://platform.claude.com/docs/en/api/errors | 2026-11-05 | SDKs retry twice with exponential backoff, honouring retry-after |
Glossary (English ↔ Tiếng Việt)
| English | Tiếng Việt |
|---|---|
| Retry policy | Chính sách thử lại: số lần thử, thời gian chờ, mã được thử lại, khóa |
| Capped exponential backoff | Backoff mũ có trần: chờ gấp đôi sau mỗi lần, tối đa cap_ms |
| Full jitter | Jitter đầy đủ: thời gian chờ lấy đều trong [0, giá trị backoff] |
| Operation / attempt | Thao tác (một việc logic) / lần thử (một lần gửi thao tác đó) |
| Duplicate side effect | Tác động trùng: cùng một tác động nghiệp vụ được áp hơn một lần |
| Side-effect ledger | Sổ tác động: các tác động đã áp, nhóm theo định danh nghiệp vụ; khác nhật ký tác động của L3-M02-L04 |
| False failure | Thất bại giả: agent báo thất bại trong khi tác động đã xảy ra |