Course contentsShow
← System Design
Lesson 355 of 1,91910. NoSQL: Key-Value StoresFree lesson

Redis as a Cache

Using Redis for caching with TTLs, eviction policies (LRU, LFU), and cache-aside pattern implementation.

Redis as a Cache

What you'll learn: How to use Redis as a high-performance cache with time-based expiration, smart eviction policies, and the cache-aside pattern.

Why Redis Excels as a Cache

Redis's in-memory storage and single-threaded architecture make it perfect for caching—reading data at microsecond latency. You've already learned about Redis's TTL (time-to-live) feature; now we'll see how it powers real caching systems.

Time-to-Live (TTL) in Caching

Every cached item can have an expiration time. Set a user profile to expire in 5 minutes, and Redis automatically removes it when stale:

SET user:123 "profile_data" EX 300

This ensures your cache stays fresh without manual cleanup.

Eviction Policies

When Redis runs out of memory, it needs to evict data. You configure policies like:

  • LRU (Least Recently Used): Removes items not accessed recently—great for hot data
  • LFU (Least Frequently Used): Removes rarely-accessed items—better for popularity-based caching

Think of LRU like clearing out clothes you haven't worn lately, while LFU removes clothes you almost never wear.

Cache-Aside Pattern

The most common caching strategy:

  1. Read: Check Redis first
  2. Miss: If not found, fetch from database
  3. Populate: Store result in Redis with TTL
  4. Return: Serve data to user

On writes, you invalidate (delete) the cached key, forcing the next read to refresh from the database. This keeps your application in control of cache consistency.

When to Cache

Cache data that's read-heavy, computation-expensive, or tolerable to slight staleness—like product catalogs, user sessions, or API rate limits.

Key Takeaway: Redis caching with TTLs and eviction policies like LRU/LFU, combined with the cache-aside pattern, dramatically reduces database load and improves response times for read-heavy workloads.