Caching, Expiration and Invalidation in Redis
This lesson explains Redis data structures, the cache-aside pattern, expiration and eviction, invalidation strategies and stampede protection.
Learning outcomes
After completing this lesson, you will be able to:
- Describe the cache-aside pattern.
- Distinguish expiration from eviction.
- Choose an eviction policy for a workload.
- Explain event-driven invalidation and stampede protection.
Data structures and key design
Redis stores values under keys, and each value has a type. Strings hold text, serialized JSON or binary data; hashes hold field-value maps, such as the fields of a product; lists, sets and sorted sets hold collections, with sorted sets ordered by score for rankings; and with RedisJSON, JSON documents can be read and updated by path.
Keys follow a naming convention such as product:42 or answer:v3:9f2c..., with colons separating parts. Including a version or schema marker in the key lets an application change the cached format without reading stale entries written in the old format. Keys should be short but descriptive, and values small: large values increase latency and network use, so a cache stores what a request needs rather than whole database rows.
Redis data types
The cache-aside pattern
Cache-aside (lazy loading) is the default caching pattern. The application owns both the cache and the database and loads the cache only when data is requested.
-
Read the cache
Look up the key; if it exists (a hit), return the value.
-
Read the source
On a miss, read the database or call the model.
-
Populate
Write the result to the cache with a time to live.
-
Return
Return the result to the caller.
import json
def get_product(product_id):
key = f"product:{product_id}"
cached = cache.get(key)
if cached is not None:
return json.loads(cached)
product = container.read_item(item=product_id, partition_key=product_id) # source of truth
cache.set(key, json.dumps(product), ex=300) # expires in 5 minutes
return productOther patterns trade simplicity for freshness. Write-through updates the cache whenever the database is written, so reads rarely miss, at the cost of caching data that may never be read. Write-behind writes to the cache first and to the database later, which is fast but risks data loss and is rarely appropriate for a cache in front of a system of record.
Caching patterns
Expiration and eviction
Expiration removes a key after a time to live (TTL). It is set with SET key value EX seconds (or PX for milliseconds), added to an existing key with EXPIRE, inspected with TTL and removed with PERSIST. The TTL bounds how stale a cached value can be: a price cached for 300 seconds can be at most five minutes out of date. Adding small random jitter to TTLs prevents thousands of keys created together from expiring together.
Eviction is what Redis does when memory is full. The eviction policy decides which keys are removed to make room, and it must suit the data.
| Policy | Behaviour when memory is full | Suits |
|---|---|---|
| volatile-lru | Evicts the least recently used keys that have a TTL | Caches where some keys must never be evicted |
| allkeys-lru | Evicts the least recently used keys of any kind | Pure caches where every key is disposable |
| volatile-ttl | Evicts keys with the shortest remaining TTL first | Data whose TTL reflects its value |
| noeviction | Rejects writes with an out-of-memory error | Data that must not be lost silently, and RediSearch indexes |
Expiration and eviction answer different questions: expiration controls freshness, and eviction controls memory. A cache needs both a sensible TTL and enough memory that eviction is rare.
Choosing an eviction policy
Invalidation and stampedes
TTLs alone allow stale reads until expiry. Invalidation removes or updates a cached entry as soon as its source changes. The simplest approach deletes the key in the same code path that updates the database; the next read misses and reloads. When writes happen in other services, invalidation is event-driven: a Cosmos DB change feed handler, an Event Grid subscription or a Service Bus message tells the cache owner which keys to delete. For entries derived from many records, such as a cached answer built from several documents, a set of keys per source (a tag) lets one change invalidate all dependent entries, or a version number in the key makes old entries unreachable.
A cache stampede happens when a popular key expires and hundreds of concurrent requests miss at once, all querying the database or the model. Protections include a short lock with SET lock:key 1 NX EX 10 so that only one request recomputes while others wait or serve the stale value, refreshing popular keys shortly before they expire, and TTL jitter.
The following diagram shows the invalidation path alongside the cache-aside reads.

Invalidation and stampedes
Stale prices after updates
A product API caches product documents from Cosmos DB in Redis for one hour. Prices are updated by a separate pricing service that writes directly to Cosmos DB. Customers sometimes see old prices for up to an hour, and reducing the TTL to one minute tripled database load.
The cache needs event-driven invalidation. A function with the Cosmos DB trigger on the products container receives each changed product and deletes (or overwrites) its product:ID key, so the next read loads the new price. The one-hour TTL can stay as a safety net, keeping database load low, and the stale window shrinks to the few seconds the change feed takes.
A shorter TTL already proved too expensive. Making the pricing service write to Redis directly couples it to the cache and misses other writers. Switching the eviction policy to allkeys-lru affects memory pressure, not freshness.
What is the difference between a key's TTL and the cache's eviction policy?
Show answer
The TTL removes a key after a set time to bound staleness. The eviction policy decides which keys are removed when memory is full.
Exam Tips
Remember for the exam
- Cache-aside: read cache, on a miss read the source, then SET with a TTL.
- TTL controls freshness; the eviction policy controls what happens when memory is full.
- Invalidate on write or from change events; add TTL jitter and stampede protection.
- volatile-lru evicts only keys with a TTL; noeviction rejects writes when full.