Blog/Real-time Communication with Socket.io and Redis

Real-time Communication with Socket.io and Redis

Building scalable real-time applications requires more than just WebSockets. When you have multiple server instances, you need a way to share messages between them. Redis Pub/Sub combined with Socket.io solves this elegantly.

Why Redis with Socket.io?

When running multiple Node.js instances behind a load balancer, a user connected to Server A won't receive messages emitted from Server B. Redis acts as a message broker between all instances.

Implementation

import { Server } from 'socket.io'
import { createAdapter } from '@socket.io/redis-adapter'
import { createClient } from 'redis'

const io = new Server(server, {
  cors: { origin: '*' }
})

// Create Redis clients
const pubClient = createClient({ url: 'redis://localhost:6379' })
const subClient = pubClient.duplicate()

await Promise.all([pubClient.connect(), subClient.connect()])

// Use Redis adapter
io.adapter(createAdapter(pubClient, subClient))

io.on('connection', (socket) => {
  console.log('User connected:', socket.id)

  socket.on('join-room', (room) => {
    socket.join(room)
  })

  socket.on('message', (data) => {
    // This will work across all server instances!
    io.to(data.room).emit('message', data)
  })
})

Key Benefits

- Messages are shared across all server instances - Horizontal scaling becomes straightforward - Redis handles the pub/sub complexity for you - Works seamlessly with existing Socket.io code