Sockets or Channels? An architecture decision in Phoenix

The modern web framework Phoenix allows us easily build and deploy soft real time applications. Phoenix does this through two modules, Phoenix.Socket and Phoenix.Channel.

Phoenix Sockets are the point of connection to your application. They serve as an access point for client subscriptions. They can also be utilized by other server instances as a method of communication between nodes on a server cluster. You define channels within a socket, allowing for clients/servers to subscribe to certain topics of their choosing.

Sockets and channels have different performance costs associated with them. In Phoenix, each separate socket is considered an independent connection to the server. Sockets must maintain a bi directional connection and therefore also come with networking costs. Channels on the other hand are “free”. Processes in Elixir are very lightweight, backed by the wonderful OTP framework. Although they do use CPU and memory, the cost is very insignificant when compared to the costs of a socket. Therefore, we can assume that an added channel to the application costs very little/nothing at all. Because of these differences, having an idle socket connection can be considered expensive. It needs to maintain the “heartbeat” connection even if it is not being utilized. It would be much cheaper to have an architecture of having one socket and many channels versus having many sockets each with one channel.

Optimized socket architecture

There are circumstances where you would want to use multiple sockets. When you need different authentication scopes (like and Admin role), it is extremely beneficial to have a different socket for admins. This will lead to writing less code in the long run as non admin authorized users would not even be able to connect to your socket. Doing this separation of logic at a higher level, instead of managing it within custom channel behavior, can definitely save some headaches.

Overall, utilizing an architecture where different authentication scopes each get their own socket and within these sockets there are many channels that handle different topics, will lead to the greatest performance optimization.

Full-Stack Engineer