Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Keep an API up under load and make retries safe.
How can a client safely retry after losing a response to a write?
A timeout leaves the client uncertain whether the server completed its work. A stored idempotency key binds one logical operation to its result across repeated requests.
A POST creates job J for key K
The response is lost and the client retries with K
The service returns the original job J
A POST creates job J for key K
The response is lost and the client retries with K
The service returns the original job J
Given A POST creates job J for key K and The service returns the original job J, write down the missing step that connects them.
The response is lost and the client retries with K
Now take The response is lost and the client retries with K and the result above. Write an input and an implementation that could produce this trace.
A POST creates job J for key K. Check that your implementation produces the result shown above.
Should the client generate a new key after a timeout for the same operation?
Reuse the original key. A new key could make the server interpret the retry as a second operation.
A failed connection occurs after submission. A retry sends the old idempotency key and a changed body. Which of the server’s checks should distinguish it from a repeat?
Compare the retry payload with the payload recorded under the caller and key. A mismatch is a conflict. Reusing the key with the same logical payload can identify the original operation.
Check this when debugging. Calling APIs without timeouts.
Networks drop packets, servers restart and providers rate-limit you, all on an ordinary day. Model APIs add long, expensive calls and frequent 429 and 529 answers when demand peaks. What separates a fragile integration from a solid one is how it behaves when things go wrong. It needs limits that keep one client from swamping everyone, retries that help instead of making things worse, and retries that can't charge a customer twice. A model API adds one more limit you must respect as a client: a budget of tokens, not only of requests.
Wait a little, longer each time, then retry
429 means slow down. Waiting and retrying with growing delays (exponential backoff), plus a bit of randomness, gets through without making the overload worse.
This rests on Shipping an LLM app, where you wrote a RateLimiter, and LLMs in automations, where you retried with backoff. Here the same ideas get their full mechanics, and a third one joins them.
Without limits, one buggy script in a loop can take your API down for everyone, or run up your model bill overnight. A rate limiter caps how many requests each key, user or IP address may make. The most common algorithm is the token bucket. Picture a jar of arcade tokens. You spend one per game, and an attendant drops a fresh one in every few seconds. If you have saved some up, you can play several games in a row. Once the jar is empty, you wait.
capacity tokens. It starts full.rate per second, never above capacity.That allows short bursts (up to the capacity) while holding the long-run average to the rate. The picture runs a bucket that holds 3 and refills 1 a second, with seven requests.
Three requests at the start empty the bucket. The next two are refused. By 1.5 s a token and a half has dripped back.
IDEMPOTENT = {"GET", "PUT", "DELETE"}
def safe_to_retry(method, has_idempotency_key=False):
return method in IDEMPOTENT or has_idempotency_key
print(
safe_to_retry("PUT"),
safe_to_retry("POST"),
safe_to_retry("POST", has_idempotency_key=True),
)True False True
A PUT sets the resource to the same state however many times it arrives. A plain POST may create a second order or charge a card twice. A POST becomes safe to retry once it carries an idempotency key, the last pattern in this lesson.
When a phone line is busy, you redial. When the number has been disconnected, redialing won't help. Retrying helps with temporary failures and only wastes time on permanent ones:
| retry? | responses |
|---|---|
| yes | connection errors and timeouts, 429, 502, 503, 504, and a model API's 529 "overloaded" |
| usually | 500 (sometimes temporary) |
| no | 400, 401, 403, 404, 422: the same request will fail the same way |
Retrying instantly hammers a server that is already struggling, so wait longer each time: exponential backoff doubles the delay (0.5 s, 1 s, 2 s, 4 s) up to a cap. That is not enough on its own. If a thousand clients failed at the same moment, they retry at the same moments, in synchronized waves, the thundering herd. Adding randomness, called jitter, spreads them out. With full jitter, each delay is a random amount between zero and the backoff value. If the server sent Retry-After, wait that long instead, since it knows better than your formula.
Write a sentence or two, then compare it with a good answer in the lesson.
The TokenBucket class from the picture is in this lesson's setup. It reads the clock from an argument, so a cell can feed it any times. First compare its answers with the widget's, then draw its level as a plot.
The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.
import random import time import requests BASE = "https://api.gradient.test" class TokenBucket: def __init__(self, capacity, rate, now): self.capacity, self.rate = capacity, rate self.tokens, self.updated = capacity, now def allow(self, now): elapsed = now - self.updated self.tokens = min(self.capacity, self.tokens + elapsed * self.rate) self.updated = now if self.tokens >= 1: self.tokens -= 1 return True return False def retry_after(self): return max(0.0, (1 - self.tokens) / self.rate)
import matplotlib.pyplot as plt times = [0.0, 0.1, 0.2, 0.3, 0.4, 1.5, 1.6] bucket = TokenBucket(capacity=3, rate=1.0, now=0.0) levels, refused = [], [] for t in times: ok = bucket.allow(t) levels.append(bucket.tokens) if not ok: refused.append((t, bucket.tokens)) wait = f"429, retry after {bucket.retry_after():.1f}s" print(f"t={t:.1f}s", "allowed" if ok else wait) fig, ax = plt.subplots(figsize=(6, 3)) ax.step(times, levels, where="post", label="tokens after each request") ax.plot([t for t, _ in refused], [v for _, v in refused], "rx", label="refused (429)") ax.set_xlabel("time (s)") ax.set_ylabel("tokens in the bucket") ax.legend()
The level falls to 0 at the third request, stays near zero while requests keep arriving faster than one a second, and climbs back once there is a gap. Change capacity to 5 and rerun: more of the opening burst gets through, but the later average does not change.
Write next_wait(status, headers, attempt, base=1.0): return None when the status shouldn't be retried (anything except 429, 500, 502, 503, 504 and 529). Otherwise, if headers has a Retry-After of whole seconds, return that number as a float; if not, return base * 2 ** attempt.
Uses the setup above, 23 lines.
def next_wait(status, headers, attempt, base=1.0): return base * 2 ** attempt print( next_wait(429, {"Retry-After": "7"}, 0), next_wait(422, {}, 0), next_wait(503, {}, 2), )
422 Unprocessable Content from an API. What should the retry logic do?Not retry: fix the request, because the same body will fail the same way
4xx errors other than 429 mean the request itself is wrong. Retrying only adds load and delay.
Now the crowd. This cell gives 1,000 clients that failed together the same third retry (a 4 s backoff), with and without full jitter, and plots when they come back.
Uses the setup above, 23 lines.
import matplotlib.pyplot as plt rng = random.Random(1) backoff = 4.0 none = [backoff] * 1000 full = [backoff * rng.random() for _ in range(1000)] fig, ax = plt.subplots(figsize=(6, 3)) ax.hist(full, bins=16, range=(0, 4.5), label="full jitter") ax.hist(none, bins=16, range=(0, 4.5), label="no jitter") ax.set_xlabel("seconds after the failure") ax.set_ylabel("clients retrying") ax.legend() slices = [0] * 8 for w in full: slices[int(w / 0.5)] += 1 print("no jitter: 1000 clients at 4.0 s") print("full jitter: busiest half-second slice has", max(slices), "clients")
The tower is one bar of 1,000 clients. Jitter turns it into a flat spread of about 125 per half-second, an eighth of the load at any moment.
Here is the hard case. Your client POSTs "charge $50". The server charges the card, but the response is lost, and the client sees a timeout. Retrying might charge twice; not retrying might mean no charge. The fix, popularized by Stripe, works like an order number on a ticket. The client makes a unique idempotency key for each logical operation, often a random UUID, and sends it in a header. The server remembers each key with the response it gave:
Now retrying is always safe: the operation takes effect once, however many times the request arrives. The stepper runs the idea on a store with one charge function. (The exercise adds the body check from rule 3.)
Two plain POSTs, then two POSTs that share an Idempotency-Key. The practice shop behaves as the picture said.
Uses the setup above, 23 lines.
order = {"sku": "TEE-001", "quantity": 2}
url = f"{BASE}/v1/orders"
requests.post(f"{BASE}/v1/reset")
a = requests.post(url, json=order)
b = requests.post(url, json=order)
print("no key:", a.json()["id"], b.json()["id"])
headers = {"Idempotency-Key": "k-1"}
c = requests.post(url, json=order, headers=headers)
d = requests.post(url, json=order, headers=headers)
print("with key:", c.json()["id"], d.json()["id"], d.headers.get("Idempotent-Replayed"))Two plain POSTs made two orders. The second POST with the same key returned the first order's id, and a header said it was replayed.
When each layer of a system retries its call to the next, the attempts multiply. Write worst_case_calls(attempts): attempts lists how many times each layer tries, from the top down. Return the most calls the bottom service can receive for one user request: the product of all of them.
Uses the setup above, 23 lines.
def worst_case_calls(attempts): return sum(attempts) print(worst_case_calls([3, 3, 3]))
Write a sentence or two, then compare it with a good answer in the lesson.
10
The bucket never holds more than its capacity, so a full bucket allows a burst of 10. The other 5 get 429s.
bucket = TokenBucket(capacity=2, rate=1.0, now=0.0) print([bucket.allow(t) for t in [0.0, 0.2, 0.4, 1.5]])
[True, True, False, True]
The bucket starts with 2 tokens. The first two requests spend them; at 0.4 s only 0.4 tokens have dripped back, so it is refused; by 1.5 s there are 1.5 tokens, enough for one.
A model API is rate limited in more than one way. It counts requests a minute and tokens a minute, and a reply can run out one budget while the other has room. Every reply carries headers that show where you stand, and a 429 adds Retry-After. Providers also answer 529 when they are overloaded, which is temporary and retryable, and every response carries a request-id header you quote in a bug report. The practice API has a route that behaves like this, so you can read a 429 from Python. It starts with a full bucket of 3.
Uses the setup above, 23 lines.
requests.post(f"{BASE}/v1/reset") for i in range(5): r = requests.get(f"{BASE}/v1/limited") left, wait = r.headers.get("X-RateLimit-Remaining"), r.headers.get("Retry-After") print(r.status_code, left, wait)
Three 200s empty the bucket, and the fourth and fifth get 429 with Retry-After. A client that reads the header and sleeps for that long always gets through. This next cell budgets tokens a day for each key, the guard a service puts in front of a model so one user cannot spend everything. It refuses a call that would pass the limit, before the call is made.
Uses the setup above, 23 lines.
class DailyBudget: def __init__(self, limit): self.limit, self.used = limit, {} def charge(self, key, tokens): used = self.used.get(key, 0) if used + tokens > self.limit: return False self.used[key] = used + tokens return True budget = DailyBudget(1000) print(budget.charge("ana", 600), budget.charge("ana", 600), budget.charge("raj", 600)) print(budget.used)
Four failures account for most pager alerts here. A retry storm: a slow dependency, retries at every layer, and the load multiplies until nothing answers. A missing timeout: the default in requests is none, so one stuck call ties up a worker; always pass timeout=(3.05, 60), a short connect and a long read, since model calls can take a minute. A double charge: a POST retried with no idempotency key. A budget with no cap: a loop in a script spends a month of tokens overnight, which is why a service keeps a per-key budget as the cell above does. Two patterns limit the damage when a dependency stays down: a circuit breaker stops calling a failing dependency for a while, and graceful degradation falls back to something useful, such as a smaller model when the premium one is overloaded.
Goes deeper in: Async HTTP clients sends many calls under a limit, Webhooks and events retries events from the provider's side, and Caches, queues and background jobs moves slow work off the request.
POST /payments and retries with the same Idempotency-Key. The first request did succeed. What should the server do?Return the stored result of the first request, without charging again
The key ties the retry to the first attempt. The client gets the same answer, and the customer is charged once.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What does a token bucket allow that a simple "N requests per minute" counter handles poorly?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write