Facebook Pixel

How do I scale Socket.io with PM2 cluster mode?

Set exec_mode: 'cluster' and instances: 'max' in PM2 ecosystem file. Install the Redis adapter (@socket.io/redis-adapter) so messages broadcast across all cluster workers. Set REDIS_URL in the env config. Without the Redis adapter, messages only reach clients on the same worker.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Socket.io Best Practices and Performance Optimizing Real-Time Node.js

Use WebSocket transport only (transports: ['websocket']), Redis adapter for multi-instance scaling, PM2 cluster mode, limit message size, rate limit events, clean up on disconnect, monitor connections and memory, handle memory leaks, and use acknowledgments for important events.

Use io.engine.clientsCount for total connections, io.sockets.adapter.rooms.size for room count, and process.memoryUsage() for memory. Log periodically with setInterval. Use @socket.io/admin-ui for a visual dashboard. Set up CloudWatch or Datadog for production monitoring.

Periodically clean up stale data: iterate through the online users map and remove entries where the socket no longer exists (io.sockets.sockets.get(socketId) returns undefined). Monitor memory with process.memoryUsage() and restart PM2 workers if memory grows too high (max_memory_restart in ecosystem.config.js).

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.