Show contents
Chapter 4 of 6 · 20 min
Timeouts, retries and idempotency
By the end of this chapter, you'll be able to
- Set a timeout on every remote call
- Program retries with exponential backoff and jitter
- Make an operation idempotent with an idempotency key
- Implement a circuit breaker that protects a failing service and its caller
Always a timeout
A network call without a timeout can block a thread or a connection forever. Every remote call (API, database, cache) must have one, chosen from the measured percentiles: for example a little above the called service's normal p99. And timeouts must decrease along the chain: if your API promises a response within 2 s, it cannot wait 5 s for a downstream service.
Retrying… wisely
Many failures are transient: a lost packet, a restarting server. A retry catches them. But retrying immediately, and all at once, means hitting a service that is already struggling. So you wait longer and longer (exponential backoff: 100 ms, 200 ms, 400 ms…), and you randomise part of that wait (jitter) so that thousands of clients don't come back in the same millisecond.
import random
def waits(attempts, base_ms=100, cap_ms=5_000, jitter=True):
"""Capped exponential backoff; with "full" jitter, the wait is drawn between 0 and the current ceiling."""
result = []
for n in range(attempts):
ceiling = min(cap_ms, base_ms * 2 ** n)
result.append(round(random.uniform(0, ceiling)) if jitter else ceiling)
return result
random.seed(3)
print("no jitter:", waits(6, jitter=False))
for client in ("client 1", "client 2", "client 3"):
print(f"{client} :", waits(6))
no jitter: [100, 200, 400, 800, 1600, 3200]
client 1 : [24, 109, 148, 483, 1001, 210]
client 2 : [1, 167, 104, 187, 1593, 1505]
client 3 : [84, 95, 256, 120, 1016, 2778]
Without jitter, all the clients that failed together come back together, at the same instants: the load arrives in waves. With jitter, their returns spread out over time. You also limit the number of attempts (3 to 5), and only retry transient errors: a timeout or a 503 error, yes; a 400 error (invalid request), never, it will fail again.
The server returns the result of the first processing: the customer is charged only once.
Text description of the animation
- The call carries a timeout and a unique key generated by the client.
- No response: the payment may or may not have been made. We don't know.
- Wait a random, growing time before retrying.
- Retry with the SAME key: the server recognises the request.
- The server returns the result of the first processing: the customer is charged only once.
Idempotency
An operation is idempotent if running it twice has the same effect as running it once. Reading a record, yes. Debiting 5,000 F CFA, no. Yet after a timeout, the client does not know whether its request was processed: it must be able to retry safely. The solution: the client generates a unique idempotency key per operation and sends it with every attempt; the server remembers the result associated with each key.
import uuid
class PaymentService:
def __init__(self):
self.balances = {"aminata": 20_000}
self.processed = {} # idempotency key → result
def debit(self, customer, amount, key=None):
if key is not None and key in self.processed:
return self.processed[key]
self.balances[customer] -= amount
result = f"debit of {amount} F CFA, balance {self.balances[customer]}"
if key is not None:
self.processed[key] = result
return result
service = PaymentService()
print("no key, two attempts:")
print(" ", service.debit("aminata", 5_000))
print(" ", service.debit("aminata", 5_000))
key = str(uuid.uuid4())
print("same key, two attempts:")
print(" ", service.debit("aminata", 5_000, key))
print(" ", service.debit("aminata", 5_000, key))
print("real balance:", service.balances["aminata"])
no key, two attempts:
debit of 5000 F CFA, balance 15000
debit of 5000 F CFA, balance 10000
same key, two attempts:
debit of 5000 F CFA, balance 5000
debit of 5000 F CFA, balance 5000
real balance: 5000
With the key, the second attempt returns the stored result without debiting anything: the real balance stays at 5,000 F CFA. In production, the key table is stored in the database, in the same transaction as the debit (otherwise a failure between the two recreates the problem), and keys are kept long enough to cover all attempts (24 hours, for example). Serious payment APIs all accept a header of this kind.
The circuit breaker
A circuit breaker watches failures towards a service. After too many failures, it opens: calls fail immediately, without even contacting the service, which lets it recover and frees the caller. After a rest period, it becomes half-open: it lets one trial call through. Success: it closes again. Failure: it opens again.
Mini-lab: observing jitterPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: a circuit breaker
Write a class CircuitBreaker(threshold, rest) with a method call(function, now):
- closed state: call the function; after
thresholdconsecutive failures, switch to open; - open state: refuse immediately (
"refused"), unlessrestseconds have passed since opening: then switch to half-open; - half-open state: one trial call; success → closed, failure → open again.
Test it with a service that fails from t = 0 to t = 5, then responds normally.
Hint 1
state, failures (consecutive) and opened_at.Hint 2
try / except: an exception counts as a failure.Show the solution and common mistakes
class CircuitBreaker:
def __init__(self, threshold, rest):
self.threshold, self.rest = threshold, rest
self.state, self.failures, self.opened_at = "closed", 0, None
def call(self, function, now):
if self.state == "open":
if now - self.opened_at < self.rest:
return "refused"
self.state = "half-open"
try:
result = function(now)
except Exception:
self.failures += 1
if self.state == "half-open" or self.failures >= self.threshold:
self.state, self.opened_at = "open", now
return "failed"
self.state, self.failures = "closed", 0
return result
def service(t):
if t < 5:
raise TimeoutError("no response")
return "ok"
cb = CircuitBreaker(threshold=3, rest=4)
for t in range(12):
response = cb.call(service, t)
print(f"t={t:>2} {response:<7} → {cb.state}")
t= 0 failed → closed
t= 1 failed → closed
t= 2 failed → open
t= 3 refused → open
t= 4 refused → open
t= 5 refused → open
t= 6 ok → closed
t= 7 ok → closed
t= 8 ok → closed
t= 9 ok → closed
t=10 ok → closed
t=11 ok → closed
After the first three failures, the circuit opens; during the rest period, calls are refused instantly (the service is not even contacted). At t = 6, the trial call succeeds and the circuit closes.
Common mistakes:
- Counting 400 errors as service failures: one client's invalid request would open the circuit for everyone.
- Letting all calls through in half-open state: the restarting service suddenly receives all the accumulated traffic.
- Forgetting to reset
failuresto zero after a success: the circuit opens on old, scattered failures.
Summary
- 1Every remote call has a timeout, shorter along the call chain.
- 2Only transient errors are retried, with exponential backoff, jitter and a limited number of attempts.
- 3An idempotency key lets you retry a sensitive operation without running it twice.
- 4Retries at every layer multiply and turn a slowdown into an outage.
- 5A circuit breaker quickly refuses calls to a failing service, then tests it carefully.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.