Using Sockets - best practice

Hi,

I am using Sockets in my application for a few bits of functionality (i.e. real-time search, mobile verification etc).

I am wondering what the best practice is for socket and channel management. At the moment I create a socket in my app.js file and then if a user goes to a page that requires a channel I pass the socket to a function that creates a channel for a particular purpose.

After navigating away I assume the socket and and channels I have created remain active until the session ends (Logout) or session times out.

Should I be managing sockets and channels more closely? Creating and destroying as I go or is it OK to let Phoenix manage them?

Andrew

1 Like

It depends on your front end.

If You use normal templating view, then there is LiveView that might suit your need.

If not, You have an event to clean up when You leave the page.

window.onunload

If You have more complex JS frontend, then there is a chance You will have a frontend router, and changing routes can trigger load or unload of channels.

You can use a lot of channels… I usually have thoses : system, lobby, user:id, room:id etc.

I do prefer to manage channels closely, closing them from frontend when not needed anymore. But if You close the browser tab, the server will anyway detect the change.

1 Like

Thank you.

I am going to PROD in a couple of months so LiveView is out for me at the moment,

Your advice r.e. channels makes sense and I will take that approach. For the socket, from what I see it can just stay open and be managed by Phoenix, essentially like a connection pool. Am I on the right track?

Andrew

I guess so. But You need to manage how the system react to page reload…

To make sure we’re on the same page, the socket is opened when a client connects, and closes when the client disconnects. Triggering a page change disconnects the client, so the socket dies and you need to reconnect it when the next page loads. There isn’t really a “pool” either, at least not in the usual sense of having a fixed set of connections you check individual connections in / out of. Each client generally sets up only 1 socket while they’re connected, and it goes away when the client does.

Thanks Ben.

What started me thinking about it was that I was using an unauthenticated socket to do a mobile phone number verification step. After verification the User is authenticated and forwarded to the site. I wanted to the socket authenticated so that I could assign permissions for authorisation.

To your point, I quickly realised that the socket was created on each page load … so once I had an authenticated user I could then authenticate the socket. It has all become clearer as I moved forward. Thanks

PS: Love GraphQL

1 Like