On this page
  1. 1. Maya’s double refund
  2. 2. What a timeout actually tells you
  3. 3. Why you still retry
  4. 4. Reads, writes, and idempotency
  5. 5. Attempt 1: deduplicate by arguments
  6. 6. Attempt 2: let the agent pick a key
  7. 7. The fix: create the key when the refund is approved
  8. 8. Beyond your database: the payment provider
  9. 9. When retries are hours apart
  10. 10. So is this “exactly once”?
  11. 11. Back to Maya

Essay

The Agent Refunded Her Twice

· 11 min read

AI agents aren’t just answering questions anymore. More and more, they’re being given tools that let them actually do things for us: issue refunds, book flights, open tickets, or merge code. But once an agent can change something in the real world, it runs into an old problem from distributed systems: what happens when a request fails partway through and gets retried? In this post, we’ll walk through that problem with a simple example, and see why agents make it a little harder than usual.

1. Maya’s double refund

Imagine Maya, who just bought a brand new $49 heater for the winter. When it arrives, it’s broken, so she decides she wants her money back. She goes to the site where she bought it, opens a support chat window, and types “My heater arrived broken, can I get a refund?”

Behind this chat window sits a customer support agent that has a few tools at its disposal. For the sake of simplicity, let’s say these are look_up_order, issue_refund, and send_email. As a safeguard, any refund over $25 has to be approved by a human reviewer before the agent can issue it. When the agent calls issue_refund, the request goes to the store’s payments service, which talks to an external payment provider that actually sends the money back.

In a typical workflow, the agent would look up Maya’s order, propose a $49 refund to the reviewer, the reviewer would approve it, the refund would go through, and Maya would get a confirmation email.

However, in this case, things go a little differently. The agent looks up the order, the reviewer approves the refund, and the payments service asks the provider to refund $49. The provider processes the refund, but its reply is slow, and after 10 seconds the payments service gives up waiting and sends a timeout error back to the agent. The agent sees the error and does what it was built to do: it tries again, this time with slightly different arguments. The provider processes a second refund.

sequenceDiagram
    actor Maya
    participant Agent as Support agent
    actor Reviewer
    participant Payments as Payments service
    participant Provider as Payment provider

    Maya->>Agent: My heater arrived broken, can I get a refund?
    Agent->>Reviewer: Propose a $49 refund
    Reviewer-->>Agent: Approved
    Agent->>Payments: issue_refund(1042, 49.00)
    Payments->>Provider: Refund $49
    Note over Provider: Refund 1 processed
    Note over Payments: 10 seconds pass, gives up
    Payments-->>Agent: Timeout error
    Agent->>Payments: issue_refund(1042, 49, "damaged item")
    Payments->>Provider: Refund $49
    Note over Provider: Refund 2 processed
    Payments-->>Agent: OK
    Agent->>Maya: Your refund is on its way

So what just happened? As it turns out, Maya just got refunded $98, double what she paid for the heater, from one message. The reviewer never saw the second refund, because they had already approved this one and the retry happened behind the scenes. Nobody notices until someone in finance goes through the books at the end of the month.

The interesting part is that nothing here actually broke. The network was slow, the timeout fired, and the agent retried. Everything was just doing its job. What we want to get at here is that the problem wasn’t the retry. The problem was that nothing could recognize the retry as a repeat of the same request.

2. What a timeout actually tells you

A timeout only tells you something from the caller’s side: it stopped waiting. It doesn’t tell you anything about what happened on the server’s side. We can imagine three worlds at the moment the payments service gave up:

  1. The request never reached the provider, so no refund happened
  2. The refund happened, and the reply was lost or slow
  3. The refund is still in progress
flowchart LR
    A["Refund request sent"] --> B{"What happened at the provider?"}
    B --> W1["Never arrived, no refund"]
    B --> W2["Refunded, reply lost or slow"]
    B --> W3["Still processing"]
    W1 --> T["The caller sees the same thing: a timeout"]
    W2 --> T
    W3 --> T

From the caller’s end, all three of these look exactly the same. So what options do we have here? We can either:

  1. Assume it failed and retry: but in worlds 2 and 3, Maya gets refunded twice
  2. Assume it worked and stop: but in world 1, Maya never gets her refund

And waiting longer doesn’t really help either. A longer timeout just makes world 3 less likely, it doesn’t make it go away. If you’ve ever seen a checkout page that says “Do not refresh this page,” that’s a site running into this exact problem and asking you to work around it.

3. Why you still retry

What if we just stopped retrying? Most failures are temporary: maybe there was a dropped connection, a busy server, or a deploy in progress. In these cases, not retrying would mean Maya’s legitimate refund gets lost.

And even if we stopped retrying in one place, there are a lot of other places retries can come from:

  • The HTTP client library, which sometimes retries by default
  • The payments service, retrying its call to the provider
  • The agent framework’s tool-retry policy
  • The model itself, deciding to try again after an error
  • Maya, clicking or asking again

These layers also multiply. If three layers each retry three times, one request can turn into as many as 27 calls to the provider. How to retry well (exponential backoff, jitter, and limits) is its own topic, so we’ll save that for another post.

So retries are going to happen whether we plan for them or not. And since the caller can’t know which world it’s in, the server is the one that has to make retries safe.

4. Reads, writes, and idempotency

So how do we get around this? More generally, how do we make sure that an action applied once or many times has the same effect? This is what we call idempotency.

A good everyday example is an elevator button. Pressing it five times still brings one elevator. Compare that to ordering coffee, where saying “one more coffee” twice gets you two coffees.

If we look at the agent’s tools:

  • look_up_order is a read, so it’s always safe to retry
  • send_email is a write, and a duplicate is annoying but cheap
  • issue_refund is a write, and a duplicate costs money

Some writes can be made idempotent just by how you design them. “Set order 1042’s status to refunded” can run ten times and the order is still just refunded. HTTP has this idea built in too: the spec defines GET, PUT, and DELETE as idempotent and POST as not, though it’s still up to the server to keep that promise.

But a refund can’t be designed that way. Every refund is a new movement of money, so issue_refund is going to need some help.

5. Attempt 1: deduplicate by arguments

Let’s see how we can make the issue_refund tool call idempotent. To start off with, what if we hash the (order, amount) and reject a second refund with the same hash?

However, a model doesn’t replay the exact same tool call when it retries, it writes a new one. So the first call might send {"order": "1042", "amount": 49.00} and the retry might send {"order": "1042", "amount": 49, "reason": "damaged item"}. The hash is different, and we’re back to two refunds.

There is also another failure mode here. What if Maya bought two identical heaters and both arrived broken? Now she has two legitimate $49 refunds for the same order, and our hash would block the second one.

Thus, the issue we are facing is that the arguments describe what to do, not which request this is. We need an identity for the request itself.

6. Attempt 2: let the agent pick a key

What if we let the agent include a unique request_id with each tool call, and reuse it when it retries? This wouldn’t really work either. On a retry, the model might generate a fresh ID, which defeats the purpose. Or it might accidentally reuse the same ID across two different refunds, or just make one up.

Another idea is to have the agent check first: before issuing a refund, look up whether one already exists for this order. This helps, but it doesn’t guarantee anything. Two attempts can both check before either one writes, and in world 3 the first refund hasn’t even shown up yet.

Thus, the takeaway here is that the identity has to be created at the moment the refund is decided, and it can’t come from the model.

7. The fix: create the key when the refund is approved

So what if, after the reviewer approves the refund, we save the approval and use it to create the key? That’s the moment “refund Maya $49, once” actually becomes a decision, so it’s the right place for the identity to come from.

What should the key look like? The common practice is a random UUID, something like 7c9e6679-7425-40de-944b-e07fc1f90ae7, generated once when the approval is saved. To keep things readable, we’ll shorten the key to 7c9e… from here on.

The model never sees this key. When the agent calls issue_refund, the code that runs the tool looks up the approval and attaches the key itself:

when the agent calls issue_refund(order, amount):
    approval = the approval the reviewer just gave
    payments.issue_refund(
        key    = approval.key,      # created at approval time, never by the model
        order  = approval.order,
        amount = approval.amount)   # the approved amount, not whatever the model wrote

So now it doesn’t matter if the model rewords its arguments on the retry. The call still belongs to the same approval, it carries the same key, and the amount comes from what the reviewer approved. If Maya really did need a second refund, that would need a second approval, which would get its own key.

On the other side, the payments service keeps a table of the keys it has seen, and only handles each one once:

issue_refund(key, order, amount):
    if we can't claim the key:                # claiming is atomic, so only one request wins
        existing = look up the key
        if it was used for a different order or amount:  reject it (a bug, not a retry)
        if it's still in progress:                       say "still processing, try again later"
        if it's done:                                    return the saved result

    refund = provider.refund(order, amount, key)   # pass the same key along
    in one transaction:
        save the refund
        mark the key as done and save the result
    return refund

A few things are worth pointing out here. Claiming the key has to be atomic, otherwise two retries arriving at the same moment could both claim it. Saving the refund and marking the key as done happen in one transaction, so our records can never disagree with each other. And keys can’t be kept forever, but they need to be kept longer than any retry could take. Stripe, for example, keeps them for at least 24 hours.

