Back to all posts

System Design Explained to a 5-Year-Old ยท Episode 7

Redis Caching Explained: The Desk vs. The Big Basement Closet

#System Design#Redis#Caching#Database#Backend#what is redis#redis explained simply#redis caching for beginners#in memory database#cache hit vs cache miss#cache aside pattern#write through vs write behind#redis lru eviction#time to live ttl#system design interview#eli5 system design#redis performance
Redis Caching Explained: The Desk vs. The Big Basement Closet
August 15, 20267 min read

Picture yourself drawing a colorful masterpiece at your study table. Your favorite red crayon is sitting right on top of the desk. When you need it, reaching out and grabbing it takes half a second.

Now imagine keeping every single crayon locked inside a heavy wooden chest down in the basement. Every time that red crayon is needed, you have to stand up, walk down two flights of stairs, unlock the chest, grab the crayon, and walk all the way back up. That trip takes ten minutes!

That is the exact difference between Redis (the quick desk) and a Traditional Database (the slow basement closet).

Redis In-Memory Cache (The quick study desk) vs Traditional Database (The basement storage chest)

Keywords

  • RAM (In-Memory): Super fast, temporary computer memory (the desk surface right in front of you).
  • Disk Storage (Database): Permanent, slower storage on hard drives or SSDs (the heavy basement chest).
  • Cache Hit: The requested item is already sitting ready on the desk.
  • Cache Miss: The item isn't on the desk, so a slow trip down to the basement is required.
  • TTL (Time to Live): A countdown timer that automatically clears old, unused items off the desk.
  • Eviction Policy (LRU): Removing the least recently touched item when the desk runs out of room.

Character Mapping

  • Redis (In-Memory Cache): The Quick Desk right next to your chair (fast to reach, but limited space).
  • Database (PostgreSQL / MySQL / MongoDB): The Deep Basement Closet (holds unlimited items permanently, but takes effort and time to open).
  • Application Server (Backend): The Painter creating the artwork.
  • End User / Client: The person asking to view the finished artwork.

1. How Redis Works in Everyday Systems

When someone opens a profile or loads a product page on an app, the server doesn't immediately dig through millions of database rows on disk. Instead, it follows a smart routine:

text
๐Ÿ‘ค User (App Visitor)
   |
   | 1. "Show me the user profile for Alice!"
   โ†“
๐Ÿ–ฅ๏ธ Application Server (The Painter)
   |
   |--- [Step 1: Check the Desk] ---> โšก Redis (RAM Cache)
   |                                    |
   |   <--- [Cache Hit: 1โ€“2ms] ---------| (Delivers instantly!)
   |
   |--- [Cache Miss: Not on Desk] ---> ๐Ÿ—„๏ธ Database (Basement Disk)
   |                                     |
   |   <--- [Query: 50โ€“100ms] -----------| (Fetches from storage)
   |
   |--- [Step 3: Save copy on Desk] --> โšก Redis (Stored for next time!)
   โ†“
๐Ÿš€ Delivers profile to User!

Step 1: First Check (Look at the Desk)

The application server checks Redis first. Reading from RAM takes less than 1โ€“2 milliseconds. If the data is sitting there (Cache Hit), it delivers it immediately without bothering the main database.

Step 2: The Miss (Checking the Basement Storage)

If the data isn't in Redis (Cache Miss), the server heads down to the basement and executes a slower query against the primary database (PostgreSQL, MySQL, etc.).

Step 3: Saving for Next Time (Hydrating the Cache)

The server grabs the fresh database result, places a copy right on the Redis desk with an expiration timer, and returns the response to the user. The next thousand people who ask for that exact same profile get it straight from the desk instantly!


Engineers use different habits and strategies to keep data handy on the desk:

text
Pattern A: Cache-Aside (Lazy Loading)
Painter checks Desk โž” Missing? โž” Fetches from Basement โž” Copies to Desk

Pattern B: Write-Through (Synchronous)
Painter writes new note โž” Copies to Desk AND Basement at the exact same moment

Pattern C: Write-Behind (Asynchronous / Write-Back)
Painter scribbles on Desk instantly โž” Background worker files to Basement later

Pattern A: Cache-Aside (Look First, Fetch if Missing)

  • The Routine: The application looks at Redis first. If the data is absent, it fetches from the database, writes it into Redis, and returns it.
  • Why it's great: It is the most widely used caching pattern because Redis only holds items users actually request, saving precious RAM.
  • Trade-off: A cache miss has a slight penalty because it requires three steps (read cache โ†’ read DB โ†’ write cache).

