Core Module
12 min forge

Cache Aside Pattern

Master the most common caching strategy. Learn how to balance speed and data freshness by loading data into the cache only when needed.

⚑ Cache Aside Pattern (Lazy Loading)

The Cache Aside pattern is the most common caching strategy. In this pattern, the application is responsible for managing the cache and the database.

πŸ’‘ The Logic (ELI5)

Think of a Personal Assistant:

  1. You ask your Assistant for a phone number.
  2. Step 1: The Assistant checks their Notebook (The Cache).
  3. Step 2 (The Hit): If it's there, they give it to you instantly.
  4. Step 3 (The Miss): If it's not in the notebook, they run to the giant File Cabinet (The Database) to find it.
  5. Step 4: They give you the number AND write it down in their notebook so they don't have to go to the cabinet next time.

πŸ” The Deep Dive

How it works

  1. Application receives a request for data.
  2. Application checks the cache.
  3. If Cache Hit: Return data.
  4. If Cache Miss:
    • Query the Database.
    • Store the result in the Cache.
    • Return data.

Pros

  • Resilience: If the cache server (e.g., Redis) goes down, the application still works (it just goes straight to the DB).
  • Efficiency: Only requested data is cached. No wasting space on data that isn't being used.

Cons

  • First Load Delay: The very first time a piece of data is requested, it will be slow (Cache Miss).
  • Data Stale-ness: If the database is updated directly, the cache might still have the old value until it expires or is manually deleted.

🎯 Interview Pulse

Use Case

Best for general-purpose caching and read-heavy workloads where you can tolerate a small amount of data delay.

The "Thundering Herd" Problem

If 1,000,000 users all ask for the same new piece of data at the exact same time, and it's not in the cache yet, all 1,000,000 requests will hit your Database at once. The Solution: Use Locking or Pre-warming the cache for highly popular items.

Key Strategy: Invalidation

When you update the DB, you should usually delete the cache entry. This forces the next request to be a "Miss," which will then fetch the fresh data from the DB. πŸš