Caching Strategies with Redis and Valkey in 2026
Derar SattoufUpdated Backend & databases

"There are only two hard things in computer science: cache invalidation and naming things." The joke endures because caching is deceptively easy to add and surprisingly easy to get wrong. A badly designed cache serves stale prices, hides bugs, melts your database when it expires all at once, or quietly becomes the system of record.
Redis and its community fork Valkey are wire-compatible in-memory data stores that remain the default for application caching. The patterns here apply equally to both, and the examples stick to commands and client APIs common to each. Licensing and feature differences between Redis versions and Valkey evolve, so check the specifics for the version you deploy.
My default is cache-aside (lazy loading): read the cache, and on a miss load from the source and populate it. Every key needs a TTL, with jitter to avoid synchronized expiry. Prevent cache stampedes with request coalescing (single-flight), locks or probabilistic early refresh, and serve stale-while-revalidate when freshness allows.
Invalidate by deleting on write, and design key naming so related entries can be found. Some staleness is the price of caching, so bound it with TTLs. Treat the cache as disposable: the system must stay correct, just slower, if it is empty. And watch hit ratio, evictions, memory, latency and hot keys, with maxmemory and an eviction policy configured deliberately.
Redis, Valkey and the alternatives (late 2026)
| Option | Notes |
|---|---|
| Redis (Redis Ltd.) | Changed license in 2024 (source-available), then added the AGPLv3 option again with Redis 8 in 2025. Check the license terms for the version and distribution you use. |
| Valkey (Linux Foundation) | BSD-licensed fork created from Redis 7.2 in 2024; backed by AWS, Google Cloud, Oracle and others. Valkey 8 and 9 added performance work (multithreaded I/O), and features such as hash field expiration and multi-database support in cluster mode appeared in recent releases. Verify exact feature availability per version. |
| Managed services | ElastiCache, MemoryDB, Memorystore, Azure Cache, Upstash and others offer Redis- or Valkey-compatible endpoints; many major clouds now offer Valkey. Compare pricing and supported commands. |
| Dragonfly, KeyDB, Garnet, Memcached | Alternatives with different architectures or protocols; check command compatibility before swapping. Memcached is excellent for pure, simple caching. |
Clients that speak the Redis protocol (RESP) generally work against both. Keep your code to the common command set, make the connection URL configurable, and test against the exact server you deploy.
Decide what to cache
Good candidates:
- Expensive reads: aggregates, joins, rendered fragments, third-party API responses.
- Read-heavy, rarely changing data: configuration, product catalogs, feature flags.
- Session data and short-lived tokens (with care).
- Results of idempotent computations.
Poor candidates:
- Data that must be strongly consistent on every read (account balances during a transfer).
- Highly unique, never-repeated queries (hit ratio near zero).
- Anything you cannot afford to lose, if the cache is your only copy.
Before adding a cache, check whether the underlying query just needs an index. A cache in front of a slow query adds complexity; an index removes the problem.
Core pattern: cache-aside
import { createClient } from "redis";
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const TTL_SECONDS = 300;
const jitter = (base: number, pct = 0.1) =>
Math.round(base * (1 - pct + Math.random() * pct * 2));
export async function getProduct(id: string) {
const key = `v1:product:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const product = await db.product.findUnique({ where: { id } });
if (!product) {
// Negative caching: remember "not found" briefly to protect the database
await redis.set(key, JSON.stringify(null), { EX: 30 });
return null;
}
await redis.set(key, JSON.stringify(product), { EX: jitter(TTL_SECONDS) });
return product;
}
export async function updateProduct(id: string, data: ProductInput) {
const updated = await db.product.update({ where: { id }, data });
await redis.del(`v1:product:${id}`); // invalidate on write
return updated;
}Details that matter:
- Version prefix (
v1:) lets you invalidate everything by bumping the version when the cached shape changes. Deploying a new serialization format without a version bump produces deserialization errors across your fleet. - Jitter prevents thousands of keys created together from expiring together.
- Negative caching stops repeated lookups for nonexistent IDs (a common accidental DoS vector).
- Delete on write, rather than update-in-place, avoids race conditions where a slow writer overwrites a newer value.
The classic race
T1: read DB -> value A
T2: write DB -> value B, delete cache
T1: write cache <- A (stale value cached until TTL!)This is rare but real. Mitigations: short TTLs, versioned values (store a row updated_at or version and only overwrite with a newer one via a Lua script), or delayed double-delete (delete again after a short delay). For most apps, a modest TTL is an acceptable safety net.
Other write patterns
| Pattern | Flow | Use when |
|---|---|---|
| Cache-aside | App reads/writes cache and DB explicitly | General default |
| Read-through | Cache library loads from DB on miss | You want it hidden in a layer |
| Write-through | Write to cache and DB together | Reads must see new data immediately; accept write latency |
| Write-behind | Write cache now, DB asynchronously | Very high write rates; risk of data loss if cache dies |
| Refresh-ahead | Refresh hot keys before they expire | Predictable hot data, strict latency |
Write-behind makes the cache a system of record for a window of time. Do not use it unless you have a durable queue and a loss-tolerance story.
Stampede protection
A cache stampede (thundering herd) happens when a popular key expires and hundreds of concurrent requests all miss, all hit the database, and all recompute the same expensive value, possibly taking the database down.
Option A: single-flight inside each process
const inflight = new Map<string, Promise<unknown>>();
export function singleFlight<T>(key: string, loader: () => Promise<T>): Promise<T> {
const existing = inflight.get(key) as Promise<T> | undefined;
if (existing) return existing;
const p = loader().finally(() => inflight.delete(key));
inflight.set(key, p);
return p;
}
// usage
const product = await singleFlight(`product:${id}`, () => loadAndCache(id));This collapses concurrent misses within one process. With 50 instances you still get up to 50 loads, which is usually fine.
Option B: distributed lock for the refresh
async function getWithLock(key: string, ttl: number, loader: () => Promise<unknown>) {
const hit = await redis.get(key);
if (hit) return JSON.parse(hit);
const lockKey = `lock:${key}`;
const token = crypto.randomUUID();
const gotLock = await redis.set(lockKey, token, { NX: true, EX: 10 });
if (gotLock) {
try {
const value = await loader();
await redis.set(key, JSON.stringify(value), { EX: ttl });
return value;
} finally {
// Release only if we still own the lock (compare token atomically)
await redis.eval(
`if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end`,
{ keys: [lockKey], arguments: [token] }
);
}
}
// Someone else is loading: wait briefly, then re-check
await new Promise(r => setTimeout(r, 50 + Math.random() * 50));
return getWithLock(key, ttl, loader); // add a retry cap in real code
}Always set a lock TTL so a crashed holder cannot block forever, and release with an atomic compare-and-delete script.
Option C: stale-while-revalidate (usually the best UX)
Store the value with a soft expiry inside the payload and a longer hard TTL on the key. After the soft expiry, serve the stale value immediately while one request refreshes it in the background.
type Entry<T> = { value: T; softExpiresAt: number };
export async function swr<T>(key: string, softTtl: number, hardTtl: number, loader: () => Promise<T>): Promise<T> {
const raw = await redis.get(key);
if (raw) {
const entry: Entry<T> = JSON.parse(raw);
if (Date.now() < entry.softExpiresAt) return entry.value; // fresh
refreshInBackground(key, softTtl, hardTtl, loader); // stale: refresh async
return entry.value;
}
return refreshNow(key, softTtl, hardTtl, loader); // cold
}Option D: probabilistic early expiration
Each request has a small, increasing chance of refreshing before expiry (the "XFetch" algorithm), spreading refreshes over time without locks.
Invalidation strategies
- TTL only: simplest. Accept bounded staleness. Great for data where a 1-5 minute lag is fine.
- Delete on write: the writing code path deletes affected keys. Needs discipline: every write path must know every key.
- Event-driven: publish change events (from the application, an outbox, or CDC such as Debezium) and let a consumer invalidate keys. Decouples writers from cache layout.
- Tag-based: maintain sets of keys per tag; invalidate a tag by deleting its members.
// Tagging: group keys that depend on a category
await redis.set(`v1:product:${id}`, json, { EX: 300 });
await redis.sAdd(`tag:category:${categoryId}`, `v1:product:${id}`);
// Invalidate the whole category
const keys = await redis.sMembers(`tag:category:${categoryId}`);
if (keys.length) await redis.del(keys);
await redis.del(`tag:category:${categoryId}`);- Key versioning ("generation keys"): include a counter in keys,
product-list:{categoryVersion}:page1, and incrementcategoryVersionto orphan all old entries instantly. Old entries expire naturally by TTL. This avoids scanning and deleting.
Avoid KEYS * in production (it blocks the server). Use SCAN with a cursor for any enumeration, and prefer designs that never need it.
Key design and serialization
- Namespaced, predictable keys:
app:env:entity:id:variant, for exampleshop:prod:product:42:en. - Include everything the value depends on: locale, currency, tenant, user role. Forgetting
tenantIdin a key is a classic data-leak bug in multi-tenant apps. - Keep values reasonably small (kilobytes, not megabytes). Large values increase latency for everyone because commands are processed on a single thread per shard.
- Choose serialization deliberately: JSON is simple; MessagePack or Protobuf is smaller and faster. Compress large payloads only when the CPU tradeoff is worth it.
- Use native types when they fit: hashes for objects with partial updates, sorted sets for leaderboards, streams for event logs,
HyperLogLogfor approximate unique counts.
// Hash: update one field without rewriting the whole object
await redis.hSet(`user:${id}:profile`, { name: "Ada", plan: "pro" });
await redis.hIncrBy(`user:${id}:stats`, "logins", 1);More than a cache: rate limiting and locks
Fixed-window rate limiting (atomic with INCR)
export async function allow(userId: string, limit = 100, windowSec = 60) {
const bucket = Math.floor(Date.now() / 1000 / windowSec);
const key = `rl:${userId}:${bucket}`;
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, windowSec);
return count <= limit;
}For smoother behavior use a sliding window or token bucket implemented in a Lua script (atomic). See the API design post on this blog for more.
Distributed locks: know the limits
A single-instance lock with SET NX EX is fine for efficiency locks (avoid duplicate work). For correctness-critical mutual exclusion (such as preventing double-charging), a lock alone is not enough; use fencing tokens or, better, database constraints and idempotency keys. Lock expiry during a long pause (GC, network) can allow two holders at once.
Layered caching: L1 in-process plus L2 Redis
For ultra-hot, small, rarely changing data, keep a short-lived in-process cache (L1) in front of Redis (L2). It saves a network round trip but introduces per-instance staleness.
import { LRUCache } from "lru-cache";
const l1 = new LRUCache<string, unknown>({ max: 5000, ttl: 5_000 }); // 5 seconds
export async function getConfig(key: string) {
const local = l1.get(key);
if (local !== undefined) return local;
const raw = await redis.get("v1:config:" + key);
const value = raw ? JSON.parse(raw) : await loadFromDb(key);
if (!raw) await redis.set("v1:config:" + key, JSON.stringify(value), { EX: 300 });
l1.set(key, value);
return value;
}To invalidate L1 across instances, publish a message on a Pub/Sub channel when data changes and have each instance delete the key locally. Redis and Valkey also support client-side caching with server-assisted invalidation (RESP3 tracking); client library support varies, so check yours.
Other caching layers worth using first
- Browser and CDN caching with
Cache-Controlfor public content (the cheapest cache; no server hit at all). - Framework data caches (for example in Next.js, see Server Components, caching and data patterns).
- Application cache (this article).
- Database caches: Postgres shared buffers and the OS page cache already serve repeated reads; tune before adding a cache (see Postgres query performance).
Caching expensive AI calls
The same patterns apply to LLM and embedding calls: key on a hash of the model, prompt and parameters, set a TTL, and never share cached answers across tenants or permission levels. Provider-side prompt caching is a separate feature; see LLM cost optimization and prompt caching and AI gateway and model routing.
Python equivalent of cache-aside
import json, random
import redis
r = redis.Redis.from_url("redis://localhost:6379/0", decode_responses=True)
def get_product(product_id: str):
key = f"v1:product:{product_id}"
cached = r.get(key)
if cached is not None:
return json.loads(cached)
product = db_load_product(product_id) # your database call
ttl = int(300 * random.uniform(0.9, 1.1)) # jitter
r.set(key, json.dumps(product), ex=ttl if product else 30)
return productOperations: memory, eviction, and persistence
Memory limits and eviction
maxmemory 2gb
maxmemory-policy allkeys-lfu # evict least frequently used keys when fullallkeys-lru/allkeys-lfu: right for a pure cache; anything can be evicted.volatile-*: evict only keys with a TTL. Safer when you mix cache and durable data, but then you hit out-of-memory errors if keys lack TTLs.noeviction: writes fail when full. Appropriate only when Redis holds data you cannot lose.
Do not mix durable data (queues, primary records) and disposable cache in the same instance; give them separate instances with different policies.
Persistence
Pure cache: persistence can be off for speed. If you cache expensive-to-warm data, enable RDB snapshots so a restart does not cause a cold-start stampede. AOF adds durability for non-cache use.
Monitoring
Track these:
| Metric | Healthy signal |
|---|---|
Hit ratio (keyspace_hits / (hits + misses)) | High and stable; sudden drops mean invalidation bugs or key churn |
evicted_keys | Near zero means adequately sized; rising means undersized or poor TTLs |
Memory used vs maxmemory | Headroom for fragmentation and replication buffers |
| Command latency / slowlog | No long-running commands |
| Connected clients, blocked clients | Within pool limits |
| Hot keys / big keys | redis-cli --hotkeys, --bigkeys (use on replicas) |
redis-cli INFO stats | grep -E 'keyspace_(hits|misses)|evicted_keys'
redis-cli SLOWLOG GET 10
redis-cli --bigkeysResilience
- Set client timeouts and retries with backoff; never let a cache outage take down your app. On cache failure, fall back to the source (with rate limiting or a circuit breaker to protect it).
- Use replicas and automatic failover (Sentinel, or Cluster / managed service) for availability.
- In Cluster mode, multi-key operations require keys in the same slot; use hash tags (
{user:42}:profile) deliberately.
Where caching goes wrong
- No TTL on keys, so memory grows until eviction or an outage.
- The same TTL for everything, producing synchronized expiry spikes.
- Caching per-user data under a shared key (a security bug).
- Treating Redis as a database without persistence or backups.
- Using
KEYSor giantSMEMBERS/HGETALLon huge collections in production. - Caching errors or empty responses for too long after a transient failure.
- Not measuring hit ratio, so nobody notices the cache stopped helping.
- Caching before profiling, which hides a missing database index.
Hands-on lab: watch a stampede happen and fix it
docker run --rm -d --name cache-lab -p 6379:6379 valkey/valkey:latest
# or: docker run --rm -d --name cache-lab -p 6379:6379 redis:latest
redis-cli ping- Write a function that "loads" a value by sleeping 500 ms and incrementing a counter in Redis (
INCR loads). - Cache it with the cache-aside code above and a 2 second TTL.
- Fire 200 concurrent requests right after expiry with a load tool (
autocannon,k6, or a small script withPromise.all). - Check
GET loads: without protection it will be close to the number of concurrent requests. - Add
singleFlightand repeat. Expect about one load per process. - Add the distributed lock or stale-while-revalidate and repeat with several processes. Expect one load in total.
- Clean up:
docker stop cache-lab.
// k6 or any HTTP load tool works; a script version:
await Promise.all(Array.from({ length: 200 }, () => getProduct("42")));
console.log("loads:", await redis.get("loads"));Security
- Never expose Redis or Valkey to the public internet. Bind to a private network, use security groups, and enable TLS in transit when traffic crosses hosts.
- Use ACLs: create a dedicated user per application with only the commands and key patterns it needs, and disable dangerous commands (
FLUSHALL,CONFIG,DEBUG,KEYS) for application users. - Set a strong password or use your cloud's IAM authentication; rotate credentials.
- Do not store secrets or sensitive personal data in the cache without considering encryption and retention. Cached data can outlive a deletion request, so include cache keys in your data deletion process.
- Namespacing is not a security boundary; use separate instances or ACL key patterns for tenants that need isolation.
Troubleshooting
| Symptom | Likely cause and fix |
|---|---|
| Hit ratio drops suddenly | Deploy changed key format or version prefix; keys include a changing value (timestamp, request id); TTL too short. |
| Memory keeps growing | Keys without TTL, large values, or fragmentation; check INFO memory and --bigkeys. |
| Latency spikes | Large key operations, KEYS or huge HGETALL, persistence forks, swapping, or a slow client; see SLOWLOG. |
| Stale data after update | A write path forgot to invalidate, the race condition described under cache-aside, or a replica read lag; shorten TTL, add event-driven invalidation. |
OOM command not allowed | maxmemory reached with noeviction, or with volatile-* and no TTL keys; fix policy and TTLs. |
| Evictions of hot keys | Instance too small for the working set; add memory or reduce value size. |
| Connection errors under load | Client pool too small or too large; configure timeouts, pool size and keepalive. |
Cluster CROSSSLOT errors | Multi-key command across slots; use hash tags or restructure. |
Questions that come up
How long should TTLs be? As long as staleness is acceptable for the business, shorter for volatile data. Start with minutes for lists and aggregates, hours for configuration, and add event-driven invalidation if you need fresher data.
Should I cache in Redis or in the database? If the database can serve the query fast with an index, do not cache. If the query is inherently expensive, or the load is huge, cache it.
Is Redis single-threaded? Historically command execution is single-threaded per shard; newer versions use I/O threads to speed up network handling, so one instance scales further. Scale beyond that with Cluster or more instances.
Can I use the cache for sessions? Yes, with persistence or accepting forced re-login on loss. Store a session id in an HttpOnly cookie and the data in Redis.
How do I cache paginated lists? Cache pages keyed by filter and cursor, and invalidate with generation keys when the underlying set changes. See API design: rate limiting, idempotency and pagination.
How do I test cache logic? Use a real Redis or Valkey in tests (via containers) rather than mocks, and add tests for invalidation and stampede behavior.
Sources and docs
- Redis documentation
- Valkey documentation
- Redis eviction policies
- Optimal probabilistic cache stampede prevention (XFetch paper)
- How to do distributed locking (Martin Kleppmann)
- Related on this site: Django performance optimization, Express.js performance optimization, FastAPI performance optimization, event-driven architecture with outbox and idempotency