Skip to main content
Back to all articles
AI Engineering 4 min readUpdated September 26, 2026

Your Agent Cached the Tool Result. Why Did Five More Calls Still Hit the API?

Agent tool caching needs more than TTLs. Scope results by tenant and data version, coalesce concurrent misses with singleflight, and prevent stale reads from repopulating the cache after invalidation.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#Tool Result Caching#Singleflight#Cache Invalidation#Redis#TypeScript#Python#Production AI
On this page

An agent reads the same customer policy three times while working through a support request. A second agent asks for it too. Then the cache entry expires and five requests hit the source at once.

Those calls have the same inputs, but the runtime performs the same expensive work repeatedly.

Caching the result helps. It does not solve the entire problem.

A useful tool cache needs three separate rules: what counts as the same read, who owns an in-progress read, and when an old result stops being valid.

That is the difference between a quick Map and something I would trust inside a production agent.

The key is part of the authorization boundary

I would not cache by prompt text or just the tool name.

Two calls to get_policy are only interchangeable when the effective inputs and access context match. A practical key includes the tool version, normalized arguments, tenant, permission scope, and underlying data generation.

For example:

Text
tool: get_policy:v2tenant: customer-42args: policyId=refundsscopeVersion: grant-17dataVersion: policy-86

Normalize JSON argument ordering before hashing general tool inputs. Do not include secrets in readable cache keys or logs. And perform authorization before serving a cache hit: possession of a key is not permission to see the value.

I use the same rule for failures: do not cache an arbitrary timeout as though it were a valid "not found." A genuine absence may deserve a short negative TTL; a transient error does not.

Cache and singleflight do different jobs

A TTL cache answers a later request from a completed result.

Singleflight answers concurrent identical requests with one shared, still-running operation. Once that operation finishes, the in-flight entry disappears. It does not replace the TTL cache.

This is the flow I want:

Tool result cache with singleflight and generation-aware invalidation

The first caller becomes the loader. The others await the same promise. A successful result is cached only if the relevant data version has not changed while that read was running.

Here is a deliberately small in-process illustration using an explicit scoped key. The surrounding trusted application must validate the arguments, authorize the caller, and supply scopeVersion and dataVersion from authoritative state rather than model output.

type ReadKey = {  tenantId: string;  policyId: string;  scopeVersion: string;  dataVersion: string;};​const cache = new Map<string, {  value: string;  expires: number;}>();const flights = new Map<string, Promise<string>>();const generations = new Map<string, number>();​const baseKey = (key: ReadKey) =>  JSON.stringify([    "get_policy:v2", key.tenantId,    key.policyId, key.scopeVersion, key.dataVersion,  ]);​async function cachedPolicy(  input: ReadKey,  load: () => Promise<string>,): Promise<string> {  const base = baseKey(input);  const generation = generations.get(base) ?? 0;  const key = JSON.stringify([base, generation]);  const hit = cache.get(key);​  if (hit && hit.expires > Date.now()) return hit.value;​  const existing = flights.get(key);  if (existing) return existing;​  const pending = load().then((value) => {    if ((generations.get(base) ?? 0) !== generation) {      return cachedPolicy(input, load); // old result cannot refill cache    }    cache.set(key, { value, expires: Date.now() + 30_000 });    return value;  });​  flights.set(key, pending);  try {    return await pending;  } finally {    if (flights.get(key) === pending) flights.delete(key);  }}​function invalidatePolicy(input: ReadKey) {  const base = baseKey(input);  generations.set(base, (generations.get(base) ?? 0) + 1);}

These examples are process-local and explain the mechanism, not a complete distributed cache. For multiple API replicas, a Redis-backed cache plus coordinated stampede protection is needed. Independent process-local singleflight maps cannot collapse requests arriving at different replicas.

Invalidation has a race that TTL does not fix

Imagine this sequence:

Text
read starts against policy v1policy changes to v2cache entry gets deletedold read finishes and caches v1

The delete happened, but the old result arrived afterward.

Redis's client-side caching documentation describes this same class of stale-fill race: an invalidation can arrive before an older read reply.

That is why the example uses a generation in the key and checks it *again before storing*. After a write, invalidate the affected generation and ensure subsequent callers use the current authoritative data version. An old flight cannot refill the new generation's cache.

A TTL is still useful as a backstop; it is not your only freshness strategy.

Do not cache an action

A read result cache is not an idempotency system for issue_refund, send_email, or update_customer.

For a write, use a stable idempotency key at the authoritative service and record the execution outcome in the workflow. Returning a remembered response from a normal TTL cache cannot prove that the side effect did or did not happen.

I covered that separately in agent idempotency and side-effect safety.

Keep this cache for explicitly eligible reads and pure computations. Treat personalized search results as scoped, versioned data. Never let one tenant's result bleed into another tenant's prompt.

Measure the work you actually avoided

A high cache-hit percentage can still hide poor behavior. I would monitor cache hits, joined in-flight calls, upstream calls avoided, stale-read incidents, invalidation lag, and p95 latency. After each invalidation, make sure a burst of callers does not overwhelm the source while the next entry is being rebuilt.

Start with a small allowlist of repeated, costly reads. Choose TTLs based on how quickly the underlying data changes. Add event-driven invalidation for writes you control.

The goal is simple: reuse work when it is truly the same work, and stop reusing it the moment that assumption becomes false.

References

KEEP READING

Related engineering notes