socket.io-redis-adapter icon indicating copy to clipboard operation
socket.io-redis-adapter copied to clipboard

Does socket.io-redis still suffer the problems mentioned in the linked article?

Open ismail-khan opened this issue 9 years ago • 12 comments

I just read this somewhat old article: Cluster f***s when scaling Socket.IO

Here are the parts that worry me:

  1. Apparently socket.io-redis saves connection data in each node separately, and not in Redis:

All this data will be synced through pub/sub to every connected Socket.IO server. So if you have 2 node process and they both use Socket.IO stores they will both have all the data of all connections in their own process memory.

  1. It's not so simple to add a node, since we need to bring all processes/server online at the same time (I'm on Heroku and would like to scale up/down regularly/flexibly, so this is worrying!):

But storing data isn’t the only problem. Usually when you want to scale out you just want to be able to add new servers without taking your whole cluster down. This is impossible with Socket.IO. When you add a new server you need take your whole cluster down because the synced data is not stored in a general location. It’s only stored in the process’s heap, and when you join the cluster it doesn’t ask the other node processes for the old data so it’s a completely blank and empty server and can therefor not accept them and will close the connection with a “unknown handshake” error. The only way to combat this is to take your whole cluster down. Add new node processes/servers, bring them all online at the same time and start accepting connections again.

  1. Every connection creates 5 different channels!

For every connection that is established the store will subscribe to 5 different channels. So if you have 10000 concurrent connections you will also have 50000 subscriptions to your redis server which causes redis to use a magnitude more CPU than if it would just use single or a couple of channels to communicate over for ever connection.

If this has been solved, then I'd like to use socket.io-redis + socket.io-emitter to horizontally scale my app. If not, then I'll just have to implement a custom solution on top of redis.

ismail-khan avatar Mar 28 '17 14:03 ismail-khan

If possible, it would be nice to get a brief overview of how socket.io-redis works under the hood (or a reference to documentation). I'm concerned about how it will scale, especially after reading the article I linked!

ismail-khan avatar Mar 28 '17 18:03 ismail-khan

If I'm not mistaken, the article you linked to refers to socket.io 0.9.x, which dates quite a bit and there was a major rewrite for version 1.0, so most of the points are out of date now.

If possible, it would be nice to get a brief overview of how socket.io-redis works under the hood

The Redis adapter extends the default adapter, which stores the associations ids <-> rooms. It is based on a couple of hash objects, sids and rooms.

this.sids = {};
this.rooms = {};
// when a socket joins a room, the objects are updated
this.sids[socketid][room] = true;
this.rooms[room][socketid] = true;

// those associations are then used when broadcasting
io.emit('event')
// foreach socket in this.sids
// => send the packet to each socket

io.to('myroom').emit('event') 
// foreach socket in this.sids['myroom']
// => send the packet to each socket in the room

The Redis adapter adds an additional step (source):

io.emit('event')
// foreach socket in this.sids
// => send the packet to each socket
// AND emit to other nodes, which have subscribed to the message channel (through the redis pub/sub mechanism)
// once a node receive a new message, it loops through its own sids and send the packet if needed

Apparently socket.io-redis saves connection data in each node separately, and not in Redis.

Yes, that's right. Each node stores the associations ids <-> rooms of the clients it talks to. "all the data of all connections" is a bit misleading here though.

It's not so simple to add a node, since we need to bring all processes/server online at the same time

That doesn't apply anymore.

Every connection creates 5 different channels!

By default, the adapter subscribes to 3 channels (message, request and response) (source). Also, every time a room is created, a new subscription is made (source) so since a socket joins its own room every new connection will indeed create a new channel. That behaviour can be disabled though by setting the withChannelMultiplexing option to false. Enabling the multiplexing depends on your application. I'd say:

  • lots of clients, few rooms: withChannelMultiplexing to false
  • few clients, lots of messages spread across rooms: withChannelMultiplexing to true

darrachequesne avatar Mar 28 '17 20:03 darrachequesne

Hi @darrachequesne, thanks for taking the time to write that -- super helpful!

Just so I'm clear, are all the following statements true?

  1. Each node only saves connection data for the clients that are connected to that node. To figure out if a client is connected to ANY node in our cluster, we must use one of the socket.io-redis functions.

  2. If I have N nodes, and K clients (== end-users) subscribed to my cluster with withChannelMultiplexing set to false, then I should have 3N + K channels subscribed to Redis.

  3. Socket IDs are guaranteed to be unique across the entire cluster, assuming every node uses socket.io-redis.

  4. If I need to emit a message to a specific client that is connected via socket.io, but the client is connected to another, separate node, then I should use socket.io-emitter. This will only publish the message to the node that is connected to the specific client (as opposed to publishing the message to every node, which then checks if it is connected to the client).

