By Sagar Shankaran, Founder of CallSphere
Master idempotent API design for AI agent systems. Learn how to implement idempotency keys, request deduplication, and fingerprinting so agents can safely retry failed requests without duplicate side effects.
Key takeaways
AI agents operate autonomously, making API calls to execute tools, store results, and communicate with external services. Network failures, timeouts, and transient errors are inevitable. When a request fails ambiguously — the server processed it but the response was lost — the agent must retry. Without idempotent API design, that retry can create duplicate charges, send duplicate emails, or schedule duplicate meetings.
Idempotency means that making the same request multiple times produces the same result as making it once. GET, PUT, and DELETE are naturally idempotent by HTTP specification. POST is where you need explicit idempotency mechanisms.
The standard approach is to have clients send a unique idempotency key with each request. The server stores the result of the first execution and returns the cached result for subsequent requests with the same key.
Hear it before you finish reading
Talk to a live CallSphere AI voice agent in your browser — 60 seconds, no signup.
flowchart LR
CLIENT(["Client SDK"])
GW["API Gateway<br/>auth plus rate limit"]
APP["FastAPI app<br/>handlers and DI"]
VAL["Pydantic validation"]
SVC["Service layer<br/>business logic"]
DB[(Database)]
QUEUE[(Background queue)]
OBS[(Tracing)]
CLIENT --> GW --> APP --> VAL --> SVC
SVC --> DB
SVC --> QUEUE
SVC --> OBS
SVC --> CLIENT
style GW fill:#4f46e5,stroke:#4338ca,color:#fff
style APP fill:#f59e0b,stroke:#d97706,color:#1f2937
style DB fill:#ede9fe,stroke:#7c3aed,color:#1e1b4b
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel
import hashlib
import json
from datetime import datetime, timedelta
app = FastAPI()
# In production, use Redis or a database table
idempotency_store: dict[str, dict] = {}
class AgentTaskRequest(BaseModel):
agent_id: str
action: str
parameters: dict
@app.post("/v1/agent/tasks")
async def create_task(
request: AgentTaskRequest,
idempotency_key: str = Header(..., alias="Idempotency-Key"),
):
# Check for existing result
if idempotency_key in idempotency_store:
cached = idempotency_store[idempotency_key]
if cached["status"] == "processing":
raise HTTPException(
status_code=409,
detail="Request is currently being processed",
)
return cached["response"]
# Mark as processing to prevent concurrent duplicates
idempotency_store[idempotency_key] = {"status": "processing"}
try:
result = await execute_agent_task(request)
response = {
"task_id": result["id"],
"status": "completed",
"result": result["output"],
}
idempotency_store[idempotency_key] = {
"status": "completed",
"response": response,
"created_at": datetime.utcnow().isoformat(),
}
return response
except Exception as e:
del idempotency_store[idempotency_key]
raise
For production systems, store idempotency records in your database within the same transaction as the business operation. This guarantees atomicity — either both the operation and the idempotency record are committed, or neither is.
from sqlalchemy import Column, String, JSON, DateTime, text
from sqlalchemy.ext.asyncio import AsyncSession
class IdempotencyRecord(Base):
__tablename__ = "idempotency_keys"
key = Column(String(255), primary_key=True)
request_path = Column(String(500), nullable=False)
request_fingerprint = Column(String(64), nullable=False)
response_code = Column(String(3), nullable=False)
response_body = Column(JSON, nullable=False)
created_at = Column(
DateTime, server_default=text("NOW()"), nullable=False
)
async def with_idempotency(
db: AsyncSession,
key: str,
request_path: str,
request_body: dict,
handler,
):
fingerprint = hashlib.sha256(
json.dumps(request_body, sort_keys=True).encode()
).hexdigest()
existing = await db.get(IdempotencyRecord, key)
if existing:
if existing.request_fingerprint != fingerprint:
raise HTTPException(
status_code=422,
detail="Idempotency key reused with different request body",
)
return json.loads(existing.response_body)
result = await handler()
record = IdempotencyRecord(
key=key,
request_path=request_path,
request_fingerprint=fingerprint,
response_code="200",
response_body=json.dumps(result),
)
db.add(record)
await db.commit()
return result
When agents cannot send idempotency keys (for example, when calling third-party APIs), you can deduplicate based on request content. Generate a fingerprint from the request method, path, body, and a time window.
def compute_request_fingerprint(
method: str, path: str, body: dict, agent_id: str
) -> str:
canonical = json.dumps(
{
"method": method,
"path": path,
"body": body,
"agent_id": agent_id,
},
sort_keys=True,
)
return hashlib.sha256(canonical.encode()).hexdigest()
async def deduplicate_request(
fingerprint: str,
window_seconds: int = 300,
):
"""Check if an identical request was made within the time window."""
cutoff = datetime.utcnow() - timedelta(seconds=window_seconds)
# Query database for matching fingerprint within window
existing = await db.execute(
text(
"SELECT response_body FROM idempotency_keys "
"WHERE request_fingerprint = :fp AND created_at > :cutoff"
),
{"fp": fingerprint, "cutoff": cutoff},
)
row = existing.fetchone()
return json.loads(row[0]) if row else None
Idempotency records should not live forever. Implement a cleanup job that removes records older than your retry window, typically 24 to 48 hours.
async def cleanup_expired_keys(max_age_hours: int = 24):
cutoff = datetime.utcnow() - timedelta(hours=max_age_hours)
await db.execute(
text("DELETE FROM idempotency_keys WHERE created_at < :cutoff"),
{"cutoff": cutoff},
)
await db.commit()
Use a UUID v4 generated client-side. This guarantees uniqueness without coordination. The agent should generate the key before the first attempt and reuse the same key for all retries of that specific operation. Never reuse an idempotency key for a different operation — the server should reject this with a 422 status code if the request body fingerprint does not match.
Still reading? Stop comparing — try CallSphere live.
CallSphere ships complete AI voice agents per industry — 14 tools for healthcare, 10 agents for real estate, 4 specialists for salons. See how it actually handles a call before you book a demo.
Store them for at least as long as your maximum retry window. A common choice is 24 hours. After that, the key can be safely deleted. If an agent retries after the key expires, the operation will execute again, which is acceptable since such a long gap likely indicates a new intent rather than a retry.
No. GET requests are inherently idempotent by definition — they read data without side effects. Adding idempotency keys to GET requests adds complexity with no benefit. Reserve idempotency mechanisms for POST and PATCH endpoints that create or modify resources.
#Idempotency #APIDesign #AIAgents #FastAPI #Reliability #AgenticAI #LearnAI #AIEngineering

