How do you implement prompt caching in Anthropic Claude API to reduce latency and input token costs by 90%? | A1Lab@HamzaM to AI & LLMEnglish • 5 days ago

How do you implement prompt caching in Anthropic Claude API to reduce latency and input token costs by 90%?

message-square
0

How Prompt Caching Cuts Costs and Latency in Claude

Anthropic’s prompt caching lets Claude reuse previously processed prompt prefixes instead of re-computing them from scratch on every API call.

  • Up to 90% lower cost on cached reads: Reading cached input tokens costs 0.1x (10%) of the base input token price on standard models, while writing to the cache costs slightly more (1.25x for a 5-minute TTL or 2x for a 1-hour TTL).
  • Faster time to first token (TTFT): Skipping redundant prompt processing over long system instructions, reference docs, or chat history lowers latency significantly.
  • Prefix order matters: Caching matches from the start of the prompt up to a cache breakpoint (cache_control), so static content (tools, system prompt, documents) should come first and changing content (user questions) should come last.

Two Ways to Enable Prompt Caching

  1. Explicit cache_control breakpoints: Add "cache_control": {"type": "ephemeral"} (and optional "ttl": "1h" if you need a 1-hour lifetime instead of the default 5 minutes) to specific blocks like a long system prompt or document block.
  2. Automatic caching: Set a top-level "cache_control" field on the request so Claude moves the cache breakpoint forward automatically as multi-turn conversations grow.

Node.js Example Using Explicit Cache Breakpoints

import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

async function askWithCachedContext(longReferenceDoc, userQuestion) {
  const response = await anthropic.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 1024,
    system: [
      {
        type: "text",
        text: "You are a technical assistant. Answer strictly using the provided reference documentation.",
        cache_control: { type: "ephemeral" },
      },
    ],
    messages: [
      {
        role: "user",
        content: [
          {
            type: "text",
            text: longReferenceDoc,
            cache_control: { type: "ephemeral" },
          },
          {
            type: "text",
            text: userQuestion,
          },
        ],
      },
    ],
  });

  // Inspect cache writes vs. cache hits in usage metrics
  console.log("Usage:", response.usage);

  return response.content
    .filter((block) => block.type === "text")
    .map((block) => block.text)
    .join("");
}

const sampleDoc = "API reference manual content...".repeat(200);
const answer = await askWithCachedContext(sampleDoc, "How do I authenticate requests?");
console.log(answer);

Helpful Tips for Real Apps

  • Keep cached prefixes byte-identical: Putting dynamic data like timestamps or request IDs inside a cached block breaks the cache prefix hash on every call.
  • Watch the cache TTL: The default cache lifetime is 5 minutes (refreshed on hits), with a 1-hour option available—if requests arrive less often than that, you pay cache write costs without getting enough cache reads.
  • Check response.usage: Monitor cache creation and cache read token counts in your logs to confirm your breakpoints are hitting as expected.