Best practice for "finding" sockets when using an adapter #5297
-
Since socket IDs are ephemeral, what would be the best way to find a socket based on my own persistent ID (like user/session ID) when using socket.io with an adapter? I could put the ID on data, call fetchSockets(), then find the ID in that list, but if there are a lot of sockets and this lookup is frequent, it seems like a bad pattern. The other thing I could think of is just creating a room for every user when they connect, labeling these rooms with their ID, then using .in(userID).fetchSockets() to get them fairly efficiently, however I was concerned that bloating the adapter with a large amount of single person rooms could be bad for whatever service the adapter is integrated with. Is this concern unfounded or is there a better solution? I am using the Redis Streams adapter, if it's useful for the answer. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Have same question :) |
Beta Was this translation helpful? Give feedback.
-
Hi!
Yes, that's a good pattern, you can see it for example in our guide with Passport.js: https://socket.io/how-to/use-with-passport#using-the-user-id
The rooms are stored in the memory of the server the client is currently connected to, basically it's two sets (id to rooms and room to ids). See also: https://socket.io/docs/v4/rooms/#implementation-details The adapter based on Redis Streams will only use one single stream, regardless of the number of rooms, so it shouldn't be a concern. In that case, |
Beta Was this translation helpful? Give feedback.
Hi!
Yes, that's a good pattern, you can see it for example in our guide with Passport.js: https://socket.io/how-to/use-with-passport#using-the-user-id
The rooms are stored in the memory of the server the client is currently connected to, basically it's two sets (id to rooms and room to ids).
See also: https://socket.io/docs/v4/rooms/#implementation-details
The adapter based on Redis Streams will only use one single stream, regardless of the number of rooms, so it shouldn't be a concern.
In that case,
io.in(userID).fet…