Notes

Atomic Idempotency Key Enforcement for Multi-Turn Agent Tool Calling

Firestore, AI Agents

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, store an idempotency token document in Cloud Firestore using an atomic transaction before dispatching the tool. If the transaction detects an existing token in the in_flight or completed state, return the cached result immediately rather than re-executing the underlying tool.

idempotencyMutex.ts
// Atomic Idempotency Check in Cloud Firestore
export async function withIdempotency(db, key, executeTool) {
  const ref = db.collection("idempotency_keys").doc(key);
  return db.runTransaction(async (tx) => {
    const doc = await tx.get(ref);
    if (doc.exists && doc.data().status === "completed") {
      return doc.data().cachedResult;
    }
    tx.set(ref, { status: "in_flight", startedAt: Date.now() }, { merge: true });
    const result = await executeTool();
    tx.set(ref, { status: "completed", cachedResult: result, completedAt: Date.now() }, { merge: true });
    return result;
  });
}

All 7 notes