BeginnerLesson 4 of 127 min read

Errors, Retries and Idempotency: Surviving a Flaky API

Handle failures of an unreliable API: classify errors, retry only what is safe with exponential backoff and jitter, honour Retry-After, and prevent double charges with an idempotency key, demonstrated against a server that fails on purpose.

In this lesson you will

  • Tell transient from permanent errors
  • Retry with exponential backoff and jitter
  • Honour Retry-After
  • Use idempotency keys for non-idempotent calls

About 28 minutes

The customer who was charged twice

The payment API of Noor’s shop was slow one Friday evening. Her program sent a charge, waited, gave up, and sent it again. The first request had in fact succeeded, and the customer was charged twice. Networks and servers fail, and an integration must expect it: a request can fail before it reaches the server, after the server has done the work but before the reply returns, or in the middle. From the client’s side, a timeout looks identical in all three cases, so you cannot know whether the work was done.

Two practices handle this. First, retry only what is safe and likely to help. Transient failures, timeouts, 502, 503, 504 and 429 (too many requests), may succeed on a second attempt. Permanent ones, 400, 401, 403, 404 and 422, will fail again, and retrying them wastes time. Retries must be spaced out: exponential backoff doubles the wait after each failure, 0.5, 1, 2, 4 seconds, up to a cap, and jitter, a random fraction of the wait, stops thousands of clients from retrying in a synchronised wave. When a server sends a Retry-After header, obey it. Second, make non-idempotent calls safe to repeat with an idempotency key: the client generates a unique key for each logical operation and sends it in a header, and the server remembers the result for that key, so a repeated request returns the original result and does not charge again.

Status or event Retry? Why
Timeout, connection reset Yes, with a key for writes Transient, outcome unknown
429 Too Many Requests Yes, after Retry-After You are being throttled
500, 502, 503, 504 Yes, with backoff Server trouble
400, 422 No Your request is wrong
401, 403 No (refresh a token once) Credentials or rights
404 No It does not exist
import json, threading, random, urllib.request, urllib.error, http.client
from http.server import BaseHTTPRequestHandler, HTTPServer

state = {"flaky_calls": 0, "charges": [], "by_key": {}, "lose_reply": 1}
class Provider(BaseHTTPRequestHandler):
    def reply(self, code, obj, extra=None):
        b = json.dumps(obj).encode(); self.send_response(code); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(b)))
        for k, v in (extra or {}).items(): self.send_header(k, v)
        self.end_headers(); self.wfile.write(b)
    def do_GET(self):
        state["flaky_calls"] += 1; n = state["flaky_calls"]
        if n <= 2: return self.reply(503, {"error": "unavailable"})
        if n == 3: return self.reply(429, {"error": "slow down"}, {"Retry-After": "2"})
        self.reply(200, {"ok": True, "attempt": n})
    def do_POST(self):
        body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        key = self.headers.get("Idempotency-Key")
        if key and key in state["by_key"]: return self.reply(200, state["by_key"][key])
        charge = {"id": "ch_%d" % (len(state["charges"]) + 1), "amount_cents": body["amount_cents"]}
        state["charges"].append(charge)
        if key: state["by_key"][key] = charge
        if state["lose_reply"] > 0:                     # the work is done, but the reply never arrives
            state["lose_reply"] -= 1; self.connection.close(); self.close_connection = True; return
        self.reply(201, charge)
    def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), Provider); base = "http://127.0.0.1:%d" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()

rng = random.Random(7)
delays = []
def backoff(attempt, retry_after=None, base_s=0.5, cap=8.0):
    return float(retry_after) if retry_after else rng.uniform(0, min(cap, base_s * 2 ** attempt))      # "full jitter"
def request(method, path, data=None, headers=None, sleep=delays.append, tries=5):
    for attempt in range(tries):
        try:
            req = urllib.request.Request(base + path, data=json.dumps(data).encode() if data else None, method=method, headers={"Content-Type": "application/json", **(headers or {})})
            r = urllib.request.urlopen(req, timeout=2); return r.status, json.loads(r.read()), attempt + 1
        except urllib.error.HTTPError as e:
            if e.code not in (429, 500, 502, 503, 504): return e.code, json.loads(e.read()), attempt + 1       # permanent: do not retry
            sleep(backoff(attempt, e.headers.get("Retry-After")))
        except (http.client.RemoteDisconnected, ConnectionError, TimeoutError, urllib.error.URLError):
            sleep(backoff(attempt))
    raise RuntimeError("gave up after %d tries" % tries)
