I'm using the NodeJS ws library to build an app. Currently I am using an object to store instances of users' websocket connections with a unique user ID as the key. Pseudo-code:
let userWebSockets = {
'user-guid-here': WSConnection
};
This works fine and when I need to target a specific user to send a message back to I can grab their connection from the userWebSockets object thusly let ws = userWebSockets['user-guid-here'].
The problem is, if I cluster Node processes on the box I am running, fork a master process with the cluster module, or cluster the boxes, then there is no guarantee that the same userWebSockets object will be in memory, and when I try to look up a user's connection based on their unique identifier, I risk getting undefined as the return value from the lookup.
My first inclination was to use some remote k => v store like Redis to handle maintaining the dictionary, however I realized in my implementation attempt that Redis obviously isn't going to store a Javascript object and the best I could do with such a technology was serialize the object in a way that it could later be reconstituted/deserialized. I tried using Crockford's cycle.js from the following repository: https://github.com/douglascrockford/JSON-js/blob/master/cycle.js This was unsuccessful as I found that prototype methods of the object I was trying to bring back to life were not preserved (ws.send() in this case, for example).
My current workaround is to use nginx to balance to an upstream pool of instances and use the ip_hash directive to make the user ip => instance sticky, however I'm not satisfied with this solution.
Has anybody had any luck with what I'm trying to do here? I'm also open to re-architecting the app if there is a better or more idiomatic way to handle user => ws connection associations.