← Blog

Claude API Caching Layer with Redis: Setup Guide

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

If you're calling the Claude API repeatedly with similar or identical prompts, a Redis caching layer sits in front of your requests and returns stored responses instantly instead of hitting the model again. This guide covers how to set it up: picking a cache key strategy, choosing TTLs, handling streaming responses, and avoiding the pitfalls that make caches return stale or wrong answers.

The core idea is simple — before you send a request to Claude, hash the relevant inputs (model, messages, system prompt, tool definitions) into a cache key, check Redis for that key, and only call the API if there's a miss. This works best for deterministic or near-deterministic workloads: FAQ bots, document Q&A over static content, classification tasks, and any flow where the same question gets asked often.

Why cache Claude API responses at all

Two reasons dominate: latency and cost. A cached response returns in single-digit milliseconds from Redis versus hundreds of milliseconds to a few seconds for a live model call. Cost-wise, every cache hit is a request you don't pay tokens for.

This is different from prompt caching (Anthropic's own feature for reusing large system prompts or context on their side). A Redis layer caches the entire response for a given input, client-side, under your control. You can use both together — prompt caching reduces the cost of cache misses, while Redis eliminates repeated calls entirely for identical inputs.

Setting up Redis for API response caching

1. Provision Redis

For production use, a managed Redis instance (Upstash, Redis Cloud, AWS ElastiCache) is easier than self-hosting. For local development:

docker run -d --name claude-cache -p 6379:6379 redis:7-alpine

2. Design your cache key

The key must capture everything that affects the output: model name, temperature, system prompt, tool schemas, and the full message array. Don't just hash the last user message — two conversations with different history will produce different valid answers even if the final question is the same.

import { createHash } from "crypto";

function buildCacheKey(payload) {
  const relevant = {
    model: payload.model,
    temperature: payload.temperature ?? 1,
    system: payload.system ?? "",
    tools: payload.tools ?? [],
    messages: payload.messages,
  };
  const hash = createHash("sha256")
    .update(JSON.stringify(relevant))
    .digest("hex");
  return `claude:cache:${hash}`;
}

3. Check cache before calling the API

import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function getCachedOrFetch(payload) {
  const key = buildCacheKey(payload);
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const response = await fetch("https://api.subtoapi.app/v1/messages", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
  });
  const data = await response.json();

  await redis.set(key, JSON.stringify(data), { EX: 3600 });
  return data;
}

The EX: 3600 sets a one-hour TTL. The right TTL depends entirely on your use case — static document Q&A can cache for days, while anything referencing live data (prices, inventory, dates) should expire in minutes or not be cached at all.

4. Don't cache streaming responses the naive way

If you're using streaming (see /docs/streaming), you can't just dump a stream into Redis. Buffer the full response server-side, cache the complete text, and on a cache hit, replay it as a simulated stream (chunking the cached string) so your frontend behaves consistently either way:

function replayAsStream(text, res) {
  const chunks = text.match(/.{1,40}/g) || [];
  let i = 0;
  const interval = setInterval(() => {
    if (i >= chunks.length) {
      clearInterval(interval);
      return res.end();
    }
    res.write(`data: ${JSON.stringify({ delta: chunks[i] })}\n\n`);
    i++;
  }, 20);
}

5. Invalidate deliberately

Set up explicit invalidation for anything tied to source data that changes — a DEL call when the underlying document updates, or a versioned key prefix (claude:cache:v2:...) you bump when you change prompts or tool definitions. Silent stale caches are the most common failure mode.

What not to cache

Where this fits with SubToAPI

If you're already routing Claude calls through SubToAPI — turning your Claude access into an HTTPS API with application keys, streaming, and usage metadata — the Redis layer sits entirely in your own application code, in front of your calls to https://api.subtoapi.app/v1/messages. SubToAPI's usage metadata (see /docs/messages) also gives you a way to verify cache effectiveness: compare token usage before and after adding the cache layer to confirm you're actually reducing calls. Check /docs/quickstart if you're setting up API access for the first time, and /pricing for plan details across Solo, Team, and Scale tiers.

Monitoring cache performance

Track hit rate, not just presence of a cache. A low hit rate means your key strategy is too strict (small, inconsequential differences in messages are causing misses) or your TTL is too short. A simple counter in Redis works fine to start:

await redis.incr(cached ? "cache:hits" : "cache:misses");

Pull the ratio periodically and adjust TTLs or key granularity based on real data rather than guessing.

questions

Does Redis caching work with Claude's tool use? Yes, but tool definitions must be included in the cache key hash. If tool schemas change between requests, treat it as a different input — otherwise you risk serving a response generated against an outdated tool set.

How long should I set the TTL? It depends on data freshness needs: static content can use hours or days, anything involving live or frequently changing data should use minutes or be excluded from caching entirely.

Can I cache streaming responses? Not directly as a stream. Buffer and store the full response text, then replay it as simulated chunks on a cache hit so your frontend handles both cases the same way.

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 →