π§ 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
| Strategy | On Read | On Write | Sync With DB | Risk of Staleness |
|---|---|---|---|---|
| Cache-Aside | Load on miss | Write to DB, invalidate cache | Manual sync | Medium |
| Write-Through | Always cached | Write to cache + DB | Immediate | Low |
| Write-Behind | Always cached | Write to cache, delay DB | Async | High (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