AI Gateway · Exercise 02
Cache responses
Turn on exact-match response caching so repeat questions return in milliseconds for $0, and opt out per request with skipCache.
Paste this into your agent
Copied! Now paste it into your agent. No agent yet? Here's how to get one.
Cache responses
The cheapest, fastest model call is the one you don’t have to make. Support bots, documentation search, and classification endpoints often see the exact same question many times. A gateway cache hit skips the model call completely — returning in tens of milliseconds instead of seconds and costing $0 in model tokens — while still letting your code opt out on individual requests.
What you’ll build
Exact-match response caching on your gateway and a skipCache option on your Worker’s /ask route. You’ll send the same prompt twice to see a cache hit in the gateway logs and dashboard, then bypass the cache for a fresh answer.
Prerequisites
- You’ve completed See every request and still have that Worker and gateway.
Exact-match caching and skipCache
When caching is enabled on your gateway (or per call with cacheTtl), AI Gateway hashes the provider, endpoint, model, provider auth header, and full request body. Adding caching to the pipeline from Exercise 1 short-circuits repeat requests before they reach the model provider:
If an identical request arrives before the TTL expires, the gateway returns the stored response without calling the provider:
src/index.tsconst result = await env.AI.run(
"@cf/google/gemma-4-26b-a4b-it", // any affordable Workers AI chat model
{ messages: [{ role: "user", content: prompt }] },
{
gateway: {
id: "dev-school-gateway",
metadata: { user, team },
cacheTtl: 300,
skipCache: Boolean(skipCache),
},
},
);
Because the default cache key matches on the request body and not on metadata, two different users sending the exact same prompt will share a cached answer. That’s what you want for shared FAQs or classification prompts. For personalized prompts, pass skipCache: true or set a custom cacheKey that includes the user ID.