Skip to content
mentoor

Topic 2 of 5 · 5 min read

Timeouts, retries and idempotency

Goal: Identify a missing timeout or a non-idempotent retry in AI-written integration code and specify the fix.

Every call that leaves your process needs a timeout, and every retry needs proof that doing the work twice is safe. AI code usually has neither, or it has a retry loop that is worse than none.

Check yourself · 1 of 3

Why is a retry around a payment request dangerous without an idempotency key?

Choose one answer

Why it matters

An HTTP client with no timeout can wait forever. One slow dependency then ties up every worker and the whole service stalls. The opposite fix, an agent adding "retry three times" to a call that creates a charge, can bill a customer three times when the first request actually succeeded but its response was lost.

How to check it

  1. Find every outbound call: HTTP, database, queue, SDK. Is a timeout set, for connect and for the whole request? Many libraries default to none, so check the default rather than assuming.
  2. Decide what is retryable. Reads and timeouts are usually fine. A 400 validation error will never succeed on retry. A 429 or 503 may, if you wait.
  3. Check idempotency. Idempotent means that doing it twice has the same effect as doing it once. Sending an email, creating an order and charging a card are not idempotent unless the request carries a unique key that the server uses to detect duplicates. Payment APIs such as Stripe accept an idempotency key header for this.
  4. Check the backoff. Wait longer after each failure, cap the wait, add random jitter so thousands of clients do not retry in the same instant, and stop after a small number of attempts.

Before and after

def charge(order):
    for _ in range(5):
        try:
            return requests.post(PAY_URL, json=order.payload)
        except Exception:
            pass

There is no timeout, no wait, no cap on total time, and a repeated POST that may charge up to five times. A reviewed version:

def charge(order):
    for attempt in range(3):
        try:
            return requests.post(
                PAY_URL,
                json=order.payload,
                headers={"Idempotency-Key": order.id},
                timeout=(3, 10),
            )
        except (requests.ConnectTimeout, requests.ReadTimeout):
            time.sleep(random.uniform(0, 2 ** attempt))
    raise PaymentUnavailable(order.id)

What goes wrong

  • Retry storms. Tight loops with no jitter hammer a service that is already struggling.
  • Stacked retries. A retry at three layers multiplies attempts: 3 x 3 x 3 calls for one user action.
  • Retrying the unretryable. Bad input or an auth error is retried until the budget is gone.
  • Timeout longer than the caller's. The caller gives up first, and the work continues unseen.

Examples

The double email

for (let i = 0; i < 3; i++) {
  try {
    await mailer.send(welcomeEmail);
    break;
  } catch {}
}

If the mail server accepts the message but the acknowledgement times out, the loop sends it again. The user gets three welcome emails. Store a welcome_sent_at flag, or send with a message id the provider de-duplicates.

No timeout on the default client

resp = requests.get(url)

The requests library waits indefinitely unless timeout is passed. Add timeout=(3, 10) and handle Timeout explicitly.

Key points

  • Set an explicit connect and total timeout on every outbound call; do not trust library defaults.
  • Retry only errors that can succeed later, such as timeouts, 429 and 503, never validation errors.
  • A retry is safe only if the operation is idempotent, usually through a unique idempotency key.
  • Use capped exponential backoff with random jitter and a small maximum number of attempts.
  • Count retries across layers, so one user action does not become dozens of calls.

Common mistakes

  • Adding a retry loop to a POST without an idempotency key.
  • Retrying with sleep(1) in a fixed loop and calling it backoff.
  • Setting a timeout on the HTTP call but not on the database or queue call next to it.
  • Retrying every exception type, including bugs in your own code.

Check yourself · 2 of 3

What is jitter in a retry strategy?

Choose one answer

Check yourself · 3 of 3

An agent wrote requests.get(url) for a partner API. What is the most important fix?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic