AI Agent Request Deduplication 2026
A double-click sends two identical requests, the agent runs the whole tool chain twice, and you pay twice. Deduplication needs a key design, in-flight coalescing, and clear rules for what must never be merged.
📜 Table of Contents
📖 Keep reading
- OpenHands Alternatives 2026: 7 Open Source Coding Agents Compared With Real Stars
- AI Agent Ecosystem Explodes in 2026: MCP Protocol Standardization Paves the Way for Multi-Agent Collaboration
- AI Quiz Generator in 2026: Build a Free Self-Hosted Quiz App with Anki (30k Stars) + LangChain - 5 Working Patterns
Request Deduplication for AI Agents: Handle the Same Question Once
Duplicates come from three places: double clicks, client retries after a timeout, and the agent looping on the same tool. All three double the cost.
1. Four kinds of duplicate
| Source | Signal | Handling |
|---|---|---|
| Double click | Same user, same content, sub-second gap | Idempotency key, short window |
| Client retry | Retry header or same request id | Key + cached result |
| Agent loop | Same tool, same args in one trace | Per-trace tool cache |
| Semantic | Different wording, same intent | Embedding similarity, carefully |
The first three are deterministic. Semantic matching is an optimization, never a correctness guarantee.
2. Designing the key
def idempotency_key(user_id, endpoint, payload, client_key=None):
if client_key:
return f"{user_id}:{endpoint}:{client_key}"
norm = unicodedata.normalize("NFKC", json.dumps(payload, ensure_ascii=False, sort_keys=True))
norm = " ".join(norm.split()).lower()
return f"{user_id}:{endpoint}:{hashlib.sha256(norm.encode()).hexdigest()[:32]}"
Always include user_id, normalize the payload, include the tool or endpoint name, and truncate the hash to keep keys short.
3. Redis: SETNX plus result write-back
if (cached := r.get(f"done:{key}")):
return json.loads(cached)
if not r.set(f"lock:{key}", "1", nx=True, ex=60):
return wait_or_in_progress(key)
try:
result = run_agent(req)
r.set(f"done:{key}", json.dumps(result), ex=ttl)
return result
finally:
r.delete(f"lock:{key}")
Lock TTL should be roughly three times normal execution, refreshed by a heartbeat. Result TTL defines the reuse window: minutes for chat, hours to a day for write operations. On failure, release the lock and do not write a result.
4. Single-flight in process
async def single_flight(key, factory):
if key in inflight:
return await inflight[key]
task = asyncio.ensure_future(factory())
inflight[key] = task
try:
return await task
finally:
inflight.pop(key, None)
Local coalescing first, Redis across instances.
5. Semantic dedup
Risks: merging questions that look alike but need different answers, picking a threshold that does not transfer between domains, and paying for embeddings. Use it as a hint that returns a candidate answer for confirmation, not as a silent drop.
6. Duplicates inside the agent
Cache tool results per trace and state in the system prompt that known information must not be re-queried. Neither works well alone.
7. Measure it
Track duplicate share before dedup, hit rate, and error rate caused by dedup. Ship in observe-only mode for a week before enforcing.
FAQ
Will dedup look unresponsive? Return an explicit in-progress state with an estimate.
Does it apply to writes? Yes, and it matters more. Pair the key with a unique constraint in the database.
Redis or database lock? Redis for throughput, unique index for strong consistency; combine both.
What TTL? Long enough to cover the maximum plausible retry interval for that business.
Related
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.