A Retried Agent Tool Call Runs Twice Without an Idempotency Key
When autonomous agents execute external tool calls (such as payment triggers or cloud resource provisioning), network blips or TCP disconnects frequently cause the agent client to retry the request.
To prevent duplicate execution side-effects, claim an idempotency key document in Cloud Firestore with create() before dispatching the tool; create() fails if the document already exists, so exactly one caller wins. A retry that finds the key completed returns the cached result, and one that finds it in_flight gets a 409 to retry later instead of re-executing the underlying tool.
Don't run the tool inside runTransaction. Firestore's docs warn that a transaction function "might run more than once" under contention. Its writes land only at commit, so no other caller ever sees in_flight, and server SDK transactions hold document locks against a 20-second lock deadline. Make expireAt a Timestamp so a TTL policy can clear claims a crashed worker leaves behind.
// Claim the key with create(), then run the tool outside any transaction
import { Firestore, Timestamp } from "firebase-admin/firestore";
const ALREADY_EXISTS = 6; // gRPC status create() fails with when the document exists
const CLAIM_TTL_MS = 24 * 60 * 60 * 1000;
export async function withIdempotency<T>(
db: Firestore, key: string, executeTool: (key: string) => Promise<T>,
): Promise<T> {
const ref = db.collection("idempotency_keys").doc(key);
try {
// expireAt is a Timestamp so a TTL policy on it can delete abandoned claims
await ref.create({ status: "in_flight", expireAt: Timestamp.fromMillis(Date.now() + CLAIM_TTL_MS) });
} catch (err) {
if ((err as { code?: number }).code !== ALREADY_EXISTS) throw err;
const doc = (await ref.get()).data();
if (doc?.status === "completed") return doc.cachedResult as T;
throw Object.assign(new Error(`tool call ${key} is still in flight, retry later`), { status: 409 });
}
// Pass the key on so the downstream API can dedupe too; a failed call releases the claim
const result = await executeTool(key).catch(async (err: unknown) => {
await ref.delete();
throw err;
});
await ref.update({ status: "completed", cachedResult: result });
return result;
}
Get the next essay by email
One email per new essay: a production failure, taken apart, and the code that fixed it. Reply to any of them to unsubscribe.