Skip to content

Module 03 · Lesson 3.5

Tool Errors, Retries, Timeouts and Idempotency

45 minUpdated 18 Nov 2026Part of Tools, APIs and Function Calling · AI Agent Development
On this page
  1. What you will learn
  2. The three kinds of tool failure
  3. Timeouts and backoff: how long to wait, and how often to retry
  4. Why a timeout does not mean the action failed
  5. Idempotency and idempotency keys: make a retry harmless
  6. Retry a lost reply safely with Python
  7. Set limits and hand over when retries run out
  8. Conclusion and your next step
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. Frequently asked questions
  14. References

You press the lift button and nothing lights up. Did the lift hear you? You cannot tell. If you press again, the worst case is a wasted second. Now imagine the button orders a pizza. Pressing it twice could put two pizzas on your doorstep, and you will pay for both.

Tools used by an AI agent fail in the same quiet way. Calls get lost, services get busy and replies never arrive. This lesson teaches you to sort failures into three kinds, to retry only when it is safe, and to make sure a retried action never happens twice. Most of it needs no coding. A short Python example at the end shows the whole idea in action.

What you will learn

  • Sort a tool failure into bad input, a temporary problem or a permanent problem.
  • Explain timeouts, retries and backoff in plain words.
  • Describe why retrying a write tool can create a duplicate, and how an idempotency key prevents it.
  • Run a short Python script that retries a lost reply and creates only one record.

Before you start

The three kinds of tool failure

A tool is a small function the agent can call, such as lookup_order. A tool call can go wrong in many ways. The good news is that the right response depends on only three things.

In this program we use Quillfeather Cycles, a made-up online bike shop. Its agent has two tools. lookup_order(order_id) only reads. request_return(order_id, reason) creates a return request that staff must approve. Both can fail.

Kind of failureExampleRetry?What the agent should do
Bad inputThe order ID is "1042" instead of "QF-1042".No. The same input will fail again.Return an error observation so the model can fix the input.
Temporary problemA timeout, or the service says it is busy.Yes, a few times, with waits in between.Retry with limits. If it still fails, report the error and hand over.
Permanent problemThe service is switched off, or the agent is not allowed to use the tool.No. Waiting will not fix it.Stop at once and hand over to a person.
Ask one question first: will trying again change anything?

Bad input: give the model a clear error

When the agent sends a bad value, the tool should not crash. It should return an error observation. That is a short message, such as {"error": "order_id must look like QF-1234"}, that goes back to the model like any other tool result.

The model reads it, fixes the value and tries once more. You saw this pattern in Designing Tool Schemas and Validating Arguments. A good message says what was wrong and what a correct value looks like.

Temporary problems: retry a few times

Some problems go away by themselves. A service may be restarting. A network may be slow for a moment. A short wait and another try often works.

Permanent problems: stop and hand over

Other problems will not go away. The password is wrong, the tool was removed, or the agent has no permission. Retrying only wastes time. The agent should stop, say what happened in plain words and hand the customer to a person.

Not sure which kind you have? Look at the error code first. The list of HTTP response status codes (opens in a new tab) is a helpful map, and our guide to Troubleshooting LLM API Errors covers the common ones.

Timeouts and backoff: how long to wait, and how often to retry

A timeout is a limit on how long you will wait for a reply. When the time is up, you stop waiting and treat the call as failed.

Think of a restaurant kitchen. You order a soup and decide that if it is not on your table in 20 minutes, you will ask the waiter. Without that rule you would sit there all evening. A tool call with no timeout is the same. The agent can hang on one call, and your customer waits with it.

Timeout
The longest time you will wait for one reply. After that, you give up on that attempt.
Retry
Making the same call again after a failure.
Backoff
Waiting a little longer before each retry. For example, 1 second, then 2, then 4. It gives a busy service room to recover instead of hitting it again and again.

Most code libraries let you set a timeout on a call. The Python standard library, for example, accepts a timeout in urllib.request (opens in a new tab). Always set one. Never leave it empty.

Backoff matters when many users fail at once. If every client retries immediately, a busy service gets even busier. Some services publish limits on how many calls you may make, such as the Google rate limits (opens in a new tab). Waiting longer each time keeps you inside those limits.

Why a timeout does not mean the action failed

Here is the part that surprises most beginners. A timeout means you did not get an answer. It does not mean the action did not happen.

Think of posting a letter to a friend and never hearing back. Maybe the letter was lost. Maybe your friend got it, and the reply was lost. From your side, both look the same.

How a retry creates a duplicate
  1. Agent calls request_return

    For order QF-1044

  2. Service saves RT-1

    The return request now exists

  3. Reply is lost

    The agent sees a timeout

  4. Agent retries

    It thinks nothing happened

  5. Service saves RT-2

    Two return requests for one order

The first request worked. Only the reply was lost.

