InterviewHubPRO
Section Overview
Q43

Question 43 of 60

Part 4: In-Memory Caching & Fast Data Stores (Redis) (41 - 50)

72%
Databases & System Design•Part 4: In-Memory Caching & Fast Data Stores (Redis) (41 - 50)

Caching Strategies:

In Simple Words:

  • Cache-Aside (Lazy Loading): App checks cache; if miss, queries DB, populates cache, and returns.
  • Write-Through: App writes to cache; cache synchronously writes to DB.
  • Write-Behind: App writes to cache; cache asynchronously flushes batch writes to DB.
typescript
// Cache-Aside implementation:
async function getUser(id: string): Promise<User> {
  const cached = await redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);

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