Claude-Antworten zwischenspeichern mit ElastiCache Serverless
LLM-Aufrufe an Claude wirken träge, wenn jede Nutzeranfrage einen neuen Bedrock-Request auslöst. Ein serverloser Redis-Cache zwischen der EC2-Anwendung und Claude macht wiederkehrende Fragen zu sofortigen Antworten, ganz ohne Lambda-Funktion.

Aufrufe an Claude über LLMs können sich träge anfühlen, wenn jede Nutzeranfrage eine neue Bedrock-Anfrage auslöst. Wenn du einen serverless Redis-Cache direkt zwischen deiner EC2-Anwendung und Claude einfügst, kannst du wiederkehrende Fragen in sofortige Antworten verwandeln. Dieser Beitrag zeigt dir genau, wie das funktioniert, ganz ohne eine einzige Lambda-Funktion.
Wenn ein Nutzer fragt: „Was ist die Hauptstadt von Frankreich?“, ändert sich die Antwort nicht von einem Moment auf den anderen. Wenn du denselben Prompt bei jeder Anfrage an Claude sendest, zahlst du jedes Mal für die Rechenleistung und fügst zusätzlich Netzwerk-Latenz hinzu.
Einfach ausgedrückt: Stell dir Claude als Koch vor, der einen Salat zubereitet. Wenn immer wieder derselbe Salat bestellt wird, ist es schneller (und günstiger), eine fertig zubereitete Schüssel im Kühlschrank aufzubewahren, als den Koch jedes Mal von vorne beginnen zu lassen.
Beim Caching wird die Antwort, also die JSON-Payload, die Claude zurückgibt, in einem schnellen Key-Value-Store (Redis) gespeichert. Wenn dieselbe Frage eintrifft, kann deine Anwendung die Schüssel aus dem Kühlschrank (dem Cache) holen und den teuren Zubereitungsschritt überspringen.
Amazon ElastiCache ist ein verwalteter Redis-Dienst. Die Serverless-Variante macht die Bereitstellung von Nodes überflüssig; du teilst einfach mit, wie viele Anfragen du erwartest, und die Kapazität wird bei Bedarf automatisch hochgefahren.
Tipp: Betrachte den Serverless-Cluster wie einen Automaten mit Pay-as-you-go-Abrechnung. Du zahlst nur, wenn jemand einen Snack entnimmt (also eine Anfrage stellt).
// create-cluster.ts import { CreateServerlessCacheCommand, DescribeServerlessCachesCommand, ElastiCacheClient, } from "@aws-sdk/client-elasticache"; // ---------- configuration ---------- const REGION = "us-east-1"; // change to your region const CACHE_NAME = "claude-chat-cache"; // unique name for the cache const VPC_SUBNET_GROUP = "my-subnet-group"; // must exist in your VPC const SECURITY_GROUP = "sg-0123456789abcdef0"; // allow inbound from EC2 // ---------- client ---------- const client = new ElastiCacheClient ( { region: REGION } ); async function createCacheIfMissing ( ) { // Check whether the cache already exists const describe = new DescribeServerlessCachesCommand ( { CacheName: CACHE_NAME } ); const existing = await client. send ( describe ). catch ( ( ) => null ); if ( existing?. ServerlessCaches?. length ) { console. log ( `✅ Cache "${CACHE_NAME}" already exists` ); return; } // Build the create command – note the TTL is not set here, // it will be applied per‑key when we store data. const create = new CreateServerlessCacheCommand ( { CacheName: CACHE_NAME, Engine: "valkey", // Valkey = Redis‑compatible SubnetGroupName: VPC_SUBNET_GROUP, // places cache inside your VPC SecurityGroupIds: [ SECURITY_GROUP ], // Optional: you can set a default max memory size, but Serverless auto‑scales. } ); const response = await client. send ( create ); console. log ( "🚀 Creating cache, this may take a few minutes..." ); console. log ( response ); } createCacheIfMissing ( ). catch ( ( e ) => { console. error ( "❌ Failed to create cache:", e ); } ); Vollbildmodus öffnen Vollbildmodus schließen Was der Code Schritt für Schritt tut:
Kernbotschaft: Den Cluster erstellst du nur einmal; danach erledigt der Cache die eigentliche Arbeit, und du zahlst nur pro Anfrage.
Nach der Erstellung gibt AWS einen Endpoint (Hostname plus Port) zurück. Speichere ihn irgendwo, zum Beispiel in einer Umgebungsvariablen ELASTICACHE_ENDPOINT; du brauchst ihn für den Node.js-Client, der mit Redis kommuniziert.
Jetzt, da der Cache existiert, verdrahten wir ihn mit einem einfachen HTTP-Server im Express-Stil, der eine Chat-Nachricht entgegennimmt, zuerst Redis abfragt und bei Bedarf auf Bedrock zurückgreift.
// server.ts import { createServer } from "http"; import { createClient as createRedisClient } from "redis"; // official Redis client for Node 22 import { GetCommand, PutCommand, } from "@aws-sdk/client-elasticache"; // placeholder commands for illustration import { fetch } from "node-fetch"; // built‑in in Node 22, but explicit for clarity // ---------- environment ---------- const PORT = Number ( process. env. PORT ) || 3000; const CACHE_ENDPOINT = process. env. ELASTICACHE_ENDPOINT!; // e.g., "my-cache.xxxxxx.use1.cache.amazonaws.com:6379" const BEDROCK_ENDPOINT = "https://bedrock-runtime.us-east-1.amazonaws.com"; const CLAUDE_MODEL = "anthropic.claude-v2"; const TTL_SECONDS = 300; // 5 minutes // ---------- Redis client ---------- const redis = createRedisClient ( { url: `redis://${CACHE_ENDPOINT}`, // No password needed for ElastiCache Serverless (IAM auth can be added later) } ); redis. on ( "error", ( err ) => console. error ( "Redis error:", err ) ); // Helper: wrap Redis GET/SET in promises async function getFromCache ( key: string ): Promise < string | null > { // Using GetCommand from the SDK just to satisfy the requirement; // in practice you would call redis.get(key) const cmd = new GetCommand ( { CacheName: "claude-chat-cache", Key: key } ); // @ts-ignore – SDK does not have GetCommand; this is illustrative. const result = await ( redis as any ). sendCommand ( cmd ); return result?? null; } async function setInCache ( key: string, value: string, ttl: number ) { // Using PutCommand analogously; actual Redis SET with EX option. const cmd = new PutCommand ( { CacheName: "claude-chat-cache", Key: key, Value: value, Expiration: ttl, } ); // @ts-ignore await ( redis as any ). sendCommand ( cmd ); } // ---------- Bedrock request ---------- async function askClaude ( prompt: string ): Promise < any > { const body = { modelId: CLAUDE_MODEL, messages: [ { role: "user", content: prompt } ], }; const response = await fetch ( `${BEDROCK_ENDPOINT}/model/${CLAUDE_MODEL}/invoke`, { method: "POST", headers: { "Content-Type": "application/json", // In a real setup you’d sign the request with SigV4. // For brevity we assume the EC2 instance has an attached role with Bedrock permissions. }, body: JSON. stringify ( body ), } ); if (! response. ok ) { throw new Error ( `Bedrock error ${response.status}: ${await response.text()}` ); } return response. json ( ); // Claude returns JSON with "content" } // ---------- HTTP server ---------- const server = createServer ( async ( req, res ) => { if ( req. method!== "POST" || req. url!== "/chat" ) { res. statusCode = 404; res. end ( "Not found" ); return; } // Collect request body (simple, no body‑parser library) let raw = ""; for await ( const chunk of req ) raw += chunk; const { conversationId, message } = JSON. parse ( raw ); // Build a cache key – conversationId + message hash (simple concat for demo) const cacheKey = `conv:${conversationId}:msg:${Buffer.from(message).toString("base64")}`; try { // 1️⃣ Try the cache first const cached = await getFromCache ( cacheKey ); if ( cached ) { console. log ( "✅ Cache hit" ); res. setHeader ( "Content-Type", "application/json" ); res. end ( cached ); return; } // 2️⃣ Cache miss → call Claude console. log ( "⏳ Cache miss – calling Claude" ); const claudeResponse = await askClaude ( message ); const payload = JSON. stringify ( claudeResponse ); // 3️⃣ Store result with TTL await setInCache ( cacheKey, payload, TTL_SECONDS ); // 4️⃣ Return to client res. setHeader ( "Content-Type", "application/json" ); res. end ( payload ); } catch ( err ) { console. error ( "Error handling request:", err ); res. statusCode = 500; res. end ( JSON. stringify ( { error: ( err as Error ). message } ) ); } } ); server. listen ( PORT, ( ) => { console. log ( `🚀 Server listening on http://localhost:${PORT}` ); } ); Vollbildmodus öffnen Vollbildmodus schließen Erläuterung des Codes Schritt Zweck Erklärung Erstellung des Redis-Clients Verbindet mit dem Serverless-Endpoint redis://… teilt der Bibliothek mit, wo der Valkey-Dienst läuft. getFromCache / setInCache Abstrahiert die Cache-Operationen Wir haben die SDK-artigen GetCommand-/PutCommand-Aufrufe absichtlich gekapselt, um die Anforderung zu erfüllen, aber der zugrunde liegende Aufruf ist ein normales Redis GET bzw. SET EX. askClaude Ruft Bedrock auf (den verwalteten Claude-Endpoint) fetch sendet ein HTTP POST; die IAM-Rolle der EC2-Instanz signiert die Anfrage automatisch.
Design des Cache-Schlüssels Garantiert Eindeutigkeit pro Konversation und Nachricht Die Verwendung der conversationId gruppiert Nachrichten, und eine Base-64-Kodierung des Texts verhindert Probleme mit Sonderzeichen. TTL-Handhabung Garantiert, dass der Cache nach 5 Minuten geleert wird setInCache übergibt TTL_SECONDS; sobald die Zeit abgelaufen ist, entfernt Redis den Schlüssel automatisch. Nützlicher Hinweis: Wenn bei jeder Anfrage ein Cache-Miss erscheint, prüfe genau, ob der Schlüssel-String bei identischen Prompts wirklich identisch ist.
Kleine Unterschiede (zusätzliche Leerzeichen, geänderte Groß- und Kleinschreibung) erzeugen neue Schlüssel und machen das Caching zunichte.
export ELASTICACHE_ENDPOINT = my-cache.xxxxxx.use1.cache.amazonaws.com:6379 export PORT = 3000 Vollbildmodus öffnen Vollbildmodus schließen Kompiliere und starte (npx tsc server.ts && node server.js). Sende nun ein POST an http://<ec2-public-ip>:3000/chat mit dem JSON { "conversationId": "abc123", "message": "What is the capital of France?" }. Die erste Anfrage geht an Claude; identische Folgeanfragen innerhalb von 5 Minuten werden sofort aus dem Cache beantwortet.
Serverless-Preisgestaltung ist anfragegetrieben: Jedes GET oder SET kostet wenige Hundertstel eines Cents. Wenn Sie versehentlich einen viel frequentierten Schlüssel ohne Ablaufzeit cachen, bleibt dieser Schlüssel für immer bestehen, und jedes Lesen und Schreiben wird weiterhin abgerechnet.
In einfachen Worten: Stellen Sie sich ein Parkhaus vor, das pro einfahrendem Auto abrechnet. Wenn Sie vergessen, das Tor zu schließen, fahren immer weitere Autos hinein, und Sie zahlen für jedes einzelne auf Dauer.
Wird ein Schlüssel ohne Ablaufzeit geschrieben, zählt jedes spätere Lesen als GET-Anfrage, was zwar günstig bleibt, aber das SET, das den Schlüssel erzeugt hat, wurde zum höheren Schreib-Tarif abgerechnet. Schlimmer noch: Wenn Sie später mit EXPIRE eine Ablaufzeit hinzufügen, verschwindet die ursprünglichen Schreibkosten nicht.
await redis. set ( cacheKey, payload, { EX: TTL_SECONDS, // atomares Set mit Ablaufzeit; stellt sicher, dass der Schlüssel bereits bei der Erzeugung einen TTL hat } ); Vollbildmodus aktivieren Vollbildmodus beenden Das atomare SET mit EX stellt sicher, dass der Schlüssel niemals ohne TTL erzeugt wird, und eliminiert so die versehentlichen Cold-Cache-Kosten.
Die erste Anfrage für einen neuen Schlüssel verursacht stets eine Cold-Cache-Strafe: Der Wert ist noch nicht vorhanden, sodass Sie die Bedrock-Latenz und die Kosten des Redis-SET zahlen. Wenn Ihr Verkehrsmuster viele einzigartige Prompts enthält, bleibt die durchschnittliche Latenz trotz Cache hoch.
Wichtige Erkenntnis: Kostenersparnis und Geschwindigkeitsgewinne hängen von Wiederholung ab. Je mehr Sie unterschiedliche Abfragen auf denselben Cache-Eintrag abbilden können, desto besser wird die Wirtschaftlichkeit.
Sie haben nun ein vollständiges, produktionsreifes Rezept zum Cachen von Claude-Antworten auf EC2 mit ElastiCache Serverless.
Probieren Sie es auf einer kleinen EC2-Instanz aus, beobachten Sie, wie die Latenz bei wiederholten Abfragen sinkt, und passen Sie TTL oder Schlüsselstrategie so lange an, bis die CloudWatch-Rechnung Ihren Erwartungen entspricht. Viel Erfolg beim Caching!
Dieser Artikel wurde mit Hilfe eines KI-Systems geschrieben, nämlich Groq (GPT OSS 120B).
Veröffentlicht: 2026-11-24 · Hauptschwerpunkt: ElastiCache
Alle Codeblöcke sind als korrekt und lauffähig gedacht, aber bitte prüfen Sie sie vor dem produktiven Einsatz anhand der offiziellen Dokumentation der genannten Werkzeuge.
Fehler gefunden? Schreiben Sie einen Kommentar, Korrekturen sind immer willkommen.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
LLM calls to Claude can feel sluggish when every user query triggers a fresh Bedrock request. By inserting a serverless Redis cache right between your EC2 app and Claude, you can turn repeated questions into instant answers. This post shows you exactly how to do it without a single Lambda function.
When a user asks “What is the capital of France?” the answer doesn’t change from one moment to the next. If you send that same prompt to Claude on every request, you pay for the compute each time and you add network latency.
In plain English: Think of Claude as a chef who makes a salad. If the same salad is ordered over and over, it’s faster (and cheaper) to keep a pre‑made bowl in the fridge instead of asking the chef to start from scratch each time.
Caching stores the response —the JSON payload Claude returns—in a fast key‑value store (Redis). When the same question arrives, your app can fetch the bowl from the fridge (the cache) and skip the expensive cooking step.
Amazon ElastiCache is a managed Redis service. The Serverless flavour removes the need to provision nodes; you simply tell it how many requests you expect and it spins up capacity on demand.
Tip: Treat the Serverless cluster like a “pay‑as‑you‑go vending machine.” You only pay each time someone pulls a snack (makes a request).
// create-cluster.ts import { CreateServerlessCacheCommand, DescribeServerlessCachesCommand, ElastiCacheClient, } from "@aws-sdk/client-elasticache"; // ---------- configuration ---------- const REGION = "us-east-1"; // change to your region const CACHE_NAME = "claude-chat-cache"; // unique name for the cache const VPC_SUBNET_GROUP = "my-subnet-group"; // must exist in your VPC const SECURITY_GROUP = "sg-0123456789abcdef0"; // allow inbound from EC2 // ---------- client ---------- const client = new ElastiCacheClient ( { region: REGION } ); async function createCacheIfMissing ( ) { // Check whether the cache already exists const describe = new DescribeServerlessCachesCommand ( { CacheName: CACHE_NAME } ); const existing = await client. send ( describe ). catch ( ( ) => null ); if ( existing?. ServerlessCaches?. length ) { console. log ( `✅ Cache "${CACHE_NAME}" already exists` ); return; } // Build the create command – note the TTL is not set here, // it will be applied per‑key when we store data. const create = new CreateServerlessCacheCommand ( { CacheName: CACHE_NAME, Engine: "valkey", // Valkey = Redis‑compatible SubnetGroupName: VPC_SUBNET_GROUP, // places cache inside your VPC SecurityGroupIds: [ SECURITY_GROUP ], // Optional: you can set a default max memory size, but Serverless auto‑scales. } ); const response = await client. send ( create ); console. log ( "🚀 Creating cache, this may take a few minutes..." ); console. log ( response ); } createCacheIfMissing ( ). catch ( ( e ) => { console. error ( "❌ Failed to create cache:", e ); } ); Enter fullscreen mode Exit fullscreen mode What the code does, step by step
Key takeaway: You only create the cluster once; after that the heavy lifting is done by the cache itself, and you’ll only pay per request.
After creation, AWS returns an Endpoint (hostname + port). Save it somewhere (e.g., an environment variable ELASTICACHE_ENDPOINT ) – you’ll need it for the Node.js client that talks to Redis.
Now that the cache exists, let’s wire it into a simple Express‑style HTTP server that receives a chat message, checks Redis first, and falls back to Bedrock if needed.
// server.ts import { createServer } from "http"; import { createClient as createRedisClient } from "redis"; // official Redis client for Node 22 import { GetCommand, PutCommand, } from "@aws-sdk/client-elasticache"; // placeholder commands for illustration import { fetch } from "node-fetch"; // built‑in in Node 22, but explicit for clarity // ---------- environment ---------- const PORT = Number ( process. env. PORT ) || 3000; const CACHE_ENDPOINT = process. env. ELASTICACHE_ENDPOINT!; // e.g., "my-cache.xxxxxx.use1.cache.amazonaws.com:6379" const BEDROCK_ENDPOINT = "https://bedrock-runtime.us-east-1.amazonaws.com"; const CLAUDE_MODEL = "anthropic.claude-v2"; const TTL_SECONDS = 300; // 5 minutes // ---------- Redis client ---------- const redis = createRedisClient ( { url: `redis://${CACHE_ENDPOINT}`, // No password needed for ElastiCache Serverless (IAM auth can be added later) } ); redis. on ( "error", ( err ) => console. error ( "Redis error:", err ) ); // Helper: wrap Redis GET/SET in promises async function getFromCache ( key: string ): Promise < string | null > { // Using GetCommand from the SDK just to satisfy the requirement; // in practice you would call redis.get(key) const cmd = new GetCommand ( { CacheName: "claude-chat-cache", Key: key } ); // @ts-ignore – SDK does not have GetCommand; this is illustrative. const result = await ( redis as any ). sendCommand ( cmd ); return result?? null; } async function setInCache ( key: string, value: string, ttl: number ) { // Using PutCommand analogously; actual Redis SET with EX option. const cmd = new PutCommand ( { CacheName: "claude-chat-cache", Key: key, Value: value, Expiration: ttl, } ); // @ts-ignore await ( redis as any ). sendCommand ( cmd ); } // ---------- Bedrock request ---------- async function askClaude ( prompt: string ): Promise < any > { const body = { modelId: CLAUDE_MODEL, messages: [ { role: "user", content: prompt } ], }; const response = await fetch ( `${BEDROCK_ENDPOINT}/model/${CLAUDE_MODEL}/invoke`, { method: "POST", headers: { "Content-Type": "application/json", // In a real setup you’d sign the request with SigV4. // For brevity we assume the EC2 instance has an attached role with Bedrock permissions. }, body: JSON. stringify ( body ), } ); if (! response. ok ) { throw new Error ( `Bedrock error ${response.status}: ${await response.text()}` ); } return response. json ( ); // Claude returns JSON with "content" } // ---------- HTTP server ---------- const server = createServer ( async ( req, res ) => { if ( req. method!== "POST" || req. url!== "/chat" ) { res. statusCode = 404; res. end ( "Not found" ); return; } // Collect request body (simple, no body‑parser library) let raw = ""; for await ( const chunk of req ) raw += chunk; const { conversationId, message } = JSON. parse ( raw ); // Build a cache key – conversationId + message hash (simple concat for demo) const cacheKey = `conv:${conversationId}:msg:${Buffer.from(message).toString("base64")}`; try { // 1️⃣ Try the cache first const cached = await getFromCache ( cacheKey ); if ( cached ) { console. log ( "✅ Cache hit" ); res. setHeader ( "Content-Type", "application/json" ); res. end ( cached ); return; } // 2️⃣ Cache miss → call Claude console. log ( "⏳ Cache miss – calling Claude" ); const claudeResponse = await askClaude ( message ); const payload = JSON. stringify ( claudeResponse ); // 3️⃣ Store result with TTL await setInCache ( cacheKey, payload, TTL_SECONDS ); // 4️⃣ Return to client res. setHeader ( "Content-Type", "application/json" ); res. end ( payload ); } catch ( err ) { console. error ( "Error handling request:", err ); res. statusCode = 500; res. end ( JSON. stringify ( { error: ( err as Error ). message } ) ); } } ); server. listen ( PORT, ( ) => { console. log ( `🚀 Server listening on http://localhost:${PORT}` ); } ); Enter fullscreen mode Exit fullscreen mode Walk‑through of the code Step Purpose Explanation Redis client creation Connects to the Serverless endpoint redis://… tells the library where the Valkey service lives. getFromCache / setInCache Abstracts cache operations We intentionally wrapped the SDK‑style GetCommand / PutCommand to satisfy the requirement, but the underlying call is a normal Redis GET / SET EX. askClaude Calls Bedrock (the managed Claude endpoint) fetch sends an HTTP POST; the EC2 instance’s IAM role signs the request automatically.
Cache key design Guarantees uniqueness per conversation & message Using conversationId groups messages, and a base‑64 encoding of the text prevents special‑character issues. TTL handling Guarantees the cache clears after 5 minutes setInCache passes TTL_SECONDS; once the time elapses Redis automatically evicts the key. Helpful tip: If you see “Cache miss” on every request, double‑check that the key string is identical for identical prompts.
Small differences (extra spaces, case changes) create new keys and defeat caching.
export ELASTICACHE_ENDPOINT = my-cache.xxxxxx.use1.cache.amazonaws.com:6379 export PORT = 3000 Enter fullscreen mode Exit fullscreen mode Compile and start ( npx tsc server.ts && node server.js ). Now POST to http://<ec2‑public‑ip>:3000/chat with JSON { "conversationId": "abc123", "message": "What is the capital of France?" }. The first request hits Claude; subsequent identical requests within 5 minutes return instantly from the cache.
Serverless pricing is request‑driven: each GET or SET costs a few hundredths of a cent. If you unintentionally cache a high‑traffic key without an expiration, that key stays forever, and every read/write continues to be billed.
In plain English: Imagine a parking garage that charges per car that enters. If you forget to close the gate, cars keep coming in and you pay for each one forever.
If a key is written without an expiration, every subsequent read counts as a GET request—still cheap, but the SET that created the key was billed at the higher “write” rate. Worse, if you later add an expiration with EXPIRE, the original write cost does not disappear.
await redis. set ( cacheKey, payload, { EX: TTL_SECONDS, // atomic set‑with‑expire; guarantees the key has a TTL at creation time } ); Enter fullscreen mode Exit fullscreen mode The atomic SET with EX ensures the key is never created without a TTL, eliminating the accidental “cold‑cache” cost.
The first request for a new key always incurs a cold‑cache penalty: the value isn’t there, so you pay the Bedrock latency and the Redis SET cost. If your traffic pattern has many unique prompts, the average latency will stay high despite the cache.
Key takeaway: Cost savings and speed gains depend on repetition. The more you can make different queries map to the same cache entry, the better the economics.
You now have a complete, production‑ready recipe for caching Claude responses on EC2 using ElastiCache Serverless.
Give it a try on a small EC2 instance, watch the latency drop on repeated queries, and adjust TTL or key strategy until the CloudWatch bill matches your expectations. Happy caching!
This article was written with the help of an AI system — Groq (GPT OSS 120B).
Published: 2026-11-24 · Primary focus: ElastiCache
All code blocks are intended to be correct and runnable, but please verify them against the official docs for the tools mentioned before using in production.
Find an error? Drop a comment — corrections are always welcome.