Staff now have two return requests to check, and the customer may get two emails. With a payment tool, it could be two charges. This is why the module quiz warns about retrying tools that create things.

Idempotency and idempotency keys: make a retry harmless

A good fix is to make the repeat harmless. The word for this is idempotent. An action is idempotent when doing it twice has the same effect as doing it once.

A lift button is a good everyday example. The first press calls the lift. The second press changes nothing, because the lift is already coming. Compare that with a vending machine. Press "buy" twice and you get two snacks. The lift button is idempotent. The vending machine is not.

Idempotent
Doing the same request twice has the same effect as doing it once.
Idempotency key
A unique ID that you send with a request. If the service sees the same ID again, it knows the request is a repeat and gives back the first result instead of doing the work twice.

Think of the ID as a ticket number at a deli counter. If you hold up the same ticket twice, the clerk knows it is the same order and does not make a second sandwich.

How to use an idempotency key

  1. Create one unique key for each real-world action, for example qf1044-damaged-001.
  2. Send that key with the first call.
  3. If the call times out, retry with the same key. Never create a new key for a retry.
  4. Use a new key only when you mean a genuinely new action.

The service has to support keys, so check its documentation. Some web services let you choose safe repeats this way. Stripe's page on idempotent requests (opens in a new tab) shows one real service that does. For the formal rules of web methods, see RFC 9110: HTTP Semantics (opens in a new tab) and the short MDN note on idempotent (opens in a new tab).

Retry a lost reply safely with Python

The script below runs offline. It has a fake returns service that saves the request and then times out before replying. A small client retries with backoff and the same key. Then we run it a second time with no key to see the problem.

Pythonsafe_retry.py
import time


class FakeReturnsService:
    """Saves every request, but the first reply is lost (a timeout)."""

    def __init__(self):
        self.saved = {}      # idempotency key -> record
        self.records = []    # every return request that exists
        self.calls = 0

    def request_return(self, order_id, reason, key=None):
        self.calls += 1
        if key in self.saved:
            return self.saved[key]  # a repeat: same answer, no new record
        record = {"return_id": f"RT-{len(self.records) + 1}", "order_id": order_id}
        self.records.append(record)
        if key is not None:
            self.saved[key] = record
        if self.calls == 1:
            raise TimeoutError("no reply in time")  # saved, but we never hear
        return record


def call_with_retries(service, key, max_tries=3):
    wait = 0.01
    for attempt in range(1, max_tries + 1):
        try:
            return service.request_return("QF-1044", "damaged", key)
        except TimeoutError:
            print(f"  attempt {attempt} timed out, waiting {wait} s")
            time.sleep(wait)
            wait *= 2  # backoff: wait longer each time
    return {"error": "request_return failed after 3 tries. Hand over to a person."}


for key in ("qf1044-damaged-001", None):
    service = FakeReturnsService()
    print("With key:" if key else "Without key:")
    print(" ", call_with_retries(service, key))
    print("  return requests saved:", len(service.records))

Standard library only. It prints the waits and sleeps for only a hundredth of a second.

What each part does

  • class FakeReturnsService is a pretend service. A class is a blueprint for an object that keeps its own data.
  • self.saved is a dictionary, a set of pairs. It remembers each key and the record made for it.
  • if key in self.saved spots a repeat. The service returns the old record and creates nothing new.
  • self.records.append(record) saves the new return request.
  • raise TimeoutError pretends the reply got lost. The request is already saved at this point.
  • call_with_retries tries at most max_tries times. The try and except lines catch the timeout so the program carries on.
  • wait *= 2 doubles the wait each time. That is backoff.
  • The last return is the final failure. It becomes an error observation plus a handover instead of a crash.
OutputCaptured from a real run
With key:
  attempt 1 timed out, waiting 0.01 s
  {'return_id': 'RT-1', 'order_id': 'QF-1044'}
  return requests saved: 1
Without key:
  attempt 1 timed out, waiting 0.01 s
  {'return_id': 'RT-2', 'order_id': 'QF-1044'}
  return requests saved: 2

With the key, the retry gets the first record back and only one return request exists. Without the key, the retry saves a second one, RT-2. The agent thinks it made one request. Staff see two.

Set limits and hand over when retries run out

Retrying forever is as bad as waiting forever. Set limits before you ship. Without them, one broken tool can keep your agent busy, and your bill growing, all night.

  • Maximum retries per call. Two or three is usual.
  • Maximum total time. Stop the whole attempt after, say, 30 seconds, even if you have tries left.
  • Timeout on each attempt. Never wait without a limit.
  • Only retry the right kinds of failure. Retry temporary problems. Do not retry bad input or permanent problems.

When the limits run out, do not let the program crash and do not stay silent. Turn the final failure into an error observation, then follow your handover rule. For example: the agent tells the customer "I could not finish your return request. A colleague will contact you", and a person is notified.

