Result Caching: Making Agent Tool Calls Cheap to Repeat
Learn how to cache AI agent tool results without lying to the model: a read-only cacheability boundary, canonicalized keys that embed scope, per-tool TTL contracts instead of harness guesswork, epoch-fenced invalidation so the agent reads its own writes, cache markers and freshness knobs the model can actually see, and a fake-clock CI harness that proves a tenant leak or a stale read can never ship.
An agent works a refund dispute for order 8123. Over nine steps it fetches the customer record four times, the order twice, and the returns policy three times. Every fetch is a round trip, a re-serialization of the same JSON into the context window, and another debit against the backend's rate limit. Worse: between the second and third customer fetch, the customer changes their contact email — and the agent, reasoning over two different snapshots in the same transcript, drafts the confirmation to the old address.
None of those fetches were wrong. Agent loops legitimately re-check state after every write, re-validate assumptions mid-plan, and re-fetch context when a step fails and the model backs up. The bug is that the tool layer treats identical questions as brand new every time. Idempotency keys made repeats safe; result caching makes them cheap — and, done right, more consistent than the accidental re-fetches it replaces.
Naive caching in an agent loop is also one of the fastest ways to build a system that confidently lies. This article walks the full contract: what may be cached, how keys are built, where TTLs come from, how writes invalidate, what the model gets told, and the tests that keep all of it honest.
What actually repeats in an agent run
Read traffic in agent sessions clusters in three shapes. The re-check loop: after any write, a careful model fetches the affected resource to confirm the effect — update_ticket, then get_ticket. The shared-context fan-out: parallel tool calls that each need the same substrate, like five checks against the same account. And the plan template: multi-step procedures that reference the same policy document or price list at several steps.
All three shapes are reads, and reads vastly outnumber writes in most agent workloads — the write path already has its own machinery (idempotency keys, command ledgers, serialized writes). That asymmetry is the opportunity: a cache over the read path pays back in latency, in tokens (a 4 KB response re-serialized six times is 24 KB of context you paid for five times over), and in backend load.
The consistency argument is the one teams miss. A bounded-age cached read gives a decision a single snapshot to reason over. Six independent re-fetches give the decision six snapshots and a race — the agent that read the customer before and after the email change was never working with one world. Caching is not just speed; it is deciding, deliberately, which snapshot a decision gets.
The boundary: only proven reads are cacheable
Before any key or TTL, answer one question per tool: is this call observably a read? Not "usually" — provably. A tool is cacheable when identical arguments plus identical upstream state produce an identical response and the call mutates nothing: no rows written, no messages enqueued, no counters bumped, no audit log appended. If you cannot prove that from the implementation, the tool is not cacheable, whatever its name says. preview_* tools that execute dry-runs against live engines fail this test the first time someone makes the preview side-effecting.
Then carve out the never-cache classes, even inside proven reads:
- Authority decisions — permission checks and policy evaluations. Their entire value is being current; a cached "allowed" is an authorization bypass with extra steps.
- Wall-clock and sequence semantics — anything returning "now", tick counters, or queue positions. The response is stale by construction before it lands.
- Quota and limit state — "how many calls remain" must observe the debit you just caused.
- Anything sensitive to the caller's identity beyond the key — if the backend varies output by properties not present in the arguments, no key can save you (next section makes those properties explicit instead).
Encode the verdict in the tool contract, not in harness folklore. The schema gains a cache hint, and the harness refuses to cache anything undeclared:
{
"name": "get_customer",
"description": "Fetch the customer record for an order's owner.",
"parameters": {
"type": "object",
"properties": {
"customer_id": { "type": "string" },
"max_age_s": { "type": "integer", "minimum": 0 }
},
"required": ["customer_id"]
},
"x-cache": { "mode": "read", "ttl_s": 300, "key": ["customer_id", "scope"] }
}
x-cache.mode: "read" is the proof claim; ttl_s is the freshness contract (next sections). Undeclared tools bypass the cache entirely — fail closed, default to fresh.
The key: canonical arguments plus scope, or nothing
A cache key that misses either half of this is broken in a different direction. Miss canonicalization and hit rate collapses; miss scope and you leak data across tenants.
Canonicalize the arguments. Same logical call, two shapes:
{"customer_id": "cus_8123", "include": ["emails", "orders"]}
{"include": ["emails", "orders"], "customer_id": "cus_8123"}
Key on the serialized form and these are two entries; the second one misses forever. Canonical form means: sort object keys, sort unordered list fields that are sets in spirit, strip default-valued fields to their defaults' absence, normalize whitespace where it carries no meaning. Pagination needs its own move: a cursor encodes where you are, not what you asked, so a cursor in the key means near-zero hits. Normalize cursor + limit into the data range it denotes (offset=200..300) so a later call covering the same rows — perhaps with a different cursor value from a parallel branch — hits.
Embed the scope. The key must include everything the backend varies output by: tenant, acting principal, data region, feature flags if they gate fields. The canonical bug: multi-tenant deploy, key tool:args without tenant — agent A caches customer 8123's record, agent B (another tenant, same numeric ID) reads it. That is a cross-tenant data leak with a cache hit rate telling you it's working great.
def cache_key(tool, args, scope):
canonical = json.dumps(
{"tool": tool, "args": canonicalize(args), "scope": scope.as_dict()},
sort_keys=True, separators=(",", ":"),
)
digest = sha256(canonical.encode()).hexdigest()[:16]
log.debug("cache_key", preimage=canonical) # log the preimage, not just the hash
return f"{tool}:{digest}"
Log the preimage alongside the digest. When a hit rate collapses or a leak is suspected, you will need to see what actually went into the key, and digests alone tell you nothing.
TTL is a per-tool contract, not a harness guess
Freshness is a property of the data, so the tool that owns the data declares it. Customer profiles tolerate five minutes; a price list, a day; an account balance, nothing at all. The harness picking one global TTL produces the worst of both — stale where it hurts, short where it wastes. Three refinements:
Negative results cache briefly. A 404 on get_order cached for sixty seconds turns re-check loops from backend load into cache hits — but keep it short, because the agent's own next write may create the thing that was missing. That interplay (write, then immediately re-read the not-found path) is exactly the read-your-writes hazard below; the epoch fence covers it.
Never cache failures of the transport. 429s and 5xx are statements about the backend's minute, not the data — caching them makes the cache an outage amplifier. Failures of the request (4xx validation, 404) are statements about the data and may cache briefly. The distinction is the same one the retry policy already draws; reuse it.
Let the model ask for fresher. The max_age_s parameter above is the quiet power move: the caller states how stale a result may be for this decision. The harness serves a cached entry only when entry.age <= min(tool_ttl, requested_max_age). A model that is about to spend money forces freshness; one that is re-confirming context mid-plan happily takes the five-minute-old copy. Freshness becomes a per-call decision instead of a global compromise.
Read-your-writes: the invalidation fence
Here is the failure that gives agent caching its black eye. The agent calls create_draft_refund, succeeds, then re-reads the order to confirm — and the cache, TTL unexpired, returns the pre-write snapshot. No draft in the list. The model concludes the write failed and creates a second draft. Idempotency keys may catch the duplicate, but now you are spending your safety margin on a bug you created yourself.
TTL alone cannot fix this: no TTL is short enough to be correct and long enough to be useful. The write path must participate. The clean mechanism for agent-shaped workloads is an epoch fence per scope:
def execute_write(tool, args, scope):
result = backend.call(tool, args)
ledger.append(scope, tool, result) # command-ledger entry, as usual
cache.bump_epoch(scope) # writes fence the scope's reads
return result
def cache_get(key, scope):
entry = store.get(key)
if entry and entry.epoch == store.epoch(scope) and entry.age <= ttl(tool):
return entry
return None # miss: fetch fresh
Every write to a scope bumps that scope's epoch; entries written against an older epoch are dead regardless of TTL. The re-check-after-write loop now always observes its own write — the fence is exactly as fine-grained as the scope you choose. Tenant-wide epochs are coarse but trivial; per-resource epochs (bump customer:8123 on any write touching it) are precise and worth it for hot resources. Invalidation-by-subscription (the backend publishes change events the cache consumes) is the shared-infrastructure version of the same fence — fine when you own the backend, but keep the epoch check anyway; event delivery is exactly as reliable as the bus it rides on.
Where the cache lives
Two layers, two jobs. The harness-side cache lives in the agent's process, keyed per run: zero cross-process coherence, zero shared state, and it dies with the run — perfect for the re-check and fan-out shapes, which are intra-run by nature. Cap it by tokens, not entries (a 30-entry cache of fullHttpResponse-sized objects is a context budget accident), evict LRU, and reset it between user turns if your runs are long-lived conversations.
The backend-side cache (or a shared Redis in front of the tools) survives runs and serves many agents: real hit rates, real invalidation, one coherence owner. The failure mode is stacking both naively — harness TTL 300 s over backend TTL 300 s gives a worst-case staleness of 600 s that nobody declared. If both layers exist, make the harness layer turn-scoped (seconds) and let the backend layer own every TTL measured in minutes. One layer holds the freshness contract; the other is a request coalescer.
Tell the model, measure the cache
A cached result must be marked as one, in the envelope the model reads:
{
"customer_id": "cus_8123",
"email": "[email protected]",
"cache": { "hit": true, "age_s": 217, "fresh_until_s": 83 }
}
Not so the model can thank you — so its behavior is debuggable, and so a downstream tool call that acted on stale data has the evidence attached. Pair it with the metrics only operators can read: hit rate per tool, age-at-use distribution, forced-fresh (max_age_s: 0) call count, and epoch-invalidated entries per run. A hit rate that collapses after a backend deploy is the signature of a canonicalization break — some field in the arguments changed shape and every key silently rotated. That alert has caught more "the agent got slow" incidents than any latency dashboard.
Single-flight for the fan-out
Parallel tool calls that share a substrate arrive within milliseconds of each other, and a plain cache serves all of them misses — five in-flight fetches for one answer. Single-flight per key: the first caller executes, the rest await the same promise. This is ten lines in the harness and it converts the fan-out shape from multiplier to free. Bound the wait (a slow first call shouldn't wedge five siblings — they can degrade to independent fetches on timeout) and count both outcomes: coalesced_waiters next to hit and miss in the metrics above.
Prove it with a fake clock
Every property above is testable without a network. The harness that makes it cheap is a fake store plus a fake clock — TTLs and epochs move when you say so:
def test_read_after_write_never_serves_pre_write_snapshot():
store = FakeCacheStore(clock=FakeClock())
agent = FakeAgent(cache=CachingLayer(store, tools=TOOL_CONTRACTS))
agent.call("get_order", order_id="8123") # miss, cached at t=0
agent.call("create_draft_refund", order_id="8123") # write: epoch bumps
fresh = agent.call("get_order", order_id="8123") # fence: must miss
assert fresh["cache"]["hit"] is False
assert fresh["draft_refunds"] == 1 # the write is visible
def test_scope_is_in_the_key():
a = agent_for(tenant="acme").call("get_customer", customer_id="8123")
b = agent_for(tenant="globex").call("get_customer", customer_id="8123")
assert a["cache"]["hit"] is False and b["cache"]["hit"] is False
assert a["email"] != b["email"] # no cross-tenant hit
def test_ttl_expiry_and_negative_cache():
agent.call("get_order", order_id="nope") # 404, cached 60 s
assert agent.call("get_order", order_id="nope")["cache"]["hit"] is True
clock.advance(61)
assert agent.call("get_order", order_id="nope")["cache"]["hit"] is False
Add the single-flight test (five concurrent identical calls, assert exactly one upstream fetch) and the max_age_s override (cached entry within TTL, request forces freshness, assert miss), and the whole contract is pinned. Run one integration pass against a real backend in CI; keep the rest fast. A caching layer without these tests will pass every review and leak the first tenant that shares an ID.
The read path gets a memory
The rules compress to five. Only proven reads are cacheable — authority, clocks, and quota state never are, and undeclared tools bypass the cache entirely. Keys are canonical arguments plus scope, or they are collisions waiting for a victim. TTL belongs to the tool that owns the data, negative results cache briefly, transport failures never, and the model can always ask for fresher. Writes fence their scope with an epoch so an agent always reads its own writes. And the cache reports itself — marked entries, hit rates, ages — because an unmarked cache is just a liar with a good hit rate.
The series built the write path first for a reason: retries made safe, commands ledgered, writes serialized. With those fences up, the read path can afford a memory. Idempotency keys made the second call safe; a real cache makes it free — and the agent that re-checks everything becomes the reliable one, not the expensive one.
About this story
This article was written by Gen-AI using GPT 5.5 or Opus 4.7. Verify technical guidance before using it in production systems.