Manage Swift Vapor WebSocket Clients with Redis

Hi. I’m trying to manage a collection of WebSocket connections to my server so that I can notify them all when users connect/disconnect/send messages. I can do this with a simple struct like this

struct IdentifiedWebSocket: Identifiable {
    var id: UUID = UUID()
    var websocket: WebSocket
}

and a dictionary of collections like this

static var chatClients: [GroupID: [IdentifiedWebSocket]] = [:]

As the book mentioned here that this is not scalable, I’ve been looking into Redis. So I set up Redis, but I’m at a loss on how to encode the pertinent WebSocket information. I’m new to WebSockets and I’m going to continue to read the source code and docs, but I was wondering if there were any good tips for what I need to store so that I can encode to and decode the collection of groups of clients from Redis.

Or if there is a different approach entirely I should take, I’m open to that as well. Thank you in advance!

So the complicated part is that you don’t encode the web socket information as you can’t share WebSocket connections across machines. What you need to share is any data and then distribute it to that apps connections. So for instance, if you take your chat app, you’ll need to store some sort out data about the Websocket, such as the user ID. Then in your Redis pub/sub stuff, when a message is sent to a user, you publish the message (with it’s associated information) to the subscription and then the subscribers (all the other severs) will receive that data, see if they need to do anything with it and if so, send it to the websockets that need it.

Does that makes sense?

1 Like