Retries are part of the step limit

In Task Decomposition and Planning Strategies you met the step limit, and the first agent lab calls it MAX_ROUNDS. It caps how many times the agent may loop. Tool retries have their own limit inside one tool call. Both limits live in your code, so the model cannot argue its way past them.

Keep the two apart. A retry repeats the same call after a lost reply. A new round is the model deciding what to do next. If a tool error comes back to the model as an observation, the model may try the tool again. That counts as a round, so MAX_ROUNDS still protects you.

Conclusion and your next step

Sort each failure first: bad input goes back to the model, temporary problems get a few retries with backoff, and permanent problems go to a person. Always set a timeout and a retry limit. Remember that a timeout does not tell you whether a write happened, so send an idempotency key with every write you might retry.

Your next step: pick one write tool in a system you know. Write down what would happen if its reply were lost and the call ran twice. Then continue to Practical Lab: Build an Agent That Uses Two Tools, where you put validation, timeouts and error observations into one working agent.

Want more background? Revisit Connecting REST APIs and Internal Services, or look up any unfamiliar word in the Glossary of AI Engineering and Agent Terms.

Common errors and how to fix them

The same return request appears twice.

Why it happens: The call timed out, and the code retried a write without an idempotency key.

Fix: Create one key per action in your own code and send the same key on every retry.

The agent hangs and the customer waits for minutes.

Why it happens: The tool call has no timeout.

Fix: Set a timeout on every call and a maximum total time for all retries.

The agent keeps sending the same bad order ID.

Why it happens: The code retries bad input, or the error message does not say what is wrong.

Fix: Do not retry bad input. Return an error observation that names the problem and shows a correct example.

A busy service gets slower after the agent starts retrying.

Why it happens: Every retry fires at once, with no waiting.

Fix: Add backoff, so each wait is longer than the one before, and keep the retry count small.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Plan the failure handling for two tools

Quillfeather Cycles adds a tool called cancel_order(order_id) that cancels an order that has not been dispatched. Write a short failure plan for lookup_order and cancel_order side by side.

You will need

  • lookup_order only reads. cancel_order changes an order and cannot be undone by the agent.
  • Sample failures: the order ID is "1042"; the service says it is busy; the call times out; the service answers "agent not allowed".
  • The agent has a step limit called MAX_ROUNDS.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Ask: will trying again change anything?
  • A timeout on cancel_order leaves one question open. Did the order get cancelled?
  • Decide the retry limit and total time before you decide the message.
Show a model answer

A strong plan sorts the failures like this. "1042" is bad input: do not retry, return {"error": "order_id must look like QF-1234"} so the model can fix it. "Busy" is temporary: retry up to three times with waits that double, within a total of 30 seconds. A timeout is temporary but unclear: for lookup_order, retry freely. For cancel_order, retry only with the same idempotency key, because the first call may already have worked. "Agent not allowed" is permanent: stop and hand over, and also fix the permissions as described in the lesson on least privilege. When the limits run out, the agent says it could not finish and that a colleague will contact the customer, and the plan names the person or queue that receives the case. Retries stay inside one tool call, while MAX_ROUNDS still limits how many rounds the agent may use.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.A tool returns an error because the order ID is "1042". What should the agent do?
    Show the answer and explanation

    Answer: B. Bad input will fail the same way each time, so a plain retry is pointless, and the model can fix the value if it sees a clear error. Handing over at once is tempting but wasteful, because this problem is easy to repair.

  2. 2.request_return times out. Why is it risky to just call it again?
    Show the answer and explanation

    Answer: A. A timeout means no answer arrived, not that nothing happened. The second option is tempting, but a timeout can come from a slow network while the service works fine. Retrying is allowed. It must be done with the same idempotency key.

  3. 3.What does an idempotency key do?
    Show the answer and explanation

    Answer: B. The key is a unique ID for one action. The service uses it to recognise a repeat. It does nothing for speed, which is the tempting wrong answer, and it does not control what the model may call.

Frequently asked questions

What is an idempotency key in simple words?

It is a unique ID you send with a request. If the same ID arrives again, the service knows it is a repeat. It sends back the first result and does not do the action twice. Think of a ticket number at a deli counter.

Should I retry an API call that times out?

Yes for a read, because asking twice changes nothing. For a write, retry only if you send an idempotency key or can check first that the action did not happen. Always limit the number of tries and the total time.

What is exponential backoff?

It means waiting longer before each retry, usually doubling the wait: 1 second, 2 seconds, 4 seconds. It gives a busy service time to recover. Real systems often add a small random extra wait so many clients do not retry at the same moment.

How many times should an AI agent retry a tool?

Two or three tries is a common choice, plus a maximum total time such as 30 seconds. The right number depends on how long a customer will wait. Past the limit, return an error observation and hand over to a person.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.