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?
AdvancedAnswer
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.