Redis Caching for Low-Latency Sessions in a MERN App

Redis Caching for Low-Latency Sessions in a MERN App

When to cache, what to invalidate, and how Redis kept a networking platform fast under concurrent WebSocket traffic.

PITCHERS matches startup founders with technical talent, with live interactions over WebSockets. Hitting MongoDB for the same session and profile data on every event was wasteful. Redis fixed that.

What belongs in Redis

  • Session and presence data that changes often and is read constantly.
  • Expensive read results, such as a computed profile summary.
  • Short-lived counters and rate limits.

What does not belong there: anything you cannot afford to lose. Redis is the fast copy, MongoDB stays the source of truth.

Cache-aside reads

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

  const profile = await Profile.findById(id).lean();
  await redis.set(key, JSON.stringify(profile), { EX: 300 });
  return profile;
}

Invalidate on write

When a profile changes, delete its key right after the database write succeeds. The next read repopulates it. Deleting is safer than updating the cache yourself, because the database stays the only place the value is computed.

Always set a TTL

Even with invalidation, give every key an expiry. If an invalidation is ever missed, stale data heals itself within minutes instead of living forever.

Sessions across servers

Storing sessions in Redis lets any server instance handle any request, which is what makes horizontal scaling and the Socket.io Redis adapter possible.

More on this topic

Photography
3D Models
Development
Illustrations
Fashion
Digital Art
Packaging
Motion
Illustrations
Video Production
Photography
3D Models
Development
Illustrations
Fashion