Lastly, suppose I have lots clients subscribed to one room each (their own socket-ids), such that the client:room ratio is nearly 1:1. In that case would setting withChannelMultiplexing to true be a good option? I'm not sure what the tradeoff is -- it seems like limiting the number of channels is always a good thing, unless each channel has a "buffer".

ismail-khan avatar Mar 29 '17 03:03 ismail-khan

Each node only saves connection data for the clients that are connected to that node. To figure out if a client is connected to ANY node in our cluster, we must use one of the socket.io-redis functions.

Yes, that's right.

If I have N nodes, and K clients (== end-users) subscribed to my cluster with withChannelMultiplexing set to false, then I should have 3N + K channels subscribed to Redis.

withChannelMultiplexing to true: (3 + K) different channels, the first 3 being subscribed to N times (once per node) and the others only on a given node

withChannelMultiplexing to false: 3 different channels, being subscribed to N times

The channel multiplexing was introduced here: https://github.com/socketio/socket.io-redis/pull/46

Socket IDs are guaranteed to be unique across the entire cluster, assuming every node uses socket.io-redis.

Thet ID generation does not depend on socket.io-redis. The IDs are generated here: https://github.com/socketio/engine.io/blob/2.1.1/lib/server.js#L281

The base64id package uses crypto.randomBytes to generate those IDs (source), hence the unicity.

If I need to emit a message to a specific client that is connected via socket.io, but the client is connected to another, separate node, then I should use socket.io-emitter. This will only publish the message to the node that is connected to the specific client (as opposed to publishing the message to every node, which then checks if it is connected to the client).

socket.io-emitter should be used when you want to emit from a non-socket.io process (a batch, for example). Else, socket.io-redis should be enough:

server1 (with socket.io-redis)
server2 (with socket.io-redis) with one client: socket1

server1.to(socket1.id).emit('event');
// foreach socket in (server1) this.rooms[<socket1.id>]
// => nobody
// AND emit to other nodes
// once server2 receive the message, it loops through its own sids and sends the packet

In that case, with withChannelMultiplexing to true, server1 will publish the packet to socket.io#<socket1.id> channel, so only server2 will receive it. With withChannelMultiplexing to false, server1 will publish the packet to socket.io channel, so every node will receive it and decode it. That's where it depends on your application.

darrachequesne avatar Mar 29 '17 05:03 darrachequesne

socket.io-emitter should be used when you want to emit from a non-socket.io process (a batch, for example). Else, socket.io-redis should be enough:

Ah, so once the adapter is defined, we don't need to do anything different to send messages to a specfic socket? That's great!

At a broader level, I'm unsure as to why socket.io-redis works the way it does for emitting to a specific client: either we have 1 Redis channel per Socket.io connection (withChannelMultiplexing == false), or we broadcast messages to all nodes (withChannelMultiplexing == true).

Why not instead keep a map of socketId->serverId in Redis. When we want to emit a message to a socketId from server A, we first look up the serverId mapped to the room (suppose this is server B). Every server is subscribed on a unique channel (something like "sub#serverId"). Server A can thus easily figure out that Server B is connected to a given socketId, publish a message via Redis to Server B's special "subscribe" channel, and Server B can then emit the Socket.io message to the socket.

Basically it seems to me that it is possible to maintain channel multiplexing but also avoid creating lots and lots of Redis channels.

ismail-khan avatar Mar 29 '17 09:03 ismail-khan

Well, that's an interesting idea. If I understand correctly:

key _all => server1, server2 // keep track of each server (to broadcast)
// a new socket connects
key socketid1 => server1
key socketid2 => server2
// socket1.join('room1')
key room1 => server1
// socket2.join('room1')
key room1 => server1, server2

How do you handle key removal (in case a server gets disconnected)?

darrachequesne avatar Mar 29 '17 22:03 darrachequesne

Instead of saving the server name, we could instead save a custom instance ID -- some combo of server name + process ID + timestamp.

