Node.js › Caching

What is the difference between in-memory caching (like a Map or node-cache) and a distributed cache (like Redis)?

Intermediate

Answer

An in-memory cache lives entirely within a single Node.js process's memory -- extremely fast with no network overhead, but limited to that one process (useless once an application scales to multiple instances) and lost entirely on restart. A distributed cache like Redis runs as a separate shared service that all application instances connect to, providing a single consistent cache shared across every instance, at the cost of network latency per access and an additional piece of infrastructure.
// In-memory: fast, but each of N server instances has its own separate cache
const cache = new Map();

// Distributed: one shared cache across every instance
const redis = require('redis').createClient();
await redis.set(`user:${id}`, JSON.stringify(user), { EX: 3600 });
const cached = await redis.get(`user:${id}`);
Real-world example A service running behind a load balancer with five instances switches from an in-memory Map cache to Redis, since with the in-memory approach a cache-invalidation event on one instance had no way to also clear the stale entry sitting in the other four instances' separate caches.

Common follow-ups: What's a hybrid caching strategy that uses both layers together, and why might that be worth the added complexity?;How does Redis's own memory limit and eviction policy affect what you can safely rely on it for?