Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 151/ 160
08. Backend

Caching with Redis

In-memory cache for sessions, rate limits, and semantic/response caches.

BeginnerTTL · Cache-Aside3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Redis remembers answers to questions it has already seen, so the app can reply instantly instead of doing the slow work again.

Think of it like…

A desk drawer beside your workspace. The documents you use constantly stay within arm's reach instead of in the archive across town; when the drawer is full you throw out what you haven't touched lately, and you never put the only copy of anything important in it.

Where you’ve seen it

A support assistant answers about 100,000 questions a day at an average of $0.01195 per model call, or $1,195 a day. Analysis shows 25% of requests are exact repeats of earlier prompts after normalisation (same model, same prompt version, same retrieved context, temperature 0). A response cache keyed resp:v3:{tenant}:{sha256(model|prompt_version|normalised_messages)} with a one-hour TTL turns those into hits: cost per request becomes (1 − 0.25) × $0.01195, saving 25,000 × $0.01195 = $298.75 a day, about $8,960 a month, and a hit returns in roughly 0.5 ms instead of 3.4 seconds. Memory is modest: 40,000 live entries × about 3 KB (a 420-token answer plus metadata) ≈ 120 MB, with maxmemory 512mb and allkeys-lru. The key includes the tenant and a version segment so one customer's answers never serve another and a prompt change invalidates old entries by changing v3 to v4. A stampede is the dangerous case: when a popular key expires, 500 concurrent requests all miss and make 500 model calls (500 × $0.01195 = $5.98 and a likely provider throttle). The cache uses single-flight: the first miss takes a short Redis lock (SET lock:key token NX PX 30000), the others wait briefly or serve the stale copy kept for 5 more minutes, and TTLs get 10% random jitter so keys created together don't expire together. Redis also holds session data (30-minute sliding TTL), per-user counters for rate limits and a short-lived buffer for stream resume. Sensitive outputs are cached only when policy allows, never across tenants, and with short TTLs. Metrics tracked: hit rate, evictions, memory use, p99 latency and the stampede count.

Words you’ll hear

Cache-aside
Read the cache, on a miss load from the source and populate the cache.
TTL
Time to live: how long a key stays before Redis deletes it.
Eviction policy
The rule Redis uses to remove keys when memory is full, such as allkeys-lru.
Stampede
Many concurrent misses on an expired hot key overwhelming the source.

Visual diagram

Loading interactive diagram

Theory & deep dive

Cache-aside, keys, TTLs and eviction

In cache-aside the application owns the logic: GET key; if present, return it; otherwise compute, SET key value EX ttl, return. Good keys are namespaced and versioned (resp:v3:{tenant}:{hash}) so you can invalidate a whole class by bumping the version and so tenants can never collide. Hash large inputs (the normalised prompt) with SHA-256 and include everything that changes the output: model, prompt version, relevant parameters (temperature, tools) and the retrieved context identifiers. Cache only when it is safe: deterministic requests (temperature 0), results that don't depend on the individual user's private state unless the user is in the key, and outputs that are fine to repeat.

A TTL bounds staleness: choose it from how quickly the underlying data changes (minutes for retrieval results, an hour for FAQ answers). Add random jitter (say ±10%) so a batch of keys written together doesn't expire together. Redis evicts when maxmemory is reached: allkeys-lru (or allkeys-lfu) is the usual cache setting, while noeviction suits stores that must not lose data and then returns errors at the limit. Size memory from entries × average size plus overhead (40,000 × 3 KB ≈ 120 MB, plus keys and structures), and watch the hit rate, evictions and memory fragmentation. The hit-rate economics are simple: saved cost per day = requests × hit rate × cost per miss, here 100,000 × 0.25 × $0.01195 = $298.75.

Savings by hit rate

100,000 requests/day × $0.01195 = $1,195/day without a cache. Hit rate 10%: saves $119.50. 25%: $298.75. 40%: $478. Each point of hit rate is worth about $11.95 a day at this volume.

Key takeaway: Version and namespace keys, include everything that affects the output and size TTL and memory from measured hit rates.

Stampedes, hot keys, invalidation and safety

A cache stampede happens when a popular key expires and many requests miss at once: 500 concurrent misses would trigger 500 model calls (500 × $0.01195 ≈ $5.98) and probably hit provider rate limits. Defences: single-flight (a short lock with SET key token NX PX so only one request recomputes while others wait or serve stale data), stale-while-revalidate (keep the expired value for a few more minutes and refresh in the background), TTL jitter and early refresh of hot keys. A hot key (one key receiving a very large share of traffic) can saturate a single Redis shard, so replicate it, add a small in-process cache in front (a few seconds) or split it into numbered copies.

