In the cache-aside (lazy loading) pattern, who populates the cache?
Options
- The database itself fills the cache by itself
- The app: on a miss, read the DB and set the cache (Correct option)
- A nightly batch job that preloads all the keys
- The CDN fills the cache on every single request
Answer
The application: on a miss it reads the DB, then writes the value into the cache
Why
Cache-aside steps: 1) the app asks the cache; 2) if found (hit), use it; 3) if not (miss), read from the database and store the result in the cache with a TTL (expiry time).
Only data that is actually requested gets cached.
Downsides: the first request is slow, and cached data can be outdated until it expires or you delete it on update.
def get_user(uid):
user = cache.get(f"user:{uid}")
if user is None: # miss
user = db.load_user(uid)
cache.set(f"user:{uid}", user, ttl=300)
return userRemember
Cache-aside: check cache → on miss load DB → store in cache.