Daniel Profile picture
Life long learner. #algorithms #Database #Elixir #Rust

Aug 20, 2021, 10 tweets

The WebSocket architecture of @elixirphoenix
#myelixirstatus

1. The endpoint will start several children, we only focus on server and socket here:

* socket children

pool supervisor + a bunch of dynamic supervisors which will eventually start channel servers

the number of dynamic supervisors is the number of CPU cores of your server

* server children

The ranch listener supervisor will start a connection supervisor and an acceptor supervisor.

The acceptors will handle connection creation requests.

A cowboy server process is created after a connection is accepted.

2. Socket creation

After getting an HTTP request with a socket upgrade, the cowboy server process will start to initiate middlewares.

The Phoenix cowboy handler is one of the middlewares.

WebSocket protocol flow:

3. After initialization, protocol switch happens, WebSocket protocol will takeover.

It can start to handle TCP messages from clients and Erlang messages from the Phoenix channel servers.

* The websocket_handle callback will be called when clients send messages to the socket.

If there's no related Phoenix channel server, a server process will be started under the dynamic supervisor.

* The websocket_info will be called if the channel sends messages to the socket process.

4. Broadcast

when a channel server is spawned, the PID is registered under the full topic name in the registry.

If you broadcast a message to a topic, all the pids are retrieved from the registry, and messages will be sent out to either the channel process or socket process.

5. Your turn

Now it's time to read more codes and do some experiments. Happy building!

A retweet to the first tweet would be greatly appreciated. 💌

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling