Repaso
Español
System DesignIntermediateSD-04

In the cache-aside (lazy loading) pattern, who populates the cache?

Options

  1. The database itself fills the cache by itself
  2. The app: on a miss, read the DB and set the cache (Correct option)
  3. A nightly batch job that preloads all the keys
  4. 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 user

Remember

Cache-aside: check cache → on miss load DB → store in cache.

Key terms

Practice this question in Repaso