← Blog

Claude API Response Caching with Redis

2026-11-24 · 5 min read · SubToAPI Team

If you're searching for "claude api response caching redis," you're almost certainly trying to solve one of two problems: your Claude API bill is climbing because you're sending the same or similar prompts repeatedly, or your app feels slow because every request pays the full round-trip latency of a model call. Redis solves both. It sits in front of your Claude API calls as a fast, shared cache layer: identical requests get served from memory in single-digit milliseconds instead of waiting on a model generation that can take seconds.

This is an application-level cache, distinct from Anthropic's native prompt caching (which caches large reusable prompt prefixes server-side). Redis caching works at a different layer — it caches the full response for a given input, so you skip the API call entirely on a hit. The two techniques are complementary: use prompt caching to make uncached calls cheaper, and use Redis to avoid making the call at all when you already know the answer.

When Redis caching makes sense

Caching Claude responses is a good fit when:

It's a poor fit for genuinely unique, user-specific, or time-sensitive prompts (live chat where context changes every turn, requests involving "today's date," or anything requiring fresh information).

Designing the cache key

The cache key has to capture everything that affects the output: the model, the full message array, system prompt, temperature, max tokens, and any tool definitions. If you leave something out, you'll serve stale or wrong responses.

const crypto = require("crypto");

function buildCacheKey(request) {
  const normalized = JSON.stringify({
    model: request.model,
    system: request.system || "",
    messages: request.messages,
    temperature: request.temperature ?? 1,
    max_tokens: request.max_tokens,
    tools: request.tools || [],
  });

  const hash = crypto.createHash("sha256").update(normalized).digest("hex");
  return `claude:resp:${hash}`;
}

Hashing the full request is safer than trying to cache on the "user question" alone, since small changes to system prompts or tool schemas can meaningfully change output.

Basic cache-aside pattern

The simplest and most robust pattern is cache-aside: check Redis first, call the API on a miss, store the result, return it.

const Redis = require("ioredis");
const redis = new Redis(process.env.REDIS_URL);

async function getCachedCompletion(request) {
  const key = buildCacheKey(request);

  const cached = await redis.get(key);
  if (cached) {
    return JSON.parse(cached);
  }

  const response = await callClaudeApi(request);

  // Cache for 1 hour; adjust based on how volatile your prompts are
  await redis.set(key, JSON.stringify(response), "EX", 3600);

  return response;
}

If you're routing through SubToAPI, callClaudeApi is just an HTTPS call to your sub_live_... key — the caching layer sits entirely outside that call, so nothing about your API integration changes. See the quickstart and messages docs for the request shape to hash.

Streaming responses need a different approach

You can't cache a stream the same way you cache a single JSON object, because the client expects chunks over time, not an instant full payload. Two practical options:

  1. Cache the assembled final text, then replay it as a simulated stream on cache hits (chunk it client-side or server-side with small delays). This preserves UX consistency without a second model call.
  2. Only cache non-streaming calls and route repeat-prone traffic (FAQs, batch jobs) through non-streaming requests, reserving real streaming for genuinely novel, interactive conversations.

If you're using SubToAPI's streaming endpoint for live chat, it's common to cache only the non-streaming "lookup" paths and leave conversational turns uncached.

TTL and invalidation strategy

Pick TTLs based on how often the "correct" answer changes:

For invalidation, avoid trying to selectively delete keys — the hash-based key scheme makes that hard. Instead, version your cache namespace:

const CACHE_VERSION = "v3"; // bump when prompts/templates change
const key = `claude:resp:${CACHE_VERSION}:${hash}`;

Bumping CACHE_VERSION instantly invalidates everything without a Redis FLUSHALL, which is safer in shared Redis instances.

Caching tool-use responses

If your requests involve tool use, cache the full response object including tool_calls, not just text. Your downstream code likely branches on tool call presence, so a partial cache will break that logic. Include the tool schema in the cache key hash — changing a tool's parameters should invalidate cached results that used the old schema.

Watch for cost and correctness tradeoffs

Caching reduces API spend, but it can mask bugs: if you cache an error response or a malformed output, you'll keep serving it until the TTL expires. Guard against this explicitly:

if (response.stop_reason === "error" || !response.content?.length) {
  return response; // don't cache
}
await redis.set(key, JSON.stringify(response), "EX", 3600);

Also monitor cache hit rate. If it's below ~15-20%, the operational overhead of running Redis probably isn't worth it for your traffic pattern — you're better off relying on Anthropic's native prompt caching and efficient batching instead.

Where this fits with SubToAPI

None of this caching logic depends on which provider you're calling through — it's pure application infrastructure that sits in front of any HTTPS API. If you're using SubToAPI to turn your Claude access into application API keys with usage metadata per key, Redis caching reduces the request volume hitting those keys, which directly lowers consumption on Solo, Team, or Scale plans. You can test the pattern during the free trial at signup before wiring it into production.

questions

Does Redis caching replace Claude's prompt caching? No. Prompt caching (Anthropic-side) reduces the cost of a single call by reusing cached prompt prefixes. Redis caching (your infrastructure) skips the call entirely on exact-match repeats. Use both together for maximum savings.

What TTL should I use for cached Claude responses? It depends on content volatility: hours to days for static reference answers, minutes or no caching at all for anything involving live data, current events, or personalized context.

Can I cache streaming responses in Redis? Not directly as a stream. Cache the final assembled text and replay it as a simulated stream on hits, or restrict caching to non-streaming request paths like batch jobs and FAQ lookups.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →