How to Cache LLM Responses in Redis

Calling the LLM for the same question twice wastes money and time. Cache it: hash the prompt to a key, serve cached answers on a hit, and store new ones with a TTL. Here's the cache-aside pattern for LLM calls.

AI Engineerpythonflaskllm

Why cache LLM calls

Identical prompts produce (effectively) identical answers, but each call costs tokens and seconds. For an FAQ or Q&A endpoint where users repeat questions, caching turns a repeat question into an instant, free lookup. This is cache-aside: check cache, miss -> call LLM -> store.

Hash the prompt into a key

Use a hash of the normalized prompt so the key is fixed-length and identical inputs map to the same key:

import hashlib

def cache_key(question: str) -> str:
    norm = question.strip().lower()
    return "llm:" + hashlib.sha256(norm.encode()).hexdigest()

Cache-aside with a TTL

import redis, json
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
TTL = 300   # 5 minutes

def ask(question: str) -> str:
    key = cache_key(question)
    hit = r.get(key)
    if hit is not None:
        return json.loads(hit)          # cache hit - no LLM call

    answer = call_llm(question)          # miss - do the work
    r.setex(key, TTL, json.dumps(answer))
    return answer

First request for a question hits the LLM and caches; repeats within the TTL are served from Redis.

The details that matter

Want to try it hands-on? HeyDevJob gives you this exact setup in a live cloud workspace in your browser - edit it, run it, and see it work. Free, nothing to install.

Try it in a workspace →

What you'll practice

FAQ

How do I cache LLM responses in Redis?

Use cache-aside: hash the (normalized) prompt into a key, return the cached value on a hit, and on a miss call the LLM and store the answer with setex and a TTL. Repeated questions are then served from Redis.

What should the cache key be for an LLM call?

A hash (e.g. SHA-256) of the normalized prompt - trimmed and lowercased - plus the model name and any parameters like temperature, so different configs don't share a cached answer.

What TTL should I use for cached LLM answers?

It depends on freshness needs - short (minutes) if answers can change, longer (hours/days) for stable FAQ content. Use setex so entries expire automatically, and don't cache error responses.

Keep learning

Restore a Broken LLM API IntegrationAI/ML projectHarden an LLM Pipeline Against API FailuresAI/ML projectParse JSON From an LLM (Strip Markdown Fences)AI/ML projectAI/ML roadmapStep by step to hiredAI/ML interview questionsSTAR answersAll AI/ML projectsProjects hub

Learn it by doing. Open this in a live cloud workspace, make the change yourself, and keep a record of the work you can share.

Open the workspace →