Invalidation is the hard part: prefer short TTLs and key versions over trying to delete every affected entry; delete explicitly when a source document or permission changes (DEL by key set, or version bump for a whole class). Safety: include the tenant (and user, when answers depend on them) in the key, never cache responses to prompts containing secrets or personal data unless policy allows, encrypt sensitive values and apply short TTLs, and ensure the application still works when Redis is down (degrade to the source, with circuit breakers so that a Redis outage doesn't become a database or provider outage). Don't use Redis as the only store for anything you can't rebuild: persistence options (RDB, AOF) exist but a cache should be treated as disposable. For semantic similarity caching see the dedicated lesson; exact-match caching is the cheaper, safer first step.

Single-flight lock

SET lock:resp:v3:t77:9f2c A1B2 NX PX 30000 → OK for the first request, which calls the model and writes resp:v3:t77:9f2c. The other 499 requests see the lock, poll the key every 50 ms for up to 10 s (or return the stale copy) and read the fresh value: 1 model call instead of 500.

Key takeaway: Prevent stampedes with single-flight and jitter, keep keys tenant-safe and design for Redis being empty or unavailable.

How it works, step by step

Step 1 of 4
Backend engineer

1. Choose what is safe to cache

Pick deterministic or repeated work, and define exactly which inputs determine the output.

temperature 0 · model · prompt version · context ids
Key numbers at this step
Measure
repeat rate first

When to use it & trade-offs

What it is

Redis is an in-memory data-structure server that answers most commands in well under a millisecond. In AI backends it serves as a cache (responses, retrieved chunks, embeddings, tool results), a session store, a home for counters and rate-limit state, a lightweight queue or stream and a pub/sub channel. The dominant pattern is cache-aside: the application checks Redis first, on a miss loads from the source (a database, an API or an LLM) and writes the result back with a time-to-live (TTL). Because memory is finite, Redis evicts keys by a policy such as allkeys-lru when full, and because it is a cache, every design must tolerate a miss, a flush or a restart.

Why it matters: LLM calls are slow (seconds) and expensive (cents per thousand), while Redis reads cost around half a millisecond and almost nothing. Caching deterministic or repeated work cuts both latency and bill, protects providers from bursts and lets you keep session and counter state outside application processes. But caches also create the classic failure modes: stale data, a stampede when a hot key expires, keys that leak one tenant's data to another and memory that fills up unpredictably.

When to reach for it

  • Exact-match response caches for deterministic requests
  • Session state with sliding TTLs
  • Counters and short-lived buffers for rate limits and stream resume

When to avoid or be careful

  • Caching personalised or sensitive output under a shared key
  • Treating Redis as the system of record
  • Identical TTLs on keys created in bulk

Where to cache

In-process memory
Best for: Tiny, very hot values with a few seconds of TTL

Strengths: Fastest; no network.

Watch out: Per-instance copies and inconsistency.

Redis
Best for: Shared responses, sessions and counters

Strengths: Shared across instances; rich data types; TTLs.

Watch out: Network hop; memory cost; must tolerate loss.

Provider prompt caching
Best for: Repeated long prompt prefixes

Strengths: No infrastructure; cheaper input tokens.

Watch out: Provider-specific; doesn't skip generation.

Interview signals & numbers to know

When this topic comes up

  • “How would you cut LLM cost with caching?”
  • Cache-aside versus write-through
  • Cache stampede and single-flight
  • Eviction policies and sizing
  • Keeping tenants isolated in a shared cache

Benchmarks & rules of thumb

25% hit rate -
saves $298.75/day on 100,000 requests at $0.01195
≈ 0.5 ms vs 3.4 s -
Redis hit versus a fresh model call
500 × $0.01195 = $5.98 -
cost of one stampede without single-flight

Common mistakes & follow-ups

Common interview mistakes

  • Omitting the prompt version from the key and serving stale behaviour.
  • Letting a Redis outage take down the database or provider.
  • Caching non-deterministic output as if it were a fact.

Likely interviewer follow-ups

  • How would you invalidate cached answers after a document update?
  • What happens to your service if Redis restarts empty?
  • How do you prevent a hot key from overloading one shard?
Interview tip: Quote the hit-rate arithmetic with real prices; it shows you justify caching with numbers.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Caching with Redis with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Transactions and ACID
Next topic
Message Queues