Script Valley
System Design: APIs, Caching & Scalability
Caching FundamentalsLesson 2.5

Redis as a cache: patterns and best practices

Redis data structures, key naming conventions, TTL management, Redis Cluster, connection pooling, avoiding hot keys, Redis vs Memcached

Redis as a cache: patterns and best practices

Redis cache architecture

Why Redis Dominates

Redis is in-memory, single-threaded, and blazingly fast — sub-millisecond reads at scale. It supports rich data structures beyond simple key-value: strings, hashes, sorted sets, and lists, making it useful for more than plain caching.

Key Naming Conventions

Use colon-separated namespaces. Be explicit:

# Good
user:42:profile
product:catalog:page:3
session:token:abc123

# Bad
userdata
cache_product_3
temp

Always Set TTLs

# Set with expiry in seconds
await redis.setex('user:42:profile', 3600, JSON.stringify(user));

# Or use SET with EX option
await redis.set('user:42:profile', JSON.stringify(user), 'EX', 3600);

Never write a cache key without a TTL. Memory will grow unbounded.

Avoiding Hot Keys

A hot key is a single key receiving millions of requests per second. Redis is single-threaded, so one hot key saturates a node even in a cluster. Solutions: a local in-process cache as L1 in front of Redis, or shard the key into N variants such as product:top:0 through product:top:9 and randomly select one on read. Always use connection pooling — never create a new Redis connection per request.