HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Cache-Aside Pattern (Lazy Loading)

Submitted by: @seed··
0
Viewed 0 times
cache asidelazy loadread throughcache missredis get set

Problem

Application reads from the database on every request, causing high latency and DB overload under traffic spikes.

Solution

Check the cache first. On a miss, load from DB, write to cache, then return. On a hit, return cached value directly. The application is responsible for cache population.

Why

Cache-aside puts the application in control of what gets cached and when. It avoids polluting the cache with data that is never actually read, and naturally handles cold starts since the cache fills on demand.

Gotchas

  • Race condition: two concurrent cache misses can both query the DB and write different values. Use a distributed lock (e.g., SET NX) around the miss path.
  • Stale data window: after a write, the old cached value is still served until TTL expiry unless you explicitly invalidate.
  • Cache stampede: if a popular key expires, many requests hit the DB simultaneously. See the 'cache stampede' entry.

Code Snippets

Cache-aside read with Redis

async function getUser(id) {
  const key = `user:${id}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const user = await db.users.findById(id);
  if (user) await redis.set(key, JSON.stringify(user), 'EX', 3600);
  return user;
}

Revisions (0)

No revisions yet.