100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Database Query Caching Strategies Cheat Sheet

Database Query Caching Strategies Cheat Sheet

Query caching patterns covering cache-aside, write-through, Redis-backed result caching, invalidation, and stampede prevention.

2 PagesIntermediateJun 8, 2026

Cache-Aside (Lazy Loading)

The most common pattern: check cache first, fall back to DB, populate cache on miss.

typescript
async function getUser(id: string): Promise<User> {  const cacheKey = `user:${id}`;  const cached = await redis.get(cacheKey);  if (cached) return JSON.parse(cached);  const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);  await redis.set(cacheKey, JSON.stringify(user), 'EX', 300); // TTL 5 min  return user;}async function updateUser(id: string, data: Partial<User>) {  await db.query('UPDATE users SET name = $1 WHERE id = $2', [data.name, id]);  await redis.del(`user:${id}`); // invalidate on write}

Cache Stampede Prevention

Prevent thousands of concurrent requests from all missing the cache and hammering the DB at once.

typescript
async function getUserWithLock(id: string): Promise<User> {  const cacheKey = `user:${id}`;  const cached = await redis.get(cacheKey);  if (cached) return JSON.parse(cached);  const lockKey = `lock:${cacheKey}`;  const gotLock = await redis.set(lockKey, '1', 'NX', 'EX', 5);  if (!gotLock) {    // Another request is already refilling the cache; wait briefly and retry    await sleep(50);    return getUserWithLock(id);  }  try {    const user = await db.query('SELECT * FROM users WHERE id = $1', [id]);    await redis.set(cacheKey, JSON.stringify(user), 'EX', 300);    return user;  } finally {    await redis.del(lockKey);  }}

Write-Through & Tag-Based Invalidation

Keep cache consistent on writes, and invalidate related keys via tags.

typescript
// Write-through: update cache and DB together, in the same requestasync function writeThroughUpdate(id: string, data: Partial<User>) {  const updated = await db.query(    'UPDATE users SET name = $1 WHERE id = $2 RETURNING *', [data.name, id]);  await redis.set(`user:${id}`, JSON.stringify(updated), 'EX', 300);  return updated;}// Tag-based invalidation using a set of keys per tagasync function cacheWithTag(key: string, tag: string, value: string, ttl: number) {  await redis.set(key, value, 'EX', ttl);  await redis.sadd(`tag:${tag}`, key);}async function invalidateTag(tag: string) {  const keys = await redis.smembers(`tag:${tag}`);  if (keys.length) await redis.del(...keys);  await redis.del(`tag:${tag}`);}

Strategy Comparison

Which caching pattern fits which access profile.

  • Cache-aside- app manages cache explicitly on read miss; simplest, most common, cache can drift briefly stale
  • Write-through- cache updated synchronously with every write; always consistent, adds write latency
  • Write-behind (write-back)- writes go to cache first, flushed to DB asynchronously; fast writes, risk of data loss on crash
  • Read-through- cache library itself fetches from DB on miss, transparent to the app
  • TTL-based expiry- simplest invalidation strategy; balance staleness tolerance against cache hit rate
  • Cache stampede / dogpile- many requests missing simultaneously on a hot key's expiry; mitigate with locks or early refresh
Pro Tip

Add small random jitter to TTLs (e.g. `300 + random(0,30)` seconds) instead of a fixed value — when you cache many keys at once with identical TTLs, they all expire in the same instant and recreate the stampede problem you were trying to avoid.

Was this cheat sheet helpful?

Explore Topics

#DatabaseQueryCachingStrategies#DatabaseQueryCachingStrategiesCheatSheet#Database#Intermediate#Cache#Aside#Lazy#Loading#Databases#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet