cd /news/ai-agents/the-refund-worked-the-agent-sent-it-… · home › topics › ai-agents › article
[ARTICLE · art-177805] src=pub.towardsai.net ↗ pub= topic=ai-agents verified=true sentiment=↓ negative

The Refund Worked. The Agent Sent It Again.

A scripted retry-loop agent that refunds money through tool calls double-paid customers whenever a reply was lost, and only an idempotency key recorded atomically with the database write prevented duplicates, according to a Python/SQLite experiment using only the standard library. In 10,000 simulated orders, blind retry double-refunded 68 orders even at a 1% failure rate, while generating a new key on every attempt behaved exactly like no key at all; checking status before writing still allowed a late request to slip into the gap and create a second refund. With one key per refund, the agent still ran out of attempts without confirmation on 15 orders at a 20% failure rate and 83 at 30%, leaving two orders at 30% with no refund at all — cases the author says require reconciliation by a later job or a person looking up the operation by its ID.

recommendation

Record a caller-supplied idempotency key atomically with each money-moving write and reject reuse with different parameters; the source's UNIQUE-key version prevented double refunds that blind retry and check-then-write both produced.

more in playbook: Designing agent systems
read4 min views11 publishedNov 28, 2026

An AI agent is a program in which a model chooses steps and software carries them out through “tools”: look up an order, send an email, issue a refund.

Tool calls travel over networks, and networks drop things. The usual response to a timeout is to try again. For reading data, that is fine. For moving money, it depends on a detail the agent cannot see: did the first call work?

A fictional bookstore agent refunds $25. The service writes the refund. Then the reply disappears on the way back.

From the agent’s side, this looks the same as a request that never arrived. It retries, and the customer is paid twice.

No model error is needed. A perfectly reasonable decision to refund, followed by a perfectly reasonable retry, produces the wrong result.

I built a refund service in Python with an in-memory SQLite table, using only the standard library. The “agent” is a scripted retry loop with up to four attempts. I left the language model out on purpose, because the question is what happens after the decision to act.

Each attempt can fail in one of three ways:

In the first test, attempt one fails in a chosen way and attempt two goes through. The correct answer is always one refund.

Two results are worth slowing down for.

A new key on every try behaved exactly like no key at all. The service can only recognize a repeat if the repeat carries the same name. If your code creates the ID inside the retry loop, check this first.

Checking status first fixed the lost reply and missed the slow commit. The check truthfully answered “no refund yet.” Then the first request landed, and the retry wrote a second one. A check followed by a write leaves a gap between the two, and a late request fits inside it.

The version that held puts the rule inside the database write:

def refund(self, order_id, amount, op_key=None):    try:        with self.db:            self.db.execute("INSERT INTO refunds VALUES (?, ?, ?)",                            (order_id, amount, op_key))        return "created"    except sqlite3.IntegrityError:        row = self.db.execute(            "SELECT order_id, amount FROM refunds WHERE op_key = ?",            (op_key,)).fetchone()        if row != (order_id, amount):            return "rejected: key reused for a different refund"        return "already done"

The op_key column is declared UNIQUE. The database decides, in the same step as the write, whether this operation has happened. No gap is left for a late request.

This property is called idempotency: repeating a request has no additional effect. Amazon’s Builders’ Library describes a caller-provided request identifier, recorded atomically with the change it protects, and an error when the same identifier arrives with different parameters [1]. Stripe’s API saves the result of the first request made with a key, returns it on later requests, and rejects a reused key whose parameters differ. Its v1 documentation also says keys can be removed once they are at least 24 hours old, so a very late retry can run again [2].

I also ran 20 simultaneous inserts with one key, each on its own database connection. One row was written.

Next I ran 10,000 fictional orders at several failure rates. These rates are settings in my simulation, not measurements of any real network. A failing attempt was equally likely to be any of the three kinds, and every design faced the same sequence of failures.

At a 20% failure rate:

Even at a 1% failure rate, blind retry double-refunded 68 of the 10,000 orders.

With one key per refund, the agent still ran out of attempts without a confirmation on 15 orders at the 20% rate, and on 83 at the 30% rate. At 30%, two orders got no refund at all.

A key prevents a second payment. It cannot promise a first one, and it cannot tell the agent what happened. Those orders need reconciliation: a later job or a person who looks up the operation by its ID and settles it.

The agent should also say so. “I could not confirm your refund” is accurate. “Your refund failed” may be false.

A checklist for any tool that changes something:

If a tool cannot meet item 4, I would turn off automatic retries for it and send uncertain results to review.

The agent is a script, so this says nothing about how often a model chooses to retry. The failures are simulated inside one process. A slow request always lands just before the next write, which is the worst timing for the status check, so its real duplicate rate could be lower. My key, refund:<order id>, allows one refund per order; a real system needs an ID for each approved refund, so that two partial refunds stay possible. The ledger and the idempotency record share one database here. If your tool calls an external service, that service has to support keys, or you need another way to reconcile. I did not test key expiry.

Name the operation once, and make the system that changes the data refuse to do it twice.

The code, tests and raw output are here: <CODE_REPO_URL_TBD>. Run python3 drill.py, change the failure rate, and see what your retry design does.

The Refund Worked. The Agent Sent It Again. was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.

── more in #ai-agents 4 stories · sorted by recency
── more on @sqlite 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/the-refund-worked-th…] indexed:0 read:4min 2026-11-28 · —