Server-Side Caching

Redis, Memcached, and application-level caching.

Redis Caching

Basic set/get
SET key value
GET key

With expiration (TTL)
SETEX key 3600 value // 1 hour
SET key value EX 3600

Check if exists
EXISTS key

Delete key
DEL key

Node.js Redis Example

Cache middleware
const redis = require(redis);
const client = redis.createClient();

async function cacheMiddleware(req, res, next) {
  const key = req.url;
  const cached = await client.get(key);
  
  if (cached) {
    return res.json(JSON.parse(cached));
  }
  
  res.sendResponse = res.json;
  res.json = (body) => {
    client.setex(key, 3600, JSON.stringify(body));
    res.sendResponse(body);
  };
  next();
}

Cache Strategies

Cache-Aside (Lazy Loading)
1. Check cache
2. If miss, load from DB
3. Store in cache
4. Return data

Write-Through
Write to cache and DB simultaneously

Write-Behind
Write to cache first, DB async later

Read-Through
Cache automatically loads from DB on miss

Cache Invalidation

Time-based (TTL)
Expires after fixed time

Event-based
Invalidate on data update/delete

Pattern-based deletion
KEYS user:*
DEL user:123 user:456

Cache warming
Pre-populate cache with frequent data