The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S19 · V2·19

Safe Retries and a Revalidated Menu

Volume 2, chapter 19. Kitchen actions become safe to retry: each tap carries an Idempotency-Key, stored in the order log with the event, so a repeat after a lost response answers with the order's state instead of "409 already accepted". A small retry module retries only what's safe, only on failures that can pass, honours Retry-After, spreads clients with full jitter and stops at a deadline. The full menu gets an ETag and is revalidated on every load. A browser test loses a response on purpose: without a key, the cook sees "Failed to fetch" and then a 409 for an action that worked; with one, a single tap ends in "Accepted".

6 parts · ~7 min to read
Updated Suggest a correction

Stage 19: safe retries and a revalidated menu

The brief

What you'll build.

  • server: POST /orders/{id}/events accepts an Idempotency-Key; a key seen before (in memory, or recovered from the log after a restart) answers 200 with the order's current state and Idempotent-Replayed: true; customer ids are restricted to letters, digits, - and _ (so they can't imitate the kitchen-event: key namespace), on the API and on the HTML form;
  • GET /menu.json: every dish (the kitchen display's names were limited to 50), Cache-Control: no-cache and an ETag; If-None-Match gets a 304 with no body and no Content-Length;
  • web-src/api.ts: withRetries (network errors, per-try timeouts, 408/429/502/503/504; Retry-After; full jitter; attempts and a deadline) and postCommand (one key per user action, the same on every try); the display's buttons use it;
  • tests: RetryTest (3 tests), a form test, api.test.mjs (5 tests), and web-tests/stage19.py.

Why a real company needs this. On restaurant Wi-Fi, some responses are lost after the server has done the work. Without a way to retry safely, the client either gives up (the cook taps again and gets a confusing error) or retries blindly (and, for non-idempotent actions, does things twice). Every system that takes payments, orders or bookings needs exactly-once effects over an at-least-once network.

Why now. Chapter 19 is frontend networking: HTTP semantics, idempotency, caching and ETags, and the costs of the network. Stage 17 added actions over an unreliable connection; stage 5 built idempotency keys for placement; this stage completes the picture for every write.

What you'll have at the end.

  • every kitchen action safe to retry, across restarts;
  • a retry policy with tests for each rule;
  • ADR-0021: retries and idempotency.

Theory to own

  1. Lost responses. A cook taps "Accept"; the server applies it; the response is lost. What can the client know, and what should happen next? (Companion, theoretical gap 1.)
  2. Which failures to retry. Network errors, timeouts, 400, 404, 409, 429, 500, 502, 503, 504: which, and why?
  3. Jitter. Why randomise retry delays, and why "full" jitter? (Companion, Code walkthrough.)
  4. Keys. Who generates the idempotency key, how long must the server remember it, and what does it return for a repeat?
  5. Revalidation. Why no-cache with an ETag for the menu, rather than max-age=300?

Build it

Step 1: idempotent kitchen events

In Server.event, read an optional Idempotency-Key; build IdempotencyKey.of("kitchen-event:" + orderId, requestId); inside the order's lock, if the key is known, answer 200 with the order's current state and Idempotent-Replayed: true; otherwise apply the event as before and log it with the key (log.append(next, Optional.ofNullable(key), …)), then remember it. Since recovered keys are already loaded into byKey at start-up (stage 5), they survive restarts. Restrict customer ids to [A-Za-z0-9_-]{1,40} so no customer can be called kitchen-event:o1. Write RetryTest: the same key twice gives 200 and the replay header; a new key gives 409; no key keeps the old behaviour; after a restart, the key is still known.

Checkpoint. 26 server tests pass.

Step 2: a menu that revalidates

Add GET /menu.json: the whole menu as Dish[], ETag (the first 16 hex characters of a SHA-256 of the body), Cache-Control: no-cache; answer 304 when If-None-Match matches. Make write() send no body and no Content-Length on a 304. Switch the display's names to /menu.json. Test: 200 then 304, no Content-Length on the 304, and a new ETag after replaceMenu.

Checkpoint. RetryTest's menu test passes; the display shows names for every dish.

Step 3: the retry policy

Write web-src/api.ts. withRetries(attempt, opts): call attempt(n); on failure, retry only network errors (TypeError), per-try timeouts (TimeoutError) and statuses 408, 429, 502, 503, 504; wait Retry-After if the server sent it (capped), otherwise a random time between 0 and baseMs × 2ⁿ⁻¹ (capped); stop after attempts or when the next wait would pass deadlineMs. postCommand(url, body) generates one key with crypto.randomUUID() and sends it on every try, with an 8-second timeout per try. Make time, sleep and randomness injectable, and test each rule in api.test.mjs.

Checkpoint. check-js.sh: 5 modules, 15 tests pass.

Step 4: lose a response on purpose

Write web-tests/stage19.py. Route /orders/*/events so the first request is forwarded to the server (route.fetch()) and its response is then dropped (route.abort("connectionreset")):

  1. with plain fetch and no key (stage 17's client), tap "accept" twice;
  2. with the display's real button (stage 19's client), tap once; record each attempt's key and whether its response was replayed;
  3. answer the first try with 503 and Retry-After: 1; time the second try;
  4. reload the display and check /menu.json revalidates.

Checkpoint. Without a key, the cook gets errors for an action that worked; with one, one tap ends in "Accepted".

Step 5: check every caller of a tightened rule

Restricting customer ids changed place(), which the HTML checkout (stage 13) also calls, and the form allowed any 40 characters. A customer number like "Ravi K" would have passed the review page and failed at checkout with "Order not placed". Add the same rule to the form's validation with a human message, and a PagesTest for it.

Checkpoint. 27 server tests pass; stages 13, 14 and 17 still pass.

Senior and architect lens

1. Exactly-once effects are a protocol between client and server. The server makes an action recognisable (a key, stored atomically with its effect); the client makes it repeatable (the same key on every try) and decides when to stop. Neither half works alone, and the stage's evidence shows both failure modes: no key (errors for success) and no retry (a user left guessing).

2. ADR-0021: retries and idempotency. Write it with these points:

  • Decision: every write that a client may retry carries an Idempotency-Key, generated per user action; the server stores the key with the effect, in the same durable write, and answers a repeat with success and the current state.
  • Client policy: retry network errors, timeouts (keyed writes and GETs), 408, 429, 502, 503, 504; honour Retry-After; full jitter from 250 ms, capped at 5 s; 3 attempts within 10 s for interactive actions; show "retrying" to the user; never retry 4xx otherwise.
  • Caching: shared, changing data (/menu.json) is no-cache with an ETag; personal data is private, no-cache; nothing changing gets max-age until stage 31's versioned assets.
  • Revisit when: a gateway or another service starts retrying too (budgets, so retries don't multiply), or keys need expiry (storage grows with every action).

3. Errors are a user experience. "Failed to fetch" followed by "409 already accepted" is technically accurate and useless to a cook. The display now says what it's doing ("Retrying…") and, on giving up, what to do ("check the connection and tap again", safe because a new tap is a new key and the server rejects a second accept with a clear reason).

4. Test harnesses need the same discipline as the code. The first run of the browser test measured scenario 2's retry as scenario 3's: shared state, in-flight work, and assumptions about ordering (the Companion to chapter 15's theoretical gap 2, in Python). Isolate scenarios and wait for completion, not for the first sign of it.

5. A tightened rule has callers. Changing what the API accepts is a contract change (stage 16's lesson, here for an input rather than an output): find every client, including your own HTML form, and give each a way to fail gracefully.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
keys are remembered forever, in memory and in the log memory grows with every action Volume 3 (key expiry and compaction)
the checkout form still posts without a retry policy a lost checkout response leaves the customer unsure stage 29 (client-side placement with keys, queued while offline)
pricedBy still packs two rule names in one string the contract can only say "string" stage 30 (API cleanup with the contract package)
optional fields and unions in the contract the schema language has neither stage 30
retries at more than one layer load multiplies in an outage Volume 3 (gateway retry budgets)
an offline display queues nothing taps while offline are lost stage 29 (background sync with the same keys)

Evidence

  • RetryTest (3) and the new form test pass: 27 server tests.
  • api.test.mjs passes: 15 JavaScript tests in all; the retry rules are each tested.
  • stage19.py's output (no key against key, Retry-After, revalidation) is in the README.
  • Stages 13, 14 and 17 still pass.
  • ADR-0021 is committed.

Carry forward

  • postCommand is how every write leaves the browser from now on; stage 29's client-side checkout and offline queue use it with the same keys.
  • Keys stored with effects is the server rule for every write endpoint in Volume 3.
  • /menu.json with an ETag is the model for cacheable shared data; stage 31 adds CDN caching on top.
  • "Show what you're doing" (retry messages on the card) is part of stage 20's accessibility pass: those messages must reach screen readers too.