Using Socket.IO and Redis Adapter


Using Socket.IO and Redis Adapter

What is Socket.IO and Redis Adapter?

The use of Socket.IO and Redis Adapter is frequently encountered in applications requiring real-time communication on Node.js. Socket.IO is a powerful library that enables bidirectional, low-latency data transmission between servers and clients. To ensure scalability in multiple Node.js processes (e.g., on multiple servers), Redis Adapter is used. Thanks to Redis, room and user management between Socket.IO servers is synchronized, which allows seamless implementation of horizontal scalability scenarios.

How to Install Socket.IO and Redis Adapter?

The basic steps to use Socket.IO in a multi-server environment with Redis Adapter consist of installing the required packages and making the appropriate configurations. In the installation scenario below, we will integrate the Redis adapter into a Socket.IO server. Let's assume your Redis server is also active.

npm install socket.io socket.io-redis redis

After installation, the following structure is applied on the server side to use the Redis Adapter in Socket.IO:

const { createServer } = require('http');
const { Server } = require('socket.io');
const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('redis');

const httpServer = createServer();
const io = new Server(httpServer);

(async () => {
  const pubClient = createClient({ url: 'redis://localhost:6379' });
  const subClient = pubClient.duplicate();

  await pubClient.connect();
  await subClient.connect();

  io.adapter(createAdapter(pubClient, subClient));

  io.on('connection', (socket) => {
    console.log('User connected:', socket.id);
    socket.on('message', (data) => {
      socket.broadcast.emit('message', data);
    });
  });

  httpServer.listen(3000, () => {
    console.log('Server started on port 3000');
  });
})();

Advantages of Using Socket.IO and Redis Adapter

The use of Socket.IO and Redis Adapter offers significant advantages in terms of performance, reliability, and scalability in real-time web applications. Thanks to the Redis Adapter, multiple Socket.IO servers can communicate with each other, and messages or events in all rooms reach every server completely. For projects such as messaging applications, instant notification systems, or live scoreboards, this structure is essential for seamless operation with high user numbers.

In conclusion, using Socket.IO and Redis Adapter is one of the best solutions for those who want to develop high-traffic, flexible, and consistent real-time applications through horizontal scaling. By preferring this architecture in your development process, you can both increase your application's capacity and make its maintenance easier.