Pattern B: Write-Through (Save Everywhere at Once)

  • The Routine: Whenever data is added or updated, the application writes the update to Redis and the primary database simultaneously before acknowledging success.
  • Why it's great: The cache is always 100% consistent with the database. You never read stale data.
  • Trade-off: Writing takes slightly longer because every write must complete in two places.

Pattern C: Write-Behind / Write-Back (Write on Desk First, File Later)

  • The Routine: The application writes new data directly to Redis at lightning speed and confirms success immediately. A background task collects updates and batches them down to the database periodically (e.g., every 5 minutes).
  • Why it's great: Blazing fast write speeds, ideal for high-frequency writes like game telemetry or logging.
  • Trade-off: If the Redis server crashes before the background worker files the data into the database, unsaved changes could be lost!

3. What Happens When the Desk Gets Full? (LRU & TTL)

A desk surface cannot hold everything in the house. Because RAM is expensive and limited in size (e.g., 16 GB of RAM vs. 2 TB of hard drive space), Redis needs rules to manage space:

text
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                   THE REDIS DESK                       โ”‚
โ”‚  [Red Crayon]    [Blue Crayon]    [Green Crayon]       โ”‚
โ”‚  (Used 1s ago)   (Used 10s ago)   (Used 2 hrs ago)     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                           โ”‚
            โœจ New Yellow Crayon arrives!
                           โ”‚
                           โ–ผ
          ๐Ÿ‘‹ Bye Green Crayon! (LRU Eviction)

LRU (Least Recently Used) Eviction

When Redis runs out of memory and needs to store new data, the LRU algorithm identifies the key that hasn't been touched for the longest period of time, deletes it from RAM, and makes room for the new item.

TTL (Time to Live / Self-Cleaning Timer)

You can attach an automatic countdown timer (e.g., EXPIRE key 1800 for 30 minutes) to any cached item. Once the timer reaches zero, Redis quietly removes the key. This ensures temporary data like trending hashtags or weather reports refresh regularly.


4. Real-World Uses for Redis

Use CaseHow Redis Powers ItWhy Redis is Chosen
๐Ÿ† Live Sports Scores & LeaderboardsUses Redis Sorted Sets (ZSET) to update and rank millions of players in real-time.Instant sub-millisecond reads without hammering the SQL database.
๐Ÿ›’ Shopping Cart SessionsStores temporary shopping carts and active login tokens.Keeps page navigation silky smooth across hundreds of product pages.
๐Ÿ“ฑ OTP & Verification CodesStores 6-digit SMS login codes with a strict 2-minute TTL timer.Data automatically self-destructs without running manual database cleanup jobs.
๐Ÿ›ก๏ธ API Rate LimitingTracks request counts per user IP address per minute.Increments counters atomically at over 100,000 operations per second.

5. Redis vs. Traditional Database: Quick Comparison

Featureโšก Redis (Cache)๐Ÿ—„๏ธ Traditional DB (PostgreSQL / MySQL)
Storage LocationRAM (In-Memory)Hard Disk / SSD (Persistent)
SpeedSub-millisecond (0.5 โ€“ 2 ms)Milliseconds to Seconds (15 โ€“ 200 ms)
CapacityLimited (Gigabytes)Massive (Terabytes to Petabytes)
CostHigher per GBMuch cheaper per GB
Primary JobUltra-fast temporary accessPermanent, durable source of truth

๐Ÿ• Explain It Like You're 5

If you are doing your homework, you keep your pencil, eraser, and ruler right on top of your desk (Redis).

You don't walk to the storage closet in the basement (Database) every time you need to erase a letter. You only visit the basement when you need a brand-new notebook that isn't on your desk yet!


๐ŸŽฏ The System Design Interview Summary

In modern scalable backend architectures, never let read-heavy traffic hit your primary database directly.

text
๐Ÿ‘ค Users (Millions of Requests)
   โ†“
๐ŸŒ CDN (Static Assets: Images, Video Chunks, CSS)
   โ†“
๐Ÿ›ก๏ธ Load Balancer
   โ†“
๐Ÿ–ฅ๏ธ Application Servers
   โ†“
   โ”œโ”€โ”€โ”€> โšก Redis Cache (Frequent Reads, Sessions, Leaderboards)
   โ”‚        โ†“ (95% Cache Hit Ratio)
   โ”‚      [Instant Response โšก]
   โ”‚
   โ””โ”€โ”€โ”€> ๐Ÿ—„๏ธ Primary Database (Source of Truth, Writes, Complex Queries)

By placing Redis between your application servers and primary database, you can achieve sub-millisecond latency, handle massive traffic spikes, and protect your database from crashing under heavy load.

Enjoyed this article? Share it: