Boss lesson · Unit 01
The safe retry
Backoff, jitter and idempotency keys
What you practise
- Retries with exponential backoff and jitter, retry storms, idempotency keys, at-least-once vs at-most-once and why "exactly-once" means dedup, circuit breakers
Try a question from this lesson
Pick one
A payment request timed out. Retrying might charge twice; not retrying might never charge. What would make the retry safe?
Correct answer
The server spots a repeated request and does the work only once
Why
You cannot remove the uncertainty, so remove the danger: if doing the request twice has the same effect as doing it once, a retry costs nothing. This lesson builds that, plus the manners a retry needs.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Jitter
Backoff alone has a flaw: clients that failed together wait the same 100, 200, 400 ms and come back together, in waves.
Jitter breaks the waves. Instead of waiting exactly the backoff time, each client waits a random time up to it. A cap keeps the wait from growing forever.
import random
def wait_ms(attempt, base=100, cap=5000):
limit = min(cap, base * 2 ** attempt)
return random.uniform(0, limit)Concept
Idempotency keys
An operation is idempotent if doing it twice has the same effect as doing it once.
To make a charge idempotent, the client invents a unique key for the purchase and sends the same key with every attempt. The server remembers each key with its result. A repeat gets the stored result back, and no second charge.
done = {}
def charge(key, amount):
if key in done:
return done[key] # a retry
receipt = f"charged {amount}"
done[key] = receipt
return receipt10 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.