Run and test WebSockets¶
This page shows how to run WebSockets safely in production and how to test your channels. You tune the limits that protect each process, run WebSocket connections in their own process if you need to, monitor events, and write channel specs. For every setting, see Provider settings in the reference.
Tune the limits¶
The provider settings limit what one client can use. The following table lists the limits and what happens when a client exceeds them:
| Setting | Default | Limits | When exceeded |
|---|---|---|---|
max_frame_size |
65_536 |
Size of one inbound frame, in bytes | Close code 1009 |
max_payload_size |
60_000 |
Size of a broadcast or of subscribed data, in bytes of JSON |
Failure(:too_large), or rejected("internal") |
max_subscriptions |
100 |
Subscriptions on one connection | Close code 4429 |
max_buffered_bytes |
1_048_576 |
Unsent bytes for one connection | Close code 4008 |
max_connections_per_identity |
20 |
Connections for one identity key in one process | Close code 4430 |
hello_timeout |
10 |
Seconds to send hello after connecting |
Close code 4408 |
heartbeat_interval |
15 |
Seconds between server pings | Close code 4000 after twice this time without traffic |
executor_threads |
4 |
Threads that run the authenticator and channel code | Work waits in a queue |
Each process enforces max_connections_per_identity separately, so behind a load balancer one
identity can hold up to that many connections in every process.
The server also sends a WebSocket ping at each heartbeat, which keeps proxies from closing quiet
connections. If your proxy closes idle connections sooner than heartbeat_interval, lower the
interval or raise the proxy's timeout.
If the endpoint refuses to upgrade a request, it returns HTTP 426, 403, 400, or 501. For the causes, see Handshake responses.
Run WebSockets in a separate process¶
By default, WebSocket connections run in your web process. To give them their own process, complete the following steps:
-
Set up the SQL backend, so that broadcasts from the web process and from job workers reach the new process. See Broadcast across processes.
-
Start a second Puma process with the same
config.ru:This process runs the full middleware stack, so session authentication keeps working.
-
Configure your proxy to route the endpoint's path, such as
/sockets, to that process. Forward theUpgradeandConnectionheaders.
If you authenticate with tokens only, the second process can serve the endpoint without the rest of the app. To do so, create a separate Rackup file:
Then start Puma with that file:
sockets.ru skips the app's middleware, so request.session is empty in the authenticator.
Monitor events¶
Mankai publishes events for connections, subscriptions, actions, broadcasts, and errors on your
app's notifications bus. The provider registers the events when it starts, so subscribe in an
after(:start) hook. The following example logs the outcome of every action:
# config/providers/sockets.rb
Hanami.app.register_provider(:sockets, namespace: true, from: :mankai_sockets, source: :sockets) do
configure do |config|
# ...
end
after(:start) do
target["notifications"].subscribe(:"mankai.sockets.action") do |event|
target["logger"].info("socket action #{event[:channel]}.#{event[:action]}: #{event[:outcome]}")
end
end
end
In production, watch at least mankai.sockets.error, mankai.sockets.reject, and
mankai.sockets.disconnect. For every event and its payload, see
Events.
Test a channel¶
Because channels are components, a spec can build one with test dependencies and call subscribe
and receive directly. Use RecordingBroadcaster in place of the real broadcaster: it records
broadcasts instead of sending them.
The following spec tests the chat channel and its PostMessage operation from
Build channels and broadcast:
# spec/channels/chat_spec.rb
require "mankai/sockets/testing"
RSpec.describe Bookshelf::Channels::Chat do
include Mankai::Sockets::Testing::Channels
include Mankai::Sockets::Testing::Matchers
subject(:channel) { described_class.new(post_message: post_message) }
let(:broadcaster) { Mankai::Sockets::Testing::RecordingBroadcaster.new }
let(:post_message) { Bookshelf::Operations::PostMessage.new(broadcaster: broadcaster) }
let(:subscription) do
subscription_for(params: {room: 1}, identity: Mankai::Sockets::Identity.new(key: "user:7", value: "7"))
end
it "listens to the room's stream" do
result = channel.subscribe(subscription)
expect(result.value![:streams]).to eq([Mankai::Sockets::Stream.of("chat", 1)])
end
it "broadcasts what was said" do
result = channel.receive(subscription, message("speak", body: "hi"))
expect(result).to be_success
expect(broadcaster).to have_broadcast(
Mankai::Sockets::Stream.of("chat", 1), a_hash_including(body: "hi", user_id: "7")
)
end
it "fails on an empty message" do
result = channel.receive(subscription, message("speak", body: " "))
expect(result).to be_failure
expect(broadcaster.broadcasts).to be_empty
end
end
subscription_for and message build a channel's inputs, and have_broadcast matches a recorded
broadcast. For Minitest, use assert_broadcast. For every helper, see
Testing in the reference.
Use the memory backend in tests¶
In the test environment, use the memory backend so that specs don't need the messages table or a polling thread:
# config/providers/sockets.rb
config.backend = Hanami.env?(:test) ? :memory : Mankai::Sockets::SQL.backend(gateway: "db.gateway")
If you write your own backend, check it against the shared examples in
mankai/sockets/testing/backend_examples. For the contract, see
Backend contract.
Production checklist¶
Before you go to production, check the following:
- Every private connection is authenticated.
allow_anonymousis off for private data. - Sessions are enabled, or tokens are set up, for whatever your authenticator reads.
allowed_originslists the exact origins that you serve.- You've decided whether WebSocket connections run in the web process or a separate one.
- The SQL backend is in use if more than one process serves connections or broadcasts.
- The database pool has at least
executor_threadsplus one connections. - The limits fit your payload sizes and connection counts.
- The proxy terminates TLS and forwards the
UpgradeandConnectionheaders. mankai.sockets.error,mankai.sockets.reject, andmankai.sockets.disconnectevents are monitored.