Phoenix Channels: A Quick Overview

Phoenix is a modern web framework for the functional programming language Elixir. Phoenix comes shipped with something called Phoenix Channels, a feature of Phoenix that allows for soft real-time communication out of the box.

Channels can be used for:

  • Chat rooms and APIs for messaging apps
  • “Breaking” news (like emergencies or sports info.)
  • Events in games
  • Much more!

Channels may seem intimidating but I hope to demystify whats going on behind the scenes for you!

The structure of a channel is quite simple. At a very high level, channels enable clients to connect to a web server and subscribe to various “topics.” A client then sends and receives messages over its subscribed topics. A client can subscribe to as many topics desired on a single connection, which reduces expensive connections! Awesome! Channels are also transport agnostic which means that two systems, one using long-polling and one using WebSockets, can utilize the same logic. Let’s break it down a little more in depth!

Source: Real-Time Phoenix by Stephen Bussy (pg. 97)

The client will begin by connecting to a socket via one of two transport mechanisms: WebSockets or long polling. Once the client has connected to the socket, it uses that network connection to join a channel. That connection is represented by a Phoenix.Channel.Server process PID.

When a client successfully establishes this connection, Phoenix Channels initializes an instance of %Phoenix.Socket{}. The channel server will then retain awareness of this socket instance and maintains state within that instance.

Once a client is connected to a channel, the client will start sending and receiving messages up and down the channel. If the client sends a message, the channel will send this message to the local PubSub server for the specified topic the client is subscribing to. This channel server process in turn sends the message to any clients connected to the same channel topic on the same server. Then the PubSub server forwards the message to any remote PubSub servers running on other nodes in the node cluster. These nodes then send the message to their own subscribed clients. This allows for real time application data to be sent between different servers of a distributed system.

From the Phoenix Channels docs:

The power this offers is incredible! It gives smaller companies the capabilities to manage large user traffic with less hardware.

If your next project will rely heavily on real-time data, consider using Elixir and Phoenix for a highly scalable, highly fault tolerant solution!

Credits: Real-Time Phoenix by Stephen Bussy

Full-Stack Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store