Skip to content
AgenticAIWiki
  1. Learn
  2. Part 13
  3. 68. Serving patterns
  4. 68.3

Lesson 68.3 · 3 of 5 · 4 min read · Reviewed 24 Nov 2026

Idempotency and retries at scale

By the end, you can

  • Make model-backed operations safe to retry.
  • Use idempotency keys and deduplication at scale.

Chapter 63 introduced idempotentIdempotency: The property that doing an operation twice has the same effect as doing it once. retries inside one agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done.. In a busy service, retries come from everywhere: queues redeliver, webhooks repeat, users double-click.

The rule

Any step with an effect outside the model must be safe to run twice.

How

  1. Idempotency keyIdempotency key: A unique id sent with a write request so the server can ignore duplicate retries of the same request. per operation. For example refund:{order_id}:{request_id}. Pass it to the downstream system if it supports one.
  2. Record completion. Before or as part of the effect, write the key to a store. On retry, check first.
  3. Retry the cheap, safe part. Re-running a model call costs tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. but changes nothing outside. Re-sending an email changes the world.
job --> model decides "refund 40" --> check key --> done already? skip
                                                    not done? refund, save key

Retrying model calls

  • Retry rate limit and overload errors with exponential backoffExponential backoff: Waiting longer after each failed retry, for example 1, 2, 4 then 8 seconds. and jitterJitter: Randomness added to retry delays so clients do not all retry at the same instant., and honour any retry-after header.
  • Don’t retry most 4xx errors: a bad request stays bad.
  • Cap total attempts and total time. After that, fail the job visibly.

Deduplicate inputs

Webhooks and queues can deliver the same message twice. Keep a short-lived record of message ids already handled, and drop repeats at the door.

Key points

  • At scale, retries happen constantly: network blips, worker restarts, duplicate webhooks.
  • A retry must not double an effect: give each operation an idempotency key and record completion.
  • Separate the model call (safe to repeat, costs money) from side effects (must happen once).
Hands-on labRuns in the Playground

Make a refund job safe to retry

Stop a crashed and retried job from refunding a customer twice.

You will have: A handle() function with a stable idempotency key, checked by both your job store and the payment call.

Steps

  1. Run the starter: a crash, a retry and a duplicate delivery issue 3 refunds.
  2. Build the key only from stable fields of the job.
  3. Make the payment provider return the earlier result for a repeated key.
  4. Run again: the crash still happens, but only one refund is issued.
  5. Explain why the model call in a job may be repeated but the refund may not.

Done when

  • refunds issued prints 1.
  • Attempts 2 and 3 return the same refund_id.
  • The key contains no attempt number or random part.

Open in the Playground No API key needed.

Starter code (Python)
# Make a refund job safe to retry with an idempotency key.
class Payments:
    def __init__(self):
        self.refunds, self.by_key = [], {}

    def refund(self, order_id, amount, idempotency_key):
        # TODO: if this idempotency_key was seen before, return the earlier result
        r = {"refund_id": f"rf-{len(self.refunds) + 1}", "order_id": order_id, "amount": amount}
        self.refunds.append(r)
        self.by_key[idempotency_key] = r
        return r


payments = Payments()
done = {}  # our own record of completed jobs


def handle(job, attempt, crash_after_refund=False):
    # TODO: the key must be the same on every attempt. This one is not.
    key = f"refund:{job['order_id']}:attempt-{attempt}"
    if key in done:
        return done[key]
    result = payments.refund(job["order_id"], job["amount"], idempotency_key=key)
    if crash_after_refund:
        raise RuntimeError("worker crashed before marking the job done")
    done[key] = result
    return result


job = {"order_id": "88412", "amount": 450}
try:
    handle(job, attempt=1, crash_after_refund=True)
except RuntimeError as e:
    print("attempt 1:", e)
print("attempt 2:", handle(job, attempt=2))
print("attempt 3 (duplicate delivery):", handle(job, attempt=3))
print("refunds issued:", len(payments.refunds))
Show a solution
# Make a refund job safe to retry with an idempotency key.
class Payments:
    def __init__(self):
        self.refunds, self.by_key = [], {}

    def refund(self, order_id, amount, idempotency_key):
        if idempotency_key in self.by_key:  # the provider recognises a repeat
            return self.by_key[idempotency_key]
        r = {"refund_id": f"rf-{len(self.refunds) + 1}", "order_id": order_id, "amount": amount}
        self.refunds.append(r)
        self.by_key[idempotency_key] = r
        return r


payments = Payments()
done = {}  # our own record of completed jobs


def handle(job, attempt, crash_after_refund=False):
    key = f"refund:{job['order_id']}"  # stable across every attempt of this job
    if key in done:
        return done[key]
    result = payments.refund(job["order_id"], job["amount"], idempotency_key=key)
    if crash_after_refund:
        raise RuntimeError("worker crashed before marking the job done")
    done[key] = result
    return result


job = {"order_id": "88412", "amount": 450}
try:
    handle(job, attempt=1, crash_after_refund=True)
except RuntimeError as e:
    print("attempt 1:", e)
print("attempt 2:", handle(job, attempt=2))
print("attempt 3 (duplicate delivery):", handle(job, attempt=3))
print("refunds issued:", len(payments.refunds))

Do it Practise backoff and retries in the Playground. No API key needed.

Quick checkA worker crashed after issuing a refund but before marking the job done. The job is retried. What prevents a second refund?
How sure are you?
Pick an answer and how sure you are