Node.js › Clustering & Worker Threads

What happens to in-memory state (like an in-memory cache) when using the Node.js cluster module, and how do you handle this correctly?

Advanced

Answer

Each cluster worker is a separate OS process with its own memory -- an in-memory cache exists separately and inconsistently in each worker. The fix is moving shared state to an external store like Redis, accessible consistently regardless of which worker handles a given request.
// Broken with clustering: each worker has its own separate cache
const cache = new Map();

// Correct: external shared store
await redis.set(key, value);
Real-world example A team clustering across four cores noticed roughly 1 in 4 requests seemed to miss recently cached data, traced to an in-memory Map existing separately in each worker; moving to Redis resolved it.

Common follow-ups: What's the correct way to implement rate limiting correctly across cluster workers given this same issue?;How does this apply to WebSocket connections handled by a specific worker?