Caching

Lesson 8 of 14 · 28 min

x
57%

Redis Deep Dive

Redis is the dominant distributed cache. It is an in-memory data store that supports strings, hashes, lists, sets, sorted sets, bitmaps, and more — far beyond simple key-value caching. Operations complete in sub-millisecond time because everything lives in RAM. Persistence options matter for production. RDB (Redis Database) takes point-in-time snapshots at intervals — fast recovery, but you may lose data since the last snapshot. AOF (Append Only File) logs every write operation — more durable, slower recovery. Most teams use both: RDB for fast restarts, AOF for durability. Redis Pub/Sub enables real-time messaging between services — useful for cache invalidation broadcasts. For caching specifically, strings with SETEX (set with expiry) and hashes for structured objects are the most common patterns.

Before
Plain string cache — no structure
await redis.setex('user:42', 300, JSON.stringify({
  name: 'Alice', email: 'alice@example.com', role: 'admin'
}));
// Must deserialize entire object to read one field
After
Redis hash — partial field access
await redis.hset('user:42', {
  name: 'Alice',
  email: 'alice@example.com',
  role: 'admin',
});
await redis.expire('user:42', 300);

// Read a single field without deserializing everything
const email = await redis.hget('user:42', 'email');

// Atomic increment for rate limiting
await redis.incr('rate:user:42');
await redis.expire('rate:user:42', 60);

Key Takeaway

Redis is more than a key-value store — use hashes, sorted sets, and pub/sub for structured caching and invalidation.

PreviousNext Lesson