8. Beyond your database: the payment provider

All of this protects our own records. But the money itself moves at the provider, outside of our database.

What happens if the payments service dies or times out right after calling the provider, but before saving the result? That’s exactly Maya’s situation. The provider has refunded her, but our table still says “in progress,” so we’re back to not knowing, just one step further down.

That’s why the code above passes the same key to the provider too. Payment providers like Stripe accept an Idempotency-Key header, and if they’ve already handled a key, they send back the original result instead of making a new refund. So if a retry finds a key that’s been stuck “in progress” for a while, it’s safe to call the provider again. Either the first request never made it and this one goes through, or it did make it and the provider just hands back the refund it already made.

sequenceDiagram
    participant Agent as Agent and tool layer
    participant Payments as Payments service
    participant Provider as Payment provider

    Agent->>Payments: Refund $49, key 7c9e…
    Payments->>Provider: Refund $49, same key
    Note over Provider: Refund processed
    Note over Payments: 10 seconds pass, gives up
    Payments-->>Agent: Still processing
    Agent->>Payments: Retry, key 7c9e…
    Payments->>Provider: Refund $49, same key
    Provider-->>Payments: Already done, here's the original refund
    Payments-->>Agent: Refunded $49

Not everything downstream supports keys though. Email usually doesn’t. A common way to handle this is an outbox: in the same transaction where we save the refund, we also write “send Maya a confirmation email for this refund” to a table, and a separate worker sends whatever is in it. We could still occasionally send a duplicate email, but now it’s rare, it’s cheap, and we know exactly where it can happen.

It’s also worth mentioning that MCP lets a tool declare idempotentHint: true. This is useful to know, but it’s the tool author describing their tool, not something that’s actually enforced. The real guarantee still has to come from code like the code above.

9. When retries are hours apart

In Maya’s case, the retry happened seconds after the first attempt. But what if the reviewer didn’t get to her refund for three hours, and in the meantime the server running the agent restarted for a deploy? A new process picks up the conversation. Did the refund already go out?

It’s tempting to let the model figure this out by reading the chat history. However, the history might have been trimmed to fit in the context window, or the process might have died before the tool result was ever written to it. And even if it’s all there, the model is reading the history, not checking a record. The answer should come from the saved approval and the status of its key, since those live in the database and survive a restart. (What if the database itself goes down? That’s where replication and backups come in, but that’s a story for another time.)

Workflow engines like Temporal run into the same thing. Temporal saves each finished step and picks up where it left off after a crash, but a step that was in the middle of running when the crash happened gets run again. So Temporal recommends making those steps idempotent too, using the workflow run ID and the step’s ID as the key. How this kind of durable execution works for agents is a topic for another post.

10. So is this “exactly once”?

So can we say Maya’s refund now happens exactly once? It depends on what we mean. Over a network that can lose messages, we can’t guarantee that a request is delivered exactly once. As we saw in section 2, when a sender doesn’t get a reply, it either sends again and risks a duplicate, or doesn’t and risks losing the request.

What we can guarantee is that the effect happens once: the request might show up three times, but Maya only gets refunded once. However, that guarantee only covers so much. Here it covers one refund per approved request, enforced by our key table and the provider’s, for as long as both of them keep the key.

flowchart LR
    R1["Retry 1"] --> K
    R2["Retry 2"] --> K
    R3["Retry 3"] --> K
    subgraph B["Covered by key 7c9e…"]
        K["Our key table"] --> P["The provider's keys"]
    end
    P --> E["One $49 refund"]
    A2["A second approval for the same heater"] -. "new key, not covered" .-> X["A second refund"]

For example, if a reviewer accidentally approves two separate refunds for the same heater, those are two different keys, and both will go through. As far as the code can tell, that’s correct. Catching it would need a different rule, like “refunds can’t add up to more than the order total.”

So whenever a system claims to be exactly-once, a good question to ask is: exactly once within what?

11. Back to Maya

Let’s go back to Maya one more time, now with all of this in place. The reviewer approves the refund, and the key 7c9e… is created. The provider refunds $49, the reply is slow, and the payments service gives up. The agent is told the refund is still processing, waits, and tries again with the same key. The provider recognizes the key and returns the original refund, and Maya gets her $49 and one confirmation email.

The network was just as slow, and there were just as many retries. The only difference is that every retry carried the same key, all the way to where the money actually moves.

So to sum it up: a timeout means “I don’t know,” not “it failed.” Retries will come from everywhere, so the server needs to make them safe. And the key that makes them safe should be created when the decision is made, not by the model.

← All writing