{"slug": "the-refund-worked-the-agent-sent-it-again", "title": "The Refund Worked. The Agent Sent It Again.", "summary": "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.", "body_md": "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.\n\nTool 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?\n\nA fictional bookstore agent refunds $25. The service writes the refund. Then the reply disappears on the way back.\n\nFrom the agent’s side, this looks the same as a request that never arrived. It retries, and the customer is paid twice.\n\nNo model error is needed. A perfectly reasonable decision to refund, followed by a perfectly reasonable retry, produces the wrong result.\n\nI 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.\n\nEach attempt can fail in one of three ways:\n\nIn the first test, attempt one fails in a chosen way and attempt two goes through. The correct answer is always one refund.\n\nTwo results are worth slowing down for.\n\nA **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.\n\n**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.\n\nThe version that held puts the rule inside the database write:\n\n``` python\ndef 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\"\n```\n\nThe 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.\n\nThis 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].\n\nI also ran 20 simultaneous inserts with one key, each on its own database connection. One row was written.\n\nNext 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.\n\nAt a 20% failure rate:\n\nEven at a 1% failure rate, blind retry double-refunded 68 of the 10,000 orders.\n\nWith 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.\n\nA 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.\n\nThe agent should also say so. “I could not confirm your refund” is accurate. “Your refund failed” may be false.\n\nA checklist for any tool that changes something:\n\nIf a tool cannot meet item 4, I would turn off automatic retries for it and send uncertain results to review.\n\nThe 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.\n\nName the operation once, and make the system that changes the data refuse to do it twice.\n\nThe 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.\n\n[The Refund Worked. The Agent Sent It Again.](https://pub.towardsai.net/the-refund-worked-the-agent-sent-it-again-230453919767) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.", "url": "https://wpnews.pro/news/the-refund-worked-the-agent-sent-it-again", "canonical_source": "https://pub.towardsai.net/the-refund-worked-the-agent-sent-it-again-230453919767?source=rss----98111c9905da---4", "published_at": "2026-11-28 16:01:03+00:00", "updated_at": "2026-11-28 16:42:30.513289+00:00", "lang": "en", "topics": ["ai-agents", "ai-safety", "ai-tools"], "entities": ["SQLite", "Amazon Builders' Library", "Stripe"], "also_reported_by": [], "takeaway": "Declare the caller-supplied idempotency key UNIQUE and insert it in the same database transaction as the write, then treat an IntegrityError as 'already done' only if the stored parameters match; a status check before the write leaves a gap where a late retry creates a duplicate.", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/the-refund-worked-the-agent-sent-it-again", "markdown": "https://wpnews.pro/news/the-refund-worked-the-agent-sent-it-again.md", "text": "https://wpnews.pro/news/the-refund-worked-the-agent-sent-it-again.txt", "jsonld": "https://wpnews.pro/news/the-refund-worked-the-agent-sent-it-again.jsonld"}}