Written by
Sagar Shankaran· Founder, CallSphere
LinkedInSagar Shankaran is the founder of CallSphere, where he builds production AI voice and chat agents deployed across healthcare, hospitality, real estate, and home services. He writes about agentic AI, LLM engineering, and shipping voice agents that handle real calls in production.
See how AI voice agents work for your industry. Live demo available -- no signup required.
A founder's guide to the personal AI assistant market: best AI assistant apps, business-grade options, and how CallSphere's voice agent fits in.
A founder's guide to free AI agents, low-code AI agent builders, and how to know when you should pay for a real platform like CallSphere.
Graphiti is the open-source temporal knowledge graph for AI agents in 2026. Learn how bi-temporal memory beats vector RAG for voice agents and long-running LLMs.
Chatbot app vs ChatGPT in 2026: a founder's clear take on the difference, when to use which, and how a real AI chatbot app development works.
How we built a fault-tolerant HVAC emergency triage and tech-dispatch platform on Kubernetes — three-tier CQRS, 11 micro-agents on the OpenAI Agents SDK + LangGraph, NATS JetStream, DTMF/SMS/WebSocket acceptance, circuit breakers, and an evaluation pipeline that catches regressions before they wake a tech at 3 AM.
Self-correction is now a property of the model, not the framework. What that means for production agent reliability, voice/chat fallbacks, and CallSphere.
© 2026 CallSphere Inc. All rights reserved.
Made within San Francisco