When an agent retries an API call and refunds an order twice
Timeouts, disciplined retries and one fixed idempotency key per operation fit into about 80 lines of TypeScript you can copy into a project today.
In brief
- APIs with side effects are only safe to retry when they support idempotency.
- Generate the idempotency key once per business operation, reuse it across every retry, and attach it only to POST requests.
- Retries need a budget: if every layer retries on its own, load on the database can grow 243 times.
One order, refunded twice, discovered by the finance team the morning after. Take an FDE in their second week on a client site. The customer-support agent the team deployed has a tool called createRefund, which calls the client’s internal refunds API. One afternoon the network is flaky, the first request gets no response, the agent tries again, and the money goes out twice.
The model is not at fault. The fault sits in a dozen or so lines of code wrapping fetch that everyone assumes are a chore. For an FDE, the API-calling layer is where the agent touches the client’s real money, inventory and data, so it is code that has to be right the first time.
The layer needs three things: timeouts, disciplined retries and idempotency keys. What follows takes each in turn, then combines them into one complete TypeScript function to copy and adapt for your own project.
Why naive retries are dangerous
The Amazon Builders’ Library puts it bluntly: APIs with side effects are not safe to retry unless they support idempotency. When a refund request times out, the client cannot tell whether the server processed it. The packet may never have arrived, or the money may already have moved and only the response was lost on the way back.
An idempotency key resolves exactly that ambiguity. Stripe’s documentation says that when a connection error occurs, you can resend the request without fear of creating a second object or applying an update twice.
The mechanism is simple. Stripe stores the status code and body of the first request made with each key, whether it succeeded or failed, and returns that same result for every repeat.
The words “or failed” matter. As Stripe describes it, if the first attempt returned a 500, a retry with the same key gets that same 500 back. Retrying with the old key is therefore mainly useful when the failure happened in transit, a timeout or a dropped connection, when the client has received no result at all.
How long should the timeout be?
Defaults are usually far too long for what an agent needs. OpenAI’s Node SDK sets a default timeout of 10 minutes, which is reasonable for a long model call, but an order-lookup API should never be given that long.
Amazon offers a principled way to choose. First decide what share of “false” timeouts you can accept, meaning requests that would have succeeded had you waited longer, then take the corresponding latency percentile of the downstream service, such as p99.9.
If the refunds API has a p99.9 of 1.2 seconds, a timeout of about 1.2 seconds means accepting that roughly 0.1% of requests will be cut off unnecessarily.
In Node there is no need to build this from setTimeout. AbortSignal.timeout() returns a signal that aborts itself after a given time, and when it fires it aborts with a DOMException named TimeoutError. That lets the code tell a timeout apart from a deliberate cancellation by the user, two cases that need different handling.
How many retries are enough?
OpenAI’s SDK is a good reference design. According to its README, it retries automatically twice with a short exponential backoff, and by default retries 408, 409 and 429 errors, every error of 500 and above, and connection errors. It does not retry a 400 or a 401, because resending the same request will not change anything.
Backoff alone is not enough; it needs jitter. Amazon explains jitter as adding a little randomness to the wait so that retries spread out over time. Without it, a thousand agent sessions that fail at once will all retry at the same instant and knock the service over again.
The biggest danger is retries stacked across layers. Amazon gives the example of a five-layer system in which each layer retries independently, increasing load on the database 243 times.
Working backwards, 243 is 3 to the power of 5, which corresponds to each layer making up to three attempts. Amazon’s remedy is to cap retries locally with a token bucket: when the tokens run out, stop retrying and pass the error up.
The complete version in TypeScript
Below is a callApi function that brings all three together. Note the line that generates the key: it sits outside the loop.
import { randomUUID } from "node:crypto";
type Method = "GET" | "POST" | "DELETE";
interface CallOptions {
method: Method;
url: string;
body?: unknown;
timeoutMs: number; // taken from the downstream API's p99.9
maxRetries?: number; // defaults to 2
idempotencyKey?: string; // pass one in if the operation already has a key
signal?: AbortSignal; // cancellation signal from the agent or the user
}
// Token bucket: at most 10 retries, refills 1 token per second
class RetryBudget {
private tokens = 10;
constructor() {
setInterval(() => (this.tokens = Math.min(10, this.tokens + 1)), 1000).unref();
}
take(): boolean {
if (this.tokens <= 0) return false;
this.tokens--;
return true;
}
}
const budget = new RetryBudget();
// Requests with a key: don't retry 5xx, the server has stored it and will return the same error
const isRetryableStatus = (s: number, hasKey: boolean) =>
s === 408 || s === 409 || s === 429 || (!hasKey && s >= 500);
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const backoff = (attempt: number) =>
Math.random() * Math.min(5000, 200 * 2 ** attempt); // jitter
export async function callApi(opts: CallOptions): Promise<Response> {
const maxRetries = opts.maxRetries ?? 2;
// Generated ONCE for the whole operation; only POST carries a key
const key =
opts.method === "POST" ? opts.idempotencyKey ?? randomUUID() : undefined;
for (let attempt = 0; ; attempt++) {
// Each call gets its own timeout, combined with the caller's cancellation signal
const timeout = AbortSignal.timeout(opts.timeoutMs);
const signal = opts.signal ? AbortSignal.any([opts.signal, timeout]) : timeout;
try {
const res = await fetch(opts.url, {
method: opts.method,
headers: {
"Content-Type": "application/json",
...(key ? { "Idempotency-Key": key } : {}), // header name depends on the API
},
body: opts.body ? JSON.stringify(opts.body) : undefined,
signal,
});
const canRetry =
isRetryableStatus(res.status, key !== undefined) &&
attempt < maxRetries &&
budget.take();
if (!canRetry) return res;
await res.body?.cancel(); // discard the body to free the connection before retrying
} catch (err) {
// The caller cancelled on purpose: stop now, don't retry
if (opts.signal?.aborted || attempt >= maxRetries || !budget.take()) throw err;
// Anything else is a TimeoutError or a network error: resend with the SAME key
}
await sleep(backoff(attempt));
if (opts.signal?.aborted) throw opts.signal.reason;
}
}
Back to the refund. The first call times out, the catch block receives a TimeoutError, and the function waits a random interval before resending with the same key. If the server processed the earlier attempt, it returns the stored result and there is no second refund.
Two small details are worth keeping when you modify the function. The caller’s cancellation signal is combined with the timeout through AbortSignal.any(), so if the agent is stopped midway, the function exits at once instead of retrying. And a response discarded in favor of a retry has its body cancelled, so the connection is not left hanging in the pool.
The retry condition here is narrower than OpenAI’s SDK in one respect: requests carrying a key do not retry errors of 500 and above. The reason lies in the mechanism described earlier. With an API that stores the first result per key, as Stripe does, resending the same key after a 500 only returns the same 500, spending budget for nothing.
GET and DELETE carry no key, so they still retry 5xx as usual. If the client’s API handles keys differently, ask them first before loosening this condition.
A 409 is still worth retrying when it signals a conflict with another request running concurrently. Stripe notes that it does not store a result when parameters fail validation or when a request conflicts with one already in progress, so resending is safe in those cases.
Common mistakes in the field
The most common mistake is generating the key inside the loop. Every retry then carries a new key, the server treats it as a new operation, and idempotency effectively disappears.
Agents add a subtler variant: the model calls the same tool again at a later step, and your layer generates a fresh key for that call. If the orchestrator can rerun a step, derive the key from that step’s ID and pass it in through idempotencyKey.
The second mistake is reusing a key with different parameters. Stripe compares the new parameters with the original request and returns an error if they differ. It may also delete keys after 24 hours, so a job rerun the next day cannot rely on the old key.
The third is attaching a key to every request. Stripe states that GET and DELETE are already idempotent, so sending a key with them does nothing. Nor should emails or account numbers go into the key: Stripe recommends a UUID V4 or a random string with enough entropy, up to 255 characters, containing no sensitive data.
The last mistake, and the hardest to spot, is stacking retries on top of an SDK. If your tool wraps a client that already retries twice, and the agent’s orchestrator retries on top of that, the amplification factor has multiplied before anyone notices. Pick exactly one layer to retry and switch retries off everywhere else.
Putting the skill on your CV
When reading an FDE job description, look for requirements around integrating with client systems or production reliability: that is where this kind of code belongs in your story.
On a CV, do not just write “built an agent that calls APIs”. Say which percentile you set timeouts from, which layer retries, and how you used idempotency to block duplicate operations.
In an interview, the question “what does your agent do if an order-creation request times out?” is a chance to sketch the loop above. Interviewers remember the candidate who knows that a timeout does not mean failure; it means the outcome is unknown.
Was this article useful?
Thanks for the feedback!