Skip to content
Index Ai Academy
Phase 8 · Security & reliability

Rate limits, retries and idempotency

Keep an API up under load and make retries safe.

About 45 minutes · Model names checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers7

First principles

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.

  1. Starting point

    A POST creates job J for key K

  2. What changes

    The response is lost and the client retries with K

  3. Result

    The service returns the original job J

Compare all three steps
  1. Starting point

    A POST creates job J for key K

  2. What changes

    The response is lost and the client retries with K

  3. Result

    The service returns the original job J

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

A POST creates job J for key K. Check that your implementation produces the result shown above.

Try it on a new case

Should the client generate a new key after a timeout for the same operation?

Show worked reasoning

Reuse the original key. A new key could make the server interpret the retry as a second operation.

Try a different case

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?

Show reasoning for this case

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.

Run, change, and build

Check this when debugging. Calling APIs without timeouts.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. Should the client generate a new key after a timeout for the same operation?

Why it matters

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.

What you'll be able to do

  • Work out a token bucket's level at a given time, and the Retry-After a refused request is told
  • Set timeouts, and retry only failures that can succeed on a second try
  • Space retries with exponential backoff and jitter, and see why jitter matters for a crowd of clients
  • Make POST requests safe to retry with idempotency keys, and keep a per-key token budget for a model API
Quick check
A model API answers 429 Too Many Requests. What should your code do?
  1. Switch to sending the request over plain HTTP
  2. Give up and show the user an error at once
  3. Wait a little, longer each time, then retry
  4. Retry immediately, as fast as it can
Show the answer

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.

The idea: a bucket, a wait and a saved answer

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.

  • Each client has a bucket holding up to capacity tokens. It starts full.
  • Tokens drip back in at a steady rate per second, never above capacity.
  • Each request spends one token. If the bucket is empty, the request is refused with 429 Too Many Requests, and a Retry-After header says how many seconds until one token is back.

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.

Try it now

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.

Quick check
Recall: repeating a GET, PUT or DELETE is harmless, and repeating a POST isn't. What does this print?
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),
)
  1. True False False
  2. True True True
  3. False False True
  4. True False True
Show the answer

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.

Retries: which, how long, and the crowd

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
yesconnection errors and timeouts, 429, 502, 503, 504, and a model API's 529 "overloaded"
usually500 (sometimes temporary)
no400, 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.

In your own words
How does a token bucket limit requests, and why does jitter matter when many clients retry?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: the bucket, the schedule and the saved answer

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.

Setup (runs before every cell) · 23 lines

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.

Drill

Retry, and how long to wait

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),
)
In the lesson, your code is checked as you write it.
Quick check
Your code gets 422 Unprocessable Content from an API. What should the retry logic do?
  1. Not retry: fix the request, because the same body will fail the same way
  2. Wait for the Retry-After header, then send the same request again
  3. Retry immediately, up to 10 times, in case the server was busy
  4. Retry with exponential backoff, waiting a little longer each time
Show the answer

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.

Safe to retry: the saved answer

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:

  1. New key: do the work, save the key with the response, return it.
  2. Same key, same body: return the saved response without doing the work again.
  3. Same key, different body: a client bug, so refuse it.

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.)

Worked example

The practice shop's orders, with and without a key

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"))
In the lesson you can change this and run it.

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.

Drill

Retries at every layer multiply

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]))
In the lesson, your code is checked as you write it.
In your own words
What does an idempotency key do, and what must the server store for it?

Write a sentence or two, then compare it with a good answer in the lesson.

Quick check
A token bucket has capacity 10 and refills 2 tokens a second. A client idle for a minute sends 15 requests at once. How many succeed?
  1. 10
  2. 2
  3. 0
  4. 15
Show the answer

10

The bucket never holds more than its capacity, so a full bucket allows a burst of 10. The other 5 get 429s.

Quick check
What does this print?
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]])
  1. [True, True, True, True]
  2. [True, True, False, True]
  3. [True, False, False, True]
  4. [True, True, False, False]
Show the answer

[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.

In AI and ML systems: limits you meet as a client

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)
It runs right here in your browser, with nothing to install.

Where this shows up in an engineer's week

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.

Quick check
A client times out on POST /payments and retries with the same Idempotency-Key. The first request did succeed. What should the server do?
  1. Ignore the retry, sending back nothing so the client gives up
  2. Charge again, since a retry is a new request from the client
  3. Answer 409 and make the client check the payment by hand
  4. Return the stored result of the first request, without charging again
Show the answer

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.

In your own words
How do retries bring a service down, and what three rules keep them safe?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 5 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

What does a token bucket allow that a simple "N requests per minute" counter handles poorly?

  1. Short bursts up to the capacity, while holding the average to a steady rate
  2. Unlimited requests at night, when the bucket refills at a much faster rate
  3. Requests without an API key, by giving each new client some free tokens
  4. Retries without backoff, since a failed request hands back the token it used

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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