Cache Warmup Runbook
Operational runbook for warming caches after deploys, restarts and incidents: identify hot keys, preload by priority, verify hit ratio and roll back safely.
Overview
Every cold-start story sounds the same in the incident channel: the deploy went fine, the pods came up healthy, and then p95 latency tripled because every request fell through to the database at once. The application was never the problem — the cache was empty. This runbook is the procedure that prevents that: identify which keys actually matter, preload them before traffic arrives, verify the hit ratio, and only then open the floodgates.
Use it after deployments, Redis restarts, failovers to an empty replica, cache flushes, and recovery from incidents that evicted the data. Skip it when traffic is low enough that the cache refills on its own without hurting anyone — section 1 gives the thresholds to decide. If what you need is protection against a stampede on a single hot key rather than a fleet-wide warmup, the cache stampede prevention pattern covers that case.
1. Decide Whether to Warm Up
1.1 Triggers
Not every cache miss storm deserves a full warmup. Use this table to classify the trigger and budget the operation:
Trigger | Severity | Warmup budget
───────────────────────────┼─────────────┼──────────────
Planned deployment | Low | 2-5 min
Cache restart (Redis) | Medium | 1-3 min
Cache failover (sentinel) | High | 30 sec - 2 min
Post-incident recovery | High | 1-5 min
New cache cluster | Medium | 5-10 min
Cache flush (debug/test) | Low | 1-3 min
The budget column is a ceiling, not a goal. If warming the critical tier takes 25 seconds during a failover, stop there and let the rest fill — chasing 100% coverage under incident time pressure usually costs more latency than it saves.
1.2 Warm Up or Let It Fill Naturally?
The decision hinges on one question: can the database absorb the miss storm? Let the cache fill naturally when all of these hold:
Let it fill naturally when:
- Traffic is low (< 100 req/s on cacheable paths)
- Cache hit ratio recovers within ~5 minutes
- No user-facing latency requirement is at risk
- The database has idle headroom (CPU < 50%, replication lag ~0)
Warm up when any of these hold:
- Traffic is high (> 500 req/s on cacheable paths)
- A cold cache pushes p95 latency over ~500 ms
- An SLA requires < 200 ms response time
- After a cache failover in production
- Before opening traffic to a new region or cluster
When in doubt during a planned deploy, warm anyway — a five-minute warmup is cheap insurance. During an incident, invert that logic: warm only the critical tier and get traffic moving again.
2. Identify Hot Keys
Warmup lives or dies on this step. Warm too few keys and the miss storm still happens; warm everything and you pay the full cost of a database scan for keys nobody will read. The target is the top 1-5% of keys that serve 80-90% of traffic.
2.1 Rank by Access Frequency, Not by Size
Hot means frequently requested, not large. A 5 MB product blob read twice a day is cold; a 200-byte session key read 40,000 times an hour is the first thing you warm. In practice there are four usable sources, in order of preference:
- Access logs / APM traces — the most reliable source. Your application already knows which keys it
GETs most; aggregate the last 24 hours of structured logs. OBJECT FREQ— Redis 4.0+ returns the LFU counter per key, but only whenmaxmemory-policyis an LFU variant (allkeys-lfu,volatile-lfu). With LRU policies the counter does not exist and this method is unavailable.redis-cli --hotkeys— samplesMONITORtraffic briefly and reports the hottest keys it saw. Requires LFU policy too, and the sample window matters: run it during a representative traffic period, not at 4 AM.MONITORsampling — works under any eviction policy but is heavy. Capture 30-60 seconds of traffic on a replica (never on the primary under load), extractGET/SETEXkey names, count.
MEMORY USAGE still has a role, but a different one: it tells you the cost to regenerate and store a key, which is a good tiebreaker when two keys have similar frequency — warm the expensive one first.
import json
import redis
from collections import Counter
from typing import Callable
r = redis.Redis(host="localhost", port=6379, db=0)
def hot_keys_from_logs(log_path: str, top_n: int = 1000) -> list[str]:
"""Aggregate cache keys from structured access logs (last 24 h)."""
counter: Counter[str] = Counter()
with open(log_path) as f:
for line in f:
try:
entry = json.loads(line)
except json.JSONDecodeError:
continue
key = entry.get("cache_key")
if key:
counter[key] += 1
return [key for key, _ in counter.most_common(top_n)]
def hot_keys_from_lfu(top_n: int = 100) -> list[tuple[bytes, int]]:
"""Rank keys by LFU counter. Needs maxmemory-policy *-lfu."""
ranked: list[tuple[bytes, int]] = []
for key in r.scan_iter(count=5000): # SCAN, never KEYS, in production
try:
freq = r.object("FREQ", key) # None when policy is not LFU
except redis.ResponseError:
continue
if freq:
ranked.append((key, freq))
ranked.sort(key=lambda item: item[1], reverse=True)
return ranked[:top_n]
If neither logs nor LFU are available, the fallback is MONITOR sampling plus a pass over memory_usage() for the regeneration-cost tiebreak. Whatever the source, persist the result to a hot-keys file (/config/hot-keys.json in the examples below) so the failover procedure in section 5 has something to load at 3 AM.
2.2 Prioritize by Category
Frequency alone is not the final ordering — a lukewarm config key that every request depends on beats a scorching search-result key that regenerates in 5 ms. Bucket the ranked list by impact:
Category | Key pattern | Priority
──────────────────────┼──────────────────────────┼──────────
User sessions | session:{user_id} | Critical
User profiles | user:{user_id} | High
Product catalog | product:{product_id} | High
Configuration | config:{service} | High
Rate limit counters | ratelimit:{user_id} | Medium
Search results | search:{query_hash} | Low
Computed aggregations | stats:{metric}:{period} | Medium
Critical means “the user experience breaks without it”: sessions, auth state, anything on the request path with no cheap fallback. High covers data that is expensive to rebuild or hit constantly. Everything below Medium is usually better left to natural fill.
3. Warmup Procedures
3.1 Basic Warmup Script
The unit of work is a loader: a function that takes a key name and returns the value from the source of truth (database, service, computed). The warmer below checks existence first — re-warming a live key wastes a database read and can clobber fresher data written since the key list was exported.
import json
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Callable
import redis
r = redis.Redis(host="localhost", port=6379, db=0)
def warmup_key(key: str, loader: Callable[[str], dict | None], ttl: int = 3600) -> bool:
try:
if r.exists(key): # already warm — skip the DB read
return True
data = loader(key)
if data is None:
return False
r.setex(key, ttl, json.dumps(data))
return True
except (redis.RedisError, OSError) as e:
print(f"Failed to warm {key}: {e}")
return False
def warmup_batch(
keys: list[str],
loader: Callable[[str], dict | None],
ttl: int = 3600,
workers: int = 10,
) -> tuple[int, int]:
warmed = failed = 0
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(warmup_key, k, loader, ttl): k for k in keys}
for future in as_completed(futures):
if future.result():
warmed += 1
else:
failed += 1
print(f"Warmup batch: {warmed} warmed, {failed} failed")
return warmed, failed
For very large batches, pipeline the writes instead of issuing one SETEX per key — the round-trip cost dominates once you cross a few thousand keys. The exists() check also accepts a mild race: a key written between the check and the setex gets overwritten by identical data, which is harmless here because both paths read the same source of truth.
3.2 Progressive Warmup
Concurrency is a dial pointed at the database, not at Redis. Every warmed key is one query against the source of truth, so workers should stay well under your spare connection pool — as a starting point, no more than 10-20% of max_connections on a primary under live traffic, and watch replication lag while it runs.
def progressive_warmup(
key_groups: dict[str, list[str]],
loader: Callable[[str], dict | None],
ttl: int = 3600,
) -> None:
"""Warm in priority waves; lower tiers can wait for natural fill."""
workers_per_tier = {"critical": 20, "high": 15, "medium": 10, "low": 5}
for tier in ("critical", "high", "medium", "low"):
keys = key_groups.get(tier, [])
if not keys:
continue
workers = workers_per_tier[tier]
for i in range(0, len(keys), 100): # chunks with a pause
warmup_batch(keys[i:i + 100], loader, ttl, workers)
time.sleep(0.5) # let the DB breathe
print(f"{tier}: done")
The pause between chunks is the crude but effective part: it gives the database room to serve real traffic between batches. If the DB is already hot, drop workers before raising them — a warmup that triggers a slowdown on the primary defeats its own purpose.
3.3 Warmup with Health Checks
Never warm into a cache that cannot serve. Check the instance first, then warm, then verify coverage:
def warmup_with_health_check(
keys: list[str],
loader: Callable[[str], dict | None],
ttl: int = 3600,
) -> bool:
try:
r.ping()
info = r.info()
print(f"Redis {info['redis_version']}, "
f"memory {info['used_memory_human']}")
except redis.RedisError as e:
print(f"Redis not healthy: {e}")
return False
warmed, failed = warmup_batch(keys, loader, ttl)
ratio = warmed / len(keys) * 100 if keys else 100.0
print(f"Verification: {warmed}/{len(keys)} ({ratio:.1f}%), "
f"{failed} failed")
if ratio < 80:
print("WARNING: coverage below 80% — inspect failures")
return False
return True
Note that redis.info() returns version and memory keys like redis_version and used_memory_human — there is no status field, so guard against KeyError if you adapt this. Coverage below ~80% usually means the loader is failing on a class of keys (deleted rows, renamed pattern) rather than random noise; grep the failures before retrying.
4. Deployment Warmup
4.1 Pre-Deployment Warmup
Run this before switching traffic to the new deployment. The assumption is a new cache cluster or a flushed instance next to the old one — the old cache keeps serving until step 3 verifies the new one.
#!/bin/bash
# warmup-before-deploy.sh — run BEFORE switching traffic
set -euo pipefail
REDIS_HOST="redis-new.internal"
REDIS_PORT=6379
WARMUP_SCRIPT="/opt/scripts/cache-warmup.py"
echo "=== Pre-deployment cache warmup ==="
# 1. Export hot keys from current production logs
python /opt/scripts/extract-hot-keys.py --output /tmp/hot-keys.json
# 2. Warm the new cluster (loader reads the source of truth)
python "$WARMUP_SCRIPT" --keys /tmp/hot-keys.json \
--redis "$REDIS_HOST:$REDIS_PORT"
# 3. Verify the new instance is populated and healthy
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" \
info | grep -E 'used_memory_human|keyspace_hits|keyspace_misses'
redis-cli -h "$REDIS_HOST" -p "$REDIS_PORT" dbsize
echo "=== Warmup complete — safe to switch traffic ==="
set -euo pipefail matters here: if hot-key extraction or the warmer fails, the script exits non-zero and the deployment pipeline should treat that as a gate, not a warning. Whether to block the deploy on a failed warmup is the trade-off from section 1 — under a strict SLA, block; under a tolerant one, ship and let it fill.
4.2 Post-Deployment Verification
Sampling proves the cache holds what you warmed; the INFO counters prove it is actually serving. Check both:
def verify_post_deploy(
client: redis.Redis,
warmup_keys: list[str],
sample_size: int = 50,
) -> bool:
"""Sample warmed keys and compare with server-side hit stats."""
import random
sample = random.sample(warmup_keys, min(sample_size, len(warmup_keys)))
hits = sum(1 for key in sample if client.exists(key))
ratio = hits / len(sample) * 100
print(f"Sampled {len(sample)} keys: {hits} present ({ratio:.1f}%)")
stats = client.info("stats")
served_hits = stats.get("keyspace_hits", 0)
served_misses = stats.get("keyspace_misses", 0)
print(f"Server counters: {served_hits} hits / {served_misses} misses")
if ratio < 90:
print("ALERT: warmup coverage below 90% post-deploy")
return False
return True
A subtlety worth knowing: keyspace_misses climbing fast right after the switch is not necessarily a warmup failure — keys requested that were never in the hot set count as misses too. Judge by the hit ratio and by p95 latency, not by the raw miss counter.
5. Incident Warmup
5.1 Cache Failover Warmup
After a failover to an empty replica, the order of operations is critical-first, everything-else-later. The loader is injected so the same function works against the primary database or a fallback read replica:
def warmup_after_failover(
new_redis_host: str,
hot_keys_file: str,
loader: Callable[[str], dict | None],
) -> bool:
"""Warm an empty cache instance right after a Redis failover."""
client = redis.Redis(host=new_redis_host, port=6379)
# 1. Wait for the new instance to accept connections (max ~10 s)
for attempt in range(10):
try:
client.ping()
break
except redis.ConnectionError:
print(f"Waiting for Redis… attempt {attempt + 1}")
time.sleep(1)
else:
print("ERROR: Redis unavailable after 10 s")
return False
# 2. Load the persisted hot-key list (section 2)
with open(hot_keys_file) as f:
key_groups = json.load(f)
# 3. Critical tier only — short TTL, it will be refreshed soon
critical = key_groups.get("critical", [])
warmed, _ = _batch_on(client, critical, loader, ttl=900, workers=20)
# 4. High tier next; medium and low fill naturally
high = key_groups.get("high", [])
_batch_on(client, high, loader, ttl=3600, workers=15)
print(f"Failover warmup: {warmed} critical keys restored")
return True
def _batch_on(client: redis.Redis, keys: list[str],
loader: Callable[[str], dict | None],
ttl: int, workers: int) -> tuple[int, int]:
"""warmup_batch bound to a specific client (new instance)."""
def warm_one(key: str) -> bool:
try:
if client.exists(key):
return True
data = loader(key)
if data is None:
return False
client.setex(key, ttl, json.dumps(data))
return True
except redis.RedisError:
return False
ok = bad = 0
with ThreadPoolExecutor(max_workers=workers) as pool:
for done in pool.map(warm_one, keys):
ok, bad = ok + done, bad + (not done)
return ok, bad
Two details in this procedure are easy to get wrong under pressure. The critical tier gets a shorter TTL (900 s here) on purpose: failover-warmed data should be re-freshed soon rather than trusted for a full hour, because the failover may have happened mid-write. And the loader should point at a read replica if the primary is also recovering — warming off a struggling primary can finish the job the incident started.
5.2 Incident Warmup Checklist
- Confirm the new cache instance is healthy and accepting connections
- Verify network connectivity between application and cache
- Load the hot-keys file (persisted daily) or fall back to analytics
- Warm critical keys first: sessions, config
- Warm high-priority keys second: user profiles, catalog
- Watch database load while warming; drop workers if lag grows
- Verify the hit ratio before touching traffic weights
- Resume traffic gradually — canary 10% → 50% → 100%
- Keep the old instance reachable for 5-10 min as rollback cover
6. Verify and Monitor
Warmup without verification is a hope, not a procedure. Three signals tell you whether it worked:
| Signal | Where | Healthy target |
|---|---|---|
| Hit ratio | INFO stats → keyspace_hits / (hits+misses) | ≥ 90% within 5-10 min of traffic |
| Sampled coverage | verify_post_deploy sample | ≥ 90% of warmed keys present |
| p95 latency | APM on cacheable endpoints | Back to pre-trigger baseline |
The most common post-warmup surprise is a hit ratio stuck at 70-80% while coverage looks fine — that almost always means the traffic asks for keys outside the hot set, i.e., the hot-key extraction window was too short or unrepresentative. Re-extract with a longer window rather than just warming more of the same list.
Set two alerts for the hour after any warmup: hit ratio below target (your SLA line) and DB CPU/connection saturation (the sign that natural fill is doing the storm you tried to prevent). If the second fires, throttle incoming traffic — see the rate-limiting patterns — rather than adding more warmup workers.
7. Automation
7.1 Scheduled Warmup
For caches that expire or flush on a schedule (report caches, computed aggregates), cron a lighter version of the same job:
#!/usr/bin/env python3
"""Scheduled warmup — cron or task scheduler."""
import json
import logging
from datetime import datetime
import redis
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("cache-warmup")
def main() -> None:
with open("/etc/cache-warmup/config.json") as f:
config = json.load(f)
client = redis.Redis(**config["redis"])
start = datetime.now()
for source in config["warmup_sources"]:
with open(source["keys_file"]) as f:
keys = json.load(f)
loader = build_loader(source["loader"]) # per-source resolver
warmed, failed = warmup_batch(
keys, loader,
ttl=source.get("ttl", 3600),
workers=source.get("workers", 10),
)
log.info("%s: %d warmed, %d failed", source["name"], warmed, failed)
log.info("Warmup completed in %.1fs",
(datetime.now() - start).total_seconds())
if __name__ == "__main__":
main()
# Crontab: warm every 30 min, log for later inspection
*/30 * * * * /usr/bin/python3 /opt/scripts/scheduled-warmup.py >> /var/log/cache-warmup.log 2>&1
7.2 Kubernetes Warmup Job
For cluster warmups that should run once per deploy, a Job with ttlSecondsAfterFinished is enough — it cleans itself up:
apiVersion: batch/v1
kind: Job
metadata:
name: cache-warmup
spec:
ttlSecondsAfterFinished: 60
template:
spec:
restartPolicy: OnFailure
containers:
- name: warmup
image: registry.internal/cache-warmup:latest
command: ["python3", "/app/warmup.py"]
env:
- name: REDIS_HOST
value: "redis-cluster.internal"
- name: REDIS_PORT
value: "6379"
- name: HOT_KEYS_FILE
value: "/config/hot-keys.json"
volumeMounts:
- name: config
mountPath: /config
volumes:
- name: config
configMap:
name: cache-warmup-config
Run the Job as a pre-sync or post-sync hook in your deployment pipeline, and gate the traffic switch on its completion the same way the bash gate in section 4 works.
8. Common Mistakes
- Warmed keys expiring before the switch. Warming with a short TTL on a slow pipeline means the first keys are already gone when traffic arrives. Either warm close to the switch or give warmed keys a TTL comfortably longer than the deployment window — then let normal refresh take over.
- Ranking hot keys by
MEMORY USAGE. Size measures storage and regeneration cost, not access frequency. A huge but rarely-read key is still cold. Use logs, LFU counters, orMONITORsampling for the ranking; keep memory size as a regeneration-cost tiebreaker only. - Overwhelming the database you are protecting. Twenty workers against a primary at 80% CPU just moved the outage earlier in the timeline. Size workers against spare connections, and stop if replication lag grows.
- No hot-keys file on the day of the failover. The incident procedure loads a persisted list. If nothing persists the list, failover warmup degenerates into “warm what we remember,” which is how sessions get lost.
- Warming while a write stream repopulates. During incident recovery, writes may already be refilling keys; the
exists()check avoids clobbering them, so never strip it “for speed.” - Judging success on the miss counter.
keyspace_missesincludes requests for keys that were never warm candidates. Track hit ratio and p95 latency against your SLA line instead.
Further Reading
- Redis docs —
OBJECT FREQand LFU eviction policies — the counter behind frequency-based hot-key ranking. - Redis docs —
INFOserver statistics —keyspace_hits/keyspace_missesused in sections 4-6. - AWS Prescriptive Guidance — Database caching strategies using Redis — the strategy layer above this runbook.
- Complete Guide to Redis Caching Strategies — which strategy your warmed keys live under.
- Cache Stampede Prevention Pattern — single-hot-key stampedes, the case this runbook does not cover.
- Read-Through Cache Pattern — an alternative where the cache fills itself on miss instead of being warmed.
- Companion code: the cache-warmup-runbook companion repo packages the hot-key extractor, the tiered warmup runner, the deploy gate and the Kubernetes Job.
Frequently Asked Questions
How long should cache warmup take?
For most applications, 1-5 minutes is enough; the critical tier should be warm in under 30 seconds. Total time depends on key count, loader speed and concurrency. If a full warmup exceeds ~10 minutes, cut the set to critical-only and let the rest fill naturally — a slow warmup delays the very recovery it is meant to accelerate.
Should I warm up all keys or just hot keys?
Only the hot ones — typically the top 1-5% serving 80-90% of traffic. Warming everything pays a full database scan for data nobody reads, and on a sized cache it can evict the hot keys you just warmed. Rank by access frequency from logs or OBJECT FREQ, then warm the expensive-to-regenerate entries first.
What happens if warmup fails?
The cache fills naturally as traffic arrives, which means elevated latency for the first requests — the exact storm the runbook exists to prevent. Under a strict SLA, hold the deploy or traffic switch until warmup succeeds, and keep the old cache running as cover. During natural fill, watch database load and be ready to queue or rate-limit requests if it saturates.
How do I warm up a Redis cluster with multiple shards?
Connect per shard or use redis-cli -c in cluster mode so commands route by hash slot; a cluster-aware client library does the same in code. Warm shards in parallel, and watch per-shard memory so one shard does not overflow while others sit half-empty.
Can I warm up the cache without downtime?
Yes — this is the standard approach. Warm the new cache while the old one still serves, switch the application over, and keep the old instance available for 5-10 minutes as fallback. It costs a second cache instance for that window and buys a zero-cold-start deploy.
Does warmup work for non-Redis caches?
The procedure is identical — CDN edge caches, Memcached, in-process caches — only the hot-key source changes. For a CDN, "hot keys" are your top URLs and warming means issuing GET requests through the edge; the CDN cache rules template covers the policy side.
Related Resources
Cache Strategy Decision Template
Fill-in template for choosing and documenting a cache strategy per service: decision matrix, TTL rules, invalidation plan, and rationale record.
DocCache Eviction Policy Template
Template for documenting cache eviction rules per cache layer: LRU, LFU, TTL, FIFO, random eviction. Includes policy selection matrix, per-layer configuration, memory limits, and monitoring rules with code examples.
PatternCache Stampede Prevention Pattern
Prevent thundering herd cache misses with locks, single-flight, stale-while-revalidate and early refresh strategies that keep the database safe.
GuideComplete 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.