status, body, attempts = request("GET", "/status")
print("flaky GET: status", status, "after", attempts, "attempts | waits chosen:", [round(x, 2) for x in delays])
n_before = len(state["charges"])
status2, body2, attempts2 = request("POST", "/charges", {"amount_cents": 4200}, {"Idempotency-Key": "order-1001"})
print("charge with a key, first reply lost: status", status2, body2, "after", attempts2, "attempts | charges recorded by the provider:", len(state["charges"]) - n_before)
state["lose_reply"] = 1; n_before = len(state["charges"])
status3, body3, attempts3 = request("POST", "/charges", {"amount_cents": 4200})
print("same without a key: status", status3, "after", attempts3, "attempts | charges recorded by the provider:", len(state["charges"]) - n_before, "(double charge)")
print("DATA " + json.dumps({"get": [status, attempts], "delays": delays, "keyed": [status2, attempts2, 1], "plain": [status3, attempts3, len(state["charges"]) - n_before]}))
srv.shutdown()
flaky GET: status 200 after 4 attempts | waits chosen: [0.16, 0.15, 2.0]
charge with a key, first reply lost: status 200 {'id': 'ch_1', 'amount_cents': 4200} after 2 attempts | charges recorded by the provider: 1
same without a key: status 201 after 2 attempts | charges recorded by the provider: 2 (double charge)

The first test calls an endpoint that fails on purpose: it answers 503 twice, then 429 with Retry-After: 2, then succeeds. The client made 4 attempts and finally got status 200. The waits it chose were 0.16, 0.15, 2.00 seconds. For the 503 failures it used exponential backoff with full jitter, a random wait between 0 and 0.5 x 2 to the power of the attempt number, so the first wait lies between 0 and 0.5 and the second between 0 and 1.0. For the 429 it obeyed the server and waited exactly the 2 seconds in Retry-After, instead of guessing. The lesson records the waits and does not actually sleep, so that the program runs at once, but a real client would call time.sleep with these values.

The second test is the double-charge disaster in miniature. The server processes a charge request and then drops the connection without replying, which from the client looks like a timeout. The client cannot know that the charge exists, so it retries. With an idempotency key, “order-1001”, the retry returned the original result and the provider recorded 1 charge, although the client needed 2 attempts. The same scenario without a key made the retry create a second charge, so the provider recorded 2 charges for one order, exactly the Friday-evening bug. The key must identify the logical operation, such as the order number, and be stored with the order, so that a retry after a restart reuses it.

Independent check: the counts of charges come from the provider’s own ledger, which the client does not control, and show the difference between the keyed and the unkeyed call directly. The backoff waits are checked against the bounds from the formula: each must lie between zero and the cap for its attempt number, and the Retry-After wait must equal the header value. Note that the random jitter makes the exact numbers differ from run to run in real use. Here a seeded generator makes this lesson repeatable.

Check by hand: attempt 0 allows a wait up to 0.5 x 1 = 0.5 seconds, attempt 1 up to 0.5 x 2 = 1.0, attempt 2 up to 0.5 x 4 = 2.0, and the cap of 8 seconds is reached at attempt 4. Four attempts mean three failures and one success, matching the server’s script: 503, 503, 429, 200.

Never retry a charge without an idempotency key

A retried POST can do the work twice. If the API supports idempotency keys, always send one with writes, and if it does not, check the state before you retry.

Add jitter and a cap, and set timeouts

Without jitter, many clients retry together and overload a recovering server. Without a cap the waits grow without limit, and without a timeout a hung call stalls your program for ever.

About this course

Every program in this lesson was run while the course was written, with Python 3.13 (standard library only) against small mock APIs that the lesson itself starts on a local port, and cross-checked with curl, OpenSSL, Node.js or a second calculation. The services are invented stand-ins, not real vendors: always read the current documentation of the real API you use. Providers differ in how they implement idempotency keys and Retry-After, so read their documentation for the exact rules, including how long a key is remembered.

Practice

Add a maximum total waiting time to the client. Make the server fail with a 400 and check that the client does not retry. Generate the idempotency key from the order id, and test that two requests with the same order produce one charge.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which status is worth retrying?

  1. 503
  2. 404
  3. 422
  4. 401

Transient server trouble.

What does exponential backoff do?

  1. Retries instantly
  2. Stops after one try
  3. Randomises the URL
  4. Doubles the wait after each failure

Up to a cap.

What does jitter prevent?

  1. Slow responses
  2. Bad JSON
  3. Timeouts
  4. Many clients retrying in a synchronised wave

A random fraction of the wait.

What does an idempotency key do?

  1. Encrypts the request
  2. Speeds up the call
  3. Makes a repeated write return the original result
  4. Authenticates the user

No double charge.

What should the client do with Retry-After?

  1. Ignore it
  2. Retry at once
  3. Wait that long
  4. Stop for ever

The server knows best.

Summary

  • Retry transient errors, not permanent ones.
  • Use exponential backoff with jitter, a cap and timeouts, and honour Retry-After.
  • Make writes safe to repeat with idempotency keys.
  • Test with a server that fails on purpose.

Next lesson

Lesson 5 covers rate limits.

Questions

How many retries should I allow?

Typically three to five, with a total time limit. More retries rarely help and can make an outage worse.

Can I retry a GET?

Usually yes, since GET is safe and idempotent, with backoff. Be careful with endpoints that have side effects despite the method.

What is a circuit breaker?

A pattern that stops calling a failing service for a while, so that it can recover and your program fails fast. Libraries provide it, and the idea is worth knowing.

Progress is saved in this browser.