How WebSockets work¶
A WebSocket connection is a long-lived connection between the browser and the server. Either side can send a message at any time, so the server can push a change without waiting for the browser to ask. This page explains the parts of Mankai's WebSockets feature, how a connection and a broadcast move through them, and the design choices behind them. It's for Hanami developers who want to understand the model before they build with it.
To set up WebSockets in an app, follow Add your first WebSocket channel.
When to use WebSockets¶
Use WebSockets when the server must push updates to the browser with low latency, for example:
- Chat and presence.
- Notifications.
- Live dashboards and counters.
- Collaborative editing.
Don't use them when a periodic request is enough, or when the update can wait for the next page load. WebSockets add operational work: long-lived connections, authentication, origin checks, and a process model to run.
The parts¶
The following diagram shows how a browser subscribes and how a message from your code reaches it:
browser ──connect──► sockets.endpoint ──► channel
│
subscription
│
server ──broadcaster──► stream ────────────┘──► every subscribed browser
A browser connects to the endpoint and subscribes to a channel. The channel attaches the subscription to one or more streams. When server code broadcasts to a stream, every subscription on that stream receives the message.
The following terms describe the parts. The rest of the WebSockets docs use them as defined here:
- Endpoint
- The Rack app,
sockets.endpoint, that accepts WebSocket connections. You mount it inconfig/routes.rb. It runs inside your app's middleware stack, so sessions, logging, and security middleware apply to the upgrade request: the plain HTTP request that asks the server to switch to the WebSocket protocol. - Rack full hijack
- The Rack feature that lets the endpoint take over the client's TCP socket from the web server. Puma supports it.
- Identity
- The user or client that owns a connection, as returned by your authenticator. Its identity
key, such as
user:42, groups one person's connections. - Channel
- A container component that accepts or rejects subscriptions and handles actions from the browser. A channel is stateless: it keeps nothing between calls, and per-connection data lives in the subscription.
- Subscription
- One connection's membership in a channel, with validated params.
- Action
- A named request from the browser to a channel, such as
speak. The browser sends it withperform, and the channel handles it inreceive. - Stream
- A named destination for broadcasts, such as
chat:42. The channel chooses a subscription's streams; the browser never does. - Broadcast
- A JSON message that your code sends to a stream. Every subscription on that stream receives it.
- Backend
- The component that carries broadcasts from the broadcaster to the connections that listen to a stream. The backend decides whether a broadcast can leave the process.
Connection lifecycle¶
A connection goes through the following stages:
open ──► hello ──► authenticate ──► subscribe ──► messages ──► close
│ │ │
│ └─ reject └─ rejected
└─ hello timeout
- The browser opens a connection to the endpoint. The endpoint checks the
Originheader and refuses pages that aren't inallowed_origins. - The browser client sends a
helloframe, with a token if it has one. If nohelloarrives withinhello_timeout, the server closes the connection. - The server calls your authenticator, which returns an identity or rejects the connection.
- The browser subscribes to channels. Each channel's
subscribemethod accepts or rejects the subscription and chooses its streams. - The browser sends actions, and the server sends broadcasts from the subscribed streams. Both sides exchange heartbeat pings to keep the connection alive.
- The connection closes. Each channel's
unsubscribemethod runs for the subscriptions that were open.
If the connection drops, the browser client reconnects after a random, growing delay, and re-sends its subscriptions, except the rejected ones. It doesn't reconnect after an authentication failure (close code 4401), an invalid frame (4400), or a limit that the next attempt would hit again (4429 and 4430). For every frame and close code, see the mankai-sockets protocol.
Threads and blocking work¶
The server keeps every connection on one background thread that waits for network activity, so an
idle connection costs no thread. Your authenticator and channel methods run on a small pool of
executor threads, sized by the executor_threads setting, and each connection handles one frame at
a time. Keep channel methods short. Put slow work in an operation or a background job, and
broadcast the result when it's ready.
The server starts its threads only when a process accepts its first WebSocket connection. A process that only broadcasts, such as a job worker, starts no WebSocket threads.
Broadcasts and backends¶
A broadcast goes through the backend, so the backend decides which connections it can reach. Mankai has two backends:
| Backend | A broadcast reaches | Use it for |
|---|---|---|
Memory backend (:memory) |
Connections in the same process | Development, tests, and apps with one Puma process |
| SQL backend (mankai-sockets-sql) | Connections in every process that uses the database | Several Puma workers or servers, a separate WebSocket process, or broadcasts from jobs |
The memory backend delivers a broadcast immediately, on the caller's thread. A job that runs in a worker process uses its own memory backend, so its broadcasts reach nobody.
The SQL backend stores each broadcast as a row in a table. In each process that serves WebSocket connections, a listener thread polls the table and delivers new rows for the streams that its connections watch. Because the insert runs on the app's connection, a broadcast inside a transaction rolls back with it. Delivery is at most once: a process never replays rows that were published before it watched a stream. For setup, see Broadcast across processes.
Design choices¶
Mankai makes the following choices on purpose:
- Channels choose the audience when they accept a subscription. Mankai has no per-delivery filter, because running app code for every recipient of every broadcast would hide work and make code reloading unsafe. To send different messages to different people, give them different streams. For an example, see Build channels and broadcast.
- Failure reasons stay on the server. The browser gets only
invalid,unauthorized, orinternal, so a rejection can't leak details of your app. The details go to your logs and events. - Every reachable channel is listed in the configuration. The browser can reach only the
channels in
config.channels, and the provider checks each one at boot. - Origins are checked explicitly.
allowed_originsis required and has no "allow all" value, because a browser sends cookies with a WebSocket connection from any site.