StackPractices
advanced By Mathias Paulenko

Complete Guide to Redis Caching Strategies

Choose and implement the right Redis caching pattern — cache-aside to refresh-ahead — with eviction, TTL, and production ops guidance.

Introduction

Redis answers most cache reads in under a millisecond, which is why it ends up in front of almost every database sooner or later. The hard part isn’t Redis itself — it’s choosing the pattern that fits how your workload actually reads and writes. Teams that adopt write-behind for a read-heavy API, or cache-aside for a hot leaderboard, end up debugging stale data and memory pressure instead of enjoying the speedup they expected.

This guide walks through the five patterns you’ll actually meet in production — cache-aside, read-through, write-through, write-behind, and refresh-ahead — with runnable Python examples, the trade-offs each one hides, and the operational details (eviction, TTL, serialization, monitoring) that decide whether the cache helps or hurts. Where a pattern is the wrong tool, we say so.

The Five Patterns at a Glance

All five patterns differ on the same two axes: who owns the cache — your application code or a dedicated layer — and when the database sees the write: synchronously, asynchronously, or never directly. The table below compresses the differences; the sections that follow expand each one.

PatternRead pathWrite pathConsistencyComplexity
Cache-asideApp → Redis → DB on missApp → DB, then invalidateEventualLow
Read-throughApp → cache layer → DB on missApp → cache layer → DBEventualMedium
Write-throughApp → cache → DB (sync)App → cache + DB (sync)StrongMedium
Write-behindApp → cache (DB async)App → cache, flush asyncEventual, lossyHigh
Refresh-aheadCache refreshed before TTLApp → DB, then refreshEventualHigh
flowchart diagram: Start{What matters most?

Cache-Aside (Lazy Loading)

Cache-aside is the pattern most teams start with, and for good reason: the application decides explicitly when to read from Redis and when to fall back to the database. On a read, check Redis first; on a miss, query the database, populate the cache, and return the result. On a write, update the database and delete the cached entry so the next read repopulates it.

import json
import redis

r = redis.Redis(host="localhost", port=6379, db=0)
# db is your data-access layer: ORM, driver, or repository — shown as
# db.users.find_by_id() / db.users.update() throughout these examples.

def get_user(user_id: int) -> dict | None:
    cache_key = f"user:{user_id}"
    cached = r.get(cache_key)
    if cached:
        return json.loads(cached)

    # Cache miss: read from database, then populate the cache.
    user = db.users.find_by_id(user_id)
    if user:
        r.setex(cache_key, 3600, json.dumps(user))
    return user

def update_user(user_id: int, data: dict) -> dict:
    user = db.users.update(user_id, data)
    r.delete(f"user:{user_id}")  # invalidate; next read repopulates
    return user

The write path matters more than it looks. Deleting the key (rather than updating it with the new value) avoids two failure modes: writing a cache entry for a value the database transaction later rolls back, and serializing a partially-updated object. Delete-then-repopulate keeps the cache honest at the cost of one extra database read.

Preventing a Cache Stampede

When a hot key expires — or the cache restarts — every in-flight request misses together and lands on the database at once. That’s the thundering herd, and it turns a cache outage into a database outage. A short-lived lock lets one request do the fetch while the rest wait.

import time

def get_user_safe(user_id: int, max_wait_s: float = 2.0) -> dict | None:
    cache_key = f"user:{user_id}"
    lock_key = f"lock:{cache_key}"
    deadline = time.monotonic() + max_wait_s

    cached = r.get(cache_key)
    if cached:
        return json.loads(cached)

    # Only one request may fetch; the rest poll until it finishes.
    while time.monotonic() < deadline:
        if r.set(lock_key, "1", nx=True, ex=10):
            try:
                cached = r.get(cache_key)  # double-check after acquiring
                if cached:
                    return json.loads(cached)
                user = db.users.find_by_id(user_id)
                if user:
                    r.setex(cache_key, 3600, json.dumps(user))
                return user
            finally:
                r.delete(lock_key)
        time.sleep(0.05 + random.random() * 0.05)  # jittered backoff

    # Lock holder is slow or dead: fall back to the database anyway.
    return db.users.find_by_id(user_id)

Two details separate this from the naive version: the double-check after acquiring the lock (another request may have populated the cache while we waited), and the bounded wait — an unbounded retry loop turns a slow database into a pile of sleeping coroutines.

Trade-offs

  • For: simple to implement, caches only what is actually requested, and degrades gracefully — if Redis dies, reads still work through the database.
  • Against: every miss pays database latency plus a cache write, writes can leave stale data until the next read, and cold-start or mass-invalidation events need the lock above to avoid stampedes.

Read-Through

With read-through, the application never talks to the database at all — it talks to a cache layer that owns the whole miss path: check Redis, fetch from the database on a miss, populate, return. The application never sees the database.

class ReadThroughCache:
    def __init__(self, redis_client, db_loader):
        self.redis = redis_client
        self.db_loader = db_loader  # callable: key -> dict | None

    def get(self, key: str, ttl: int = 3600) -> dict | None:
        cached = self.redis.get(key)
        if cached:
            return json.loads(cached)
        data = self.db_loader(key)
        if data is not None:
            self.redis.setex(key, ttl, json.dumps(data))
        return data

user_cache = ReadThroughCache(
    r,
    lambda key: db.users.find_by_id(int(key.split(":", 1)[1])),
)
user = user_cache.get("user:42")

The appeal is consistency of behavior: every read path gets the same caching semantics, and adding caching to a legacy codebase doesn’t mean touching every call site. The cost is that the cache layer becomes a single point of failure and a choke point — every miss funnels through it — and you lose fine-grained control over what gets cached and for how long.

Use read-through when you want caching as infrastructure (a repository decorator, a sidecar, a framework concern) rather than as application logic.

Write-Through

Write-through solves staleness by coupling the two writes: every update goes to the database and the cache in one operation. There are two orderings in the wild, and the difference matters:

  • Cache-then-DB: write to Redis, then write to the database. Lower perceived latency, but a failed database write leaves the cache holding data that doesn’t exist in the source of truth.
  • DB-then-cache: write to the database first, then update Redis. Slightly higher latency, but the cache only ever holds committed data — the safer default.

The example below uses DB-then-cache ordering, which is what most production systems should prefer:

class WriteThroughCache:
    def __init__(self, redis_client, db_writer):
        self.redis = redis_client
        self.db_writer = db_writer  # callable: (key, value) -> dict

    def set(self, key: str, value: dict, ttl: int = 3600) -> dict:
        result = self.db_writer(key, value)          # commit first
        self.redis.setex(key, ttl, json.dumps(result))  # then mirror to cache
        return result

user_cache = WriteThroughCache(
    r,
    lambda key, val: db.users.update(int(key.split(":", 1)[1]), val),
)
user = user_cache.set("user:42", {"name": "Alice"})

Trade-offs

  • For: the cache never serves data older than the last committed write — strong consistency without read-repair logic.
  • Against: every write pays two synchronous round trips, a cache outage fails writes outright (unless you add a fallback queue), and write-heavy workloads will feel it. This pattern fits configuration data, inventory counts, and anything where a stale read is a bug, not an inconvenience.

Write-Behind (Write-Back)

Write-behind inverts write-through: the application writes only to Redis and returns, and a background worker flushes to the database on its own schedule. Write latency drops to a single Redis round trip, which is why it shows up in analytics pipelines, counters, and leaderboards (implemented with sorted sets — see the leaderboard recipe).

import json
import logging
import queue
import threading

log = logging.getLogger(__name__)
write_queue: queue.Queue = queue.Queue()

def flush_worker(db_writer, batch_size: int = 50):
    """Drain the queue and batch-write to the database."""
    while True:
        batch = [write_queue.get() for _ in range(batch_size)]
        try:
            db_writer(batch)  # one bulk write per batch
        except Exception:
            log.exception("write-behind flush failed for %d keys", len(batch))
            # Requeue or dead-letter here; dropping silently loses data.
        finally:
            for _ in batch:
                write_queue.task_done()

def write_behind_set(redis_client, db_writer, key: str, value: dict, ttl: int = 3600):
    redis_client.setex(key, ttl, json.dumps(value))
    write_queue.put((key, value))  # async DB write

Trade-offs

  • For: minimal write latency, high throughput, and database load smoothing — bursts become batches.
  • Against: a Redis crash between the cache write and the flush loses acknowledged writes. Ordering, retries, and idempotency are now your problem: if two writes to the same key land out of order, the database ends up with the older value. This pattern demands a durability story (AOF persistence on Redis, a dead-letter queue for failed flushes) before it touches anything that matters.

Reach for write-behind when the data is analytics-grade — acceptable to lose a few seconds of writes — not for orders, balances, or anything a user would notice missing.

Refresh-Ahead

Refresh-ahead removes misses entirely for hot keys by having a background job rewrite entries before their TTL expires. Users always hit warm data; the database sees a steady, predictable load instead of a spike every time a popular key expires.

import json
import threading
import time

def refresh_ahead(redis_client, db_loader, pattern: str = "user:*",
                  ttl: int = 3600, horizon_s: int = 300, interval_s: int = 60):
    """Rewrite keys expiring within `horizon_s` seconds, every `interval_s`."""
    while True:
        for key in redis_client.scan_iter(match=pattern, count=200):
            remaining = redis_client.ttl(key)
            if 0 < remaining < horizon_s:
                data = db_loader(key)
                if data is not None:
                    redis_client.setex(key, ttl, json.dumps(data))
        time.sleep(interval_s)

threading.Thread(
    target=refresh_ahead,
    args=(r, lambda k: db.users.find_by_id(int(k.split(":", 1)[1]))),
    daemon=True,
).start()

Two implementation notes worth internalizing. First, scan_iter (not scan) — scan returns a (cursor, keys) tuple and only one page, while scan_iter walks the whole keyspace without blocking Redis the way KEYS does. Second, refreshing on a fixed horizon means you are guessing which keys are still hot; a key nobody reads for a week still gets refreshed every cycle. Track access (a last_accessed field or Redis OBJECT IDLETIME) if the waste matters.

Trade-offs

  • For: no misses on hot keys, fresher data than TTL expiry alone, and database load that’s proactive rather than reactive.
  • Against: wasted work refreshing cold keys, more moving parts to operate, and a refresh failure window where the key can still expire mid-flight. It is the right answer for a small set of genuinely hot keys — product catalogs, feature flags, session templates — not for the whole dataset.

Choosing a Pattern

The honest answer is that most systems end up hybrid: cache-aside for general reads, write-through or invalidation for the entities where consistency matters, and refresh-ahead for a handful of hot keys. Start simple and add complexity only when a measured problem demands it.

Your situationStart withWhy
General read-heavy API, unknown access patternsCache-asideSimplest correct default; caches only what is read
Reads vastly outnumber writes, want cache as infrastructureRead-throughUniform miss handling without touching call sites
Writes must never serve stale data (inventory, config, balances)Write-through (DB-then-cache)Cache mirrors committed state
Analytics, counters, leaderboards — loss tolerantWrite-behindWrite latency becomes one Redis round trip
A few hot keys expiring causes visible latency spikesRefresh-aheadKeeps hot keys warm before TTL hits zero
Multi-tier caching (CDN → Redis → DB)Cache-aside per layerEach layer owns its own invalidation

When Redis Caching Is the Wrong Tool

Caching isn’t free. Before adding Redis to the path, check whether the problem is actually a caching problem:

  • Dataset larger than memory: if your working set exceeds available RAM, eviction churn will make hit rates worse than no cache at all. Fix the query or shard the data first.
  • Low read amplification: if each database row is read once per hour, a cache adds a hop and a failure mode for nothing. Profile before caching.
  • Write-mostly workloads: write-behind shifts the cost, it doesn’t remove it — the database still has to absorb every write, just batched.
  • The database isn’t the bottleneck: caching in front of a per-request-billed serverless database is a cost optimization as much as a latency one — every hit is a request you don’t pay for. But if reads are already cheap (provisioned, idle capacity), the math may not justify another moving part.
  • Strong consistency requirements: no Redis pattern gives you serializable reads across the cache and the database. If that’s the requirement, the answer is the database, not Redis.
  • You haven’t measured: “the database feels slow” isn’t a caching strategy. Get p95 query times first; often the fix is an index, not a cache.

Eviction Policies

When Redis hits maxmemory, it evicts keys according to maxmemory-policy. Picking the wrong one is how caches silently lose the data you needed most.

PolicyBehaviorBest for
noevictionWrites fail when memory is fullData that must not be silently dropped
allkeys-lruEvicts least recently used key, TTL or notGeneral-purpose caching
allkeys-lfuEvicts least frequently used keySkewed access patterns
volatile-lruLRU among keys with TTL onlyMixed cached + persistent data
volatile-lfuLFU among keys with TTL onlyMixed data, frequency matters
volatile-ttlEvicts key with shortest remaining TTLTime-boxed data
volatile-randomRandom key among TTL keysLow overhead, acceptable loss
allkeys-randomRandom key, TTL or notUniform access, simplest

For a dedicated cache instance, allkeys-lru is the right default: recently used data is what you want to keep. volatile-lru only makes sense when the same Redis holds both disposable cache entries and data you can’t lose — and even then, a separate instance is usually cleaner. Note that LFU policies in Redis are approximations (they decay over time), which is fine for caching but worth knowing before you rely on exact frequencies.

# redis.conf
maxmemory 2gb
maxmemory-policy allkeys-lru

TTL Tuning

TTL is your first line of defense against stale data, and it’s also a memory management tool. A few rules that survive contact with production:

  • Always set a TTL. Keys without expiration live forever; on a cache instance that’s a memory leak with extra steps.
  • Match TTL to change frequency. Sessions: minutes. User profiles: an hour. Feature flags and config: hours to a day. Static reference data: days, with explicit invalidation on update.
  • Add jitter. If a thousand keys were written in the same second with the same TTL, they all expire together and you get a synchronized stampede. ttl + random(0, jitter) spreads the wave.
  • Version your keys. Prefixing with a schema or entity version (user:v2:42) lets you rotate formats or invalidate a whole class of entries with SCAN + UNLINK instead of touching every key.
import random

def set_with_jitter(key: str, value: str, base_ttl: int = 3600, jitter: int = 300):
    r.setex(key, base_ttl + random.randint(0, jitter), value)

TTL and eviction are complementary, not alternatives: TTL decides when data goes stale, eviction decides what dies when memory runs out. You need both.

Serialization

What you store decides what it costs. Three options cover almost every case:

  • JSON — human-readable, debuggable with redis-cli, supported everywhere. The right default; the cost is verbosity (~2x the bytes of binary formats).
  • MessagePack — compact binary, faster to encode/decode on large payloads. Worth it when you’re caching big objects and memory or CPU shows up in profiles. Requires the msgpack package.
  • Redis hashes — for objects with many fields you update independently (HSET user:42 name Alice), hashes give you partial updates without read-modify-write cycles. The trade-off: you lose the single-round-trip simplicity of a string blob and pay per-field overhead.
# JSON (default)
r.set("user:42", json.dumps({"id": 42, "name": "Alice"}))

# MessagePack (compact, needs: pip install msgpack)
import msgpack
r.set("user:42", msgpack.packb({"id": 42, "name": "Alice"}, use_bin_type=True))

# Hash (partial updates)
r.hset("user:42", mapping={"name": "Alice", "email": "alice@example.com", "age": "30"})

One trap worth naming: redis-cli GET on a MessagePack or pickled value returns bytes you can’t read. If humans will inspect the cache during incidents — and they will — prefer JSON for anything you might need to eyeball at 3 a.m.

Production Operations

Monitoring

These metrics tell you whether the cache is helping. Collect them from day one — before the first incident, not after it.

  • Hit rate: keyspace_hits / (keyspace_hits + keyspace_misses) — below ~80% on a read-heavy workload usually means TTLs are too short, keys are wrong, or the workload doesn’t benefit from caching.
  • Memory: used_memory / maxmemory — sustained values above 80% mean eviction is doing your capacity planning for you.
  • Evictions: evicted_keys rate — nonzero on a healthy cache means you’re undersized or your TTLs are too generous.
  • Latency: p99 for GET/SET should stay under ~1ms on the same network; anything higher points at big values, slow scripts, or network issues, not Redis itself.
  • Clients: connected_clients growth without matching application growth signals a connection leak — use pooling (below).
  • Persistence: if you run RDB or AOF, watch rdb_last_save_time and aof_last_write_status.
redis-cli INFO stats | grep -E "keyspace_hits|keyspace_misses|evicted_keys"
redis-cli INFO memory | grep -E "used_memory_human|maxmemory_human"

Persistence

Redis gives you two durability options, and the right choice depends on whether Redis is a cache or a system of record:

  • RDB snapshots — point-in-time dumps. Fast recovery, but you lose everything since the last snapshot. Fine for pure caches that rebuild from the database.
  • AOF — logs every write. Near-zero loss with appendfsync everysec, at the cost of more disk I/O and slower restarts.

For cache-aside and read-through workloads, RDB (or no persistence at all) is enough — losing the cache is an inconvenience, not an outage. If you run write-behind and Redis briefly holds the only copy of recent writes, AOF isn’t optional — see Redis in production for the durability setup.

# redis.conf
save 900 1
save 300 10
appendonly yes
appendfsync everysec

Clustering and High Availability

A single Redis instance covers a surprising amount of ground — tens of GB and hundreds of thousands of ops/sec. When you outgrow it, the fork in the road is:

  • Redis Sentinel — high availability without sharding. One master, replicas, automatic failover. Pick it when one node’s capacity is enough but downtime isn’t acceptable.
  • Redis Cluster — shards data across nodes by hash slot. Pick it when a single node can’t hold the working set or serve the traffic. Keys in the same hash tag ({user}:42:profile, {user}:42:prefs) land on the same slot, which matters for multi-key operations.
from redis.cluster import RedisCluster  # requires redis-py >= 4.1

rc = RedisCluster(host="localhost", port=7000)
rc.set("user:42", json.dumps({"name": "Alice"}))

Connection Pooling

Never open a connection per request. A TCP connection plus Redis handshake costs more than the command you’re trying to run. Pools amortize that cost and, just as importantly, cap the number of connections your app can leak.

pool = redis.ConnectionPool(host="localhost", port=6379, max_connections=50)
r = redis.Redis(connection_pool=pool)

Size max_connections to your worker count plus headroom; every client library holds the pool per process, so a 20-instance deployment with max_connections=50 can ask for 1,000 server connections — check maxclients on the server side.

Common Pitfalls

Storing Large Objects

Values over ~1MB are a bad trade in Redis: they inflate memory, slow replication, and block other clients during transfer. Store the payload in object storage or the database and keep only a reference (URL, ID, metadata hash) in Redis.

# Bad: a 5MB image blob in Redis
r.set("image:42", large_image_bytes)

# Good: metadata in Redis, bytes in S3
r.hset("image:42", mapping={
    "url": "s3://bucket/image42.jpg",
    "width": "1920",
    "height": "1080",
})

Using KEYS in Production

KEYS user:* blocks the entire Redis server while it scans every key — on a busy instance that’s an outage you scheduled yourself. SCAN iterates in small batches and yields between them; scan_iter wraps it for Python.

# Bad: blocks Redis
keys = r.keys("user:*")

# Good: incremental, non-blocking
for key in r.scan_iter(match="user:*", count=100):
    process(key)

Ignoring Cache Failures

If Redis goes down, the application should degrade to the database, not fall over. Wrap cache reads and writes so a ConnectionError (from redis.exceptions) falls through to the source of truth — and log it, because a silently disabled cache is a silent performance regression.

import redis.exceptions

def get_user_resilient(user_id: int) -> dict | None:
    try:
        cached = r.get(f"user:{user_id}")
        if cached:
            return json.loads(cached)
    except redis.exceptions.ConnectionError:
        log.warning("redis unavailable, reading from database")

    user = db.users.find_by_id(user_id)
    if user:
        try:
            r.setex(f"user:{user_id}", 3600, json.dumps(user))
        except redis.exceptions.ConnectionError:
            pass  # cache is down; continue without caching
    return user

Letting the Cache Become the Source of Truth

The cache is a copy. If a bug, a flush, or an eviction policy wipes it and the database can’t rebuild the entries — because you only ever wrote to Redis — you’ve lost data you thought was safe. Write-behind is the classic way this happens; pure caches should always be rebuildable.

Best Practices

The patterns above are the mechanics; these are the habits that keep a Redis deployment healthy in production:

  1. Namespace everything. Prefix keys by service, entity, and version (svc:user:v2:42). It prevents collisions in shared instances and makes targeted invalidation possible.
  2. Set TTLs on everything, then add jitter. No TTL means no expiry; no jitter means synchronized stampedes.
  3. Invalidate by delete, not by update. Deleting on write avoids caching rolled-back or partially-written state.
  4. Monitor hit rate and evictions from day one. A cache you don’t measure is a guess, not an optimization.
  5. Pool connections and cap them. Per-request connections and unbounded pools both end in maxclients errors.
  6. Treat Redis as disposable unless you’ve chosen AOF. Design every pattern so a full flush costs you a cold cache, not lost data.
  7. Prefer SCAN/scan_iter over KEYS, always. The blocking version has no place in production.

See Also

Frequently Asked Questions

Which caching pattern should I start with?

Start with cache-aside. It's the simplest to reason about, degrades gracefully when Redis fails, and caches only what is actually requested. Move to write-through or write-behind only when you have a measured consistency or throughput requirement that cache-aside cannot meet — and reach for refresh-ahead only for a small set of genuinely hot keys.

How much memory should I allocate to Redis?

Enough to hold your working set — the keys that produce most of your hits — plus 20-30% headroom for spikes and fragmentation. Watch the eviction rate: sustained evictions mean you need more memory, shorter TTLs, or a smaller cached dataset. There is no universal number; measure your hit rate at different maxmemory values and pick the knee of the curve.

Should I use Redis for session storage?

Yes — sessions are the canonical Redis workload. Set the TTL to slightly longer than the session timeout, use volatile-lru or allkeys-lru so the oldest sessions evict first, and keep an eye on memory since every logged-in user holds a key. For very large sessions, store the bulky parts in the database and keep only the session ID and hot fields in Redis.

How do I test cache behavior?

Write integration tests against a real (test) Redis instance, not mocks: verify hits return cached data, misses hit the database and populate the cache, writes invalidate entries, and TTL expiry forces a refresh. For stampede protection, fire concurrent misses at an expired key and assert only one database call happens. fakeredis works for unit tests but does not reproduce eviction or TTL edge cases faithfully.

What is the difference between Redis and Memcached?

Redis is a data-structure server: strings, hashes, lists, sets, sorted sets, streams, plus persistence, pub/sub, and clustering. Memcached is the simpler, multithreaded key-value cache. For most workloads Redis wins on features and flexibility; Memcached still has a niche in pure high-throughput key-value caching where you do not need persistence or data structures.

Should I use Redis Cluster or Redis Sentinel?

They solve different problems. Sentinel gives you high availability — automatic failover to a replica — without increasing capacity. Cluster shards data across nodes for horizontal scale. When one node has the memory and throughput but downtime is off the table, that's Sentinel. If you have outgrown a single node, use Cluster. Many production deployments run Cluster with replica sets per shard, getting both.

Is write-behind safe for production?

It can be, but only with a durability story: AOF persistence on Redis (or a replicated setup), a bounded retry queue, idempotent writes, and a dead-letter path for failed flushes. If you can't answer "what happens to the last 30 seconds of writes when Redis crashes?" you're not ready for write-behind.