Suppose we would like to push a message to socket1. This is already saved in redis as socket1 => some-instance-id (with an expiration time). We retrieve the instance ID from Redis, and check if anyone is subscribed to a channel called "sub#some-instance-id". If yes, then we go ahead and publish a message on that channel. If no, then we do whatever the current behavior is for sending a message to an empty room (my guess is nothing at all?)

The key here is that the instance ID represents an "instance" of the server, as opposed to a server itself. So when a server goes down, it's old instance ID becomes obsolete because the restarted server is now subscribed to an entirely different channel than before.

The only problems I see are (a) an extra check to determine if a given instance-id is valid, and (b) some extra data pointing to defunct instance IDs will be stored in Redis (I don't mind such data sitting around with a 1 day expiration, but maybe that's a problem for general users...).

Btw, is there a way to check if a specific socket is connected on another server? Or do we have to keep track of that ourselves?

ismail-khan avatar Apr 24 '17 13:04 ismail-khan

@ismail-khan

Btw, is there a way to check if a specific socket is connected on another server? Or do we have to keep track of that ourselves?

I keep track of all connected users across every server by creating a set in Redis called 'connected-users' that a user's id is added to when they first connect through socket.io. When they disconnect from socket.io I immediately remove their user id from the 'connected-users' set. I query this Redis set directly when I need to know if a user is currently connected.

To create and use that Redis set, I simply create a new Redis client separate from the one's used with the socket.io adapter, though that probably isn't necessary.

Another interesting thing I have done is created 2 Redis ordered sets called 'connected-hour' and 'connected-day' that tracks which users have been active in the last hour and 24 hours respectively. The connecting user also has their user id with an attached 'score' (just the timestamp of when they connected) added to these ordered sets. I then have a setInterval running every 60 seconds that removes all user ids from those sets if their attached timestamp doesn't fall within the range of an hour ago to now, or 24 hours ago to now. Before removing the user ids that are out of range, I get the list of all connected users from the original 'connected-users' set, and update their scores in the 'connected-hour' and 'connected-day' ordered sets with the current timestamp. This makes sure a user that connected and has been active more than an hour or day ago is still represented in the 'connected-hour' and 'connected-day' ordered sets.

SamDelgado avatar May 10 '17 19:05 SamDelgado

@SamDelgado Can you please share you sample code?

tayyab-sarwar avatar Feb 25 '19 11:02 tayyab-sarwar

For future readers, here's my updated answer (based on the one above from 2017)

TL;DR: the only difference is that the withChannelMultiplexing option was removed

Apparently socket.io-redis saves connection data in each node separately, and not in Redis.

Yes, that's right. Each node stores the associations ids <-> rooms of the clients it talks to.

It's not so simple to add a node, since we need to bring all processes/server online at the same time

That doesn't apply anymore. Adding/removing a node can be done at any time, with no particular action.

Every connection creates 5 different channels!

This isn't true anymore. There's only 3 channels (message, request and response) in any cases.

darrachequesne avatar Nov 14 '20 02:11 darrachequesne

Hi @darrachequesne , thanks for the thread, I learned a lot about the internals of socketio-redis pub-sub here. But your last reply left me in confusion. You said withChannelMultiplexing is now obsolete, but is there any replacement mechanism you guyz are using now?

  1. If I send a message to a room or channel,(via emitter or from client) it will definitely poke all the servers in cluster, so that every instance can send that message to all the users in the channel/room.
  2. But what If I'm sending to a particular user? In that case will redis publish the message to every instance in cluster? If true then all the instance will run a for loop for every one-2-one message event, though the user is only connected to one instance.
  3. Why "withChannelMultiplexing" was removed? Issue 41, which was causing CPU spike, is addressed now in the recent releases? If yes, can you please summery how it works now? Or any extensive documentation how these things work internally? Thanks in advance.

benzamin avatar Jul 07 '23 15:07 benzamin

@benzamin there is a new adapter based on Redis sharded PUB/SUB (requires Redis v7), added in version 8.2.0:

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

const pubClient = createClient({ host: 'localhost', port: 6379 });
const subClient = pubClient.duplicate();

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

const io = new Server({
  adapter: createShardedAdapter(pubClient, subClient)
});

io.listen(3000);

You have two subscription modes:

  • "static": 2 Redis channels per namespace

Useful when used with dynamic namespaces.

  • "dynamic": (2 + 1 per public room) Redis channels per namespace

The default value, useful when some rooms have a low number of clients (so only a few Socket.IO servers are notified).

I will update the documentation to highlight it.

darrachequesne avatar Aug 11 '23 11:08 darrachequesne