🧠 Cache-Aside Pattern (Lazy Loading) β€” Explained

Cache-Aside (also known as Lazy Loading) is a caching strategy where your application explicitly loads data into the cache only when needed β€” typically on a cache miss.


πŸ’‘ Simple Definition

β€œYou look in the cache. If it’s not there, you go to the database, get the data, store it in the cache, and return it.”


πŸ”„ How Cache-Aside Works

1. App asks: β€œIs the data in cache?”
   β†’ If YES β†’ return it βœ…
   β†’ If NO β†’ fetch from DB β›”

2. After DB fetch:
   β†’ Store the data in cache βœ…
   β†’ Return it to user

🧱 Typical Flow

// Pseudocode
function getData(key):
    data = cache.get(key)
    if data is null:
        data = db.query(key)
        cache.set(key, data)
    return data

✏️ Write Flow

In cache-aside, writes and updates go directly to the database, and the cache is either:

  • Invalidated (deleted), or

  • Updated manually

function updateData(key, newValue):
    db.update(key, newValue)
    cache.delete(key) // or cache.set(key, newValue)

βœ… Advantages

  • Simple and flexible

  • Avoids caching infrequently accessed data (saves memory)

  • Good control over when/what to cache


❌ Disadvantages

  • Cache miss penalty on first request

  • Risk of stale data if you don’t invalidate cache correctly

  • Extra code complexity to manage both cache and DB access


πŸ” Cache-Aside vs Write-Through vs Write-Behind

StrategyOn ReadOn WriteSync With DBRisk of Staleness
Cache-AsideLoad on missWrite to DB, invalidate cacheManual syncMedium
Write-ThroughAlways cachedWrite to cache + DBImmediateLow
Write-BehindAlways cachedWrite to cache, delay DBAsyncHigh (until flush)

πŸ› οΈ When to Use Cache-Aside

  • Read-heavy systems with occasional writes

  • When you want fine-grained control over cache population

  • Situations where data may change frequently, and cache needs to stay fresh


πŸ“¦ Real-World Examples

  • Product pages in an e-commerce site

  • Profile data in social media apps

  • News articles or blog posts