WebSockets
Introduction
dust-framework ships with Relay, a local WebSocket server so you can develop realtime features with broadcasting and dust-framework Echo on your machine without running an external service.
For example, while building an order tracking page, you can start Relay alongside your application, dispatch an OrderShipped event from a handler, and watch the update arrive in your browser over a local WebSocket connection.
This server is for local development. When you deploy to production, switch your credentials to managed Relay on DUST Cloud. To learn how to broadcast events, authorize private and presence channels, and subscribe from the browser with Echo, check out the broadcasting guide.
The Pusher protocol
Relay implements the Pusher protocol rather than a raw WebSocket wire format. Because of that, you don't need to build message framing, reconnection handling, or channel routing yourself. dust-framework Echo, pusher-js, and any other Pusher-compatible client library can connect to Relay without custom adapters, and you can move from local relay:start to managed Relay on DUST Cloud by updating only your environment variables.
Rather than passing messages directly between individual sockets, the protocol organizes connections around named channels and client events:
- Public channels let any connected client subscribe without authorization and receive broadcast events, such as deployment notices or live scores.
- Private channels (
private-*) restrict user-specific updates, such as order status changes, to authorized subscribers. In dust-framework, you authorize a private channel with a single callback insrc/routes/channels.rsthat returnstrueorfalse. - Presence channels (
presence-*) build on private channels by tracking which users are currently subscribed. Relay sends each new subscriber the current member list and notifies other subscribers as members join or leave. You authorize a presence channel insrc/routes/channels.rsby returning the member's details, and track who is online with Echo'suseEchoPresencehook. - Cache channels (
cache-*,private-cache-*, andpresence-cache-*) remember the most recent event published to the channel and replay it immediately when a new client subscribes. - Client events (
client-*) let subscribed browsers send messages, such as typing indicators, to other subscribers on a private or presence channel directly through Relay without making an HTTP request to your application. Send and receive them with Echo'swhisperhelpers.
Relay doesn't need access to your database or sessions. When a browser subscribes to a private or presence channel, Echo asks your application at POST /broadcasting/auth, and dust-framework signs the authorization with RELAY_APP_SECRET so Relay can verify it directly. Your application uses the same secret to sign the HTTP requests that publish broadcast events to Relay.
Installation
The local Relay server is enabled through the optional relay Cargo feature, which is off by default so applications that don't run it don't compile its dependencies. Add relay to the features your application already enables for dust-framework in Cargo.toml:
[dependencies]dust-framework = { version = "0.1", features = ["database-postgres", "redis", "sqs", "relay"] }Enabling the relay feature registers the relay:start console command in your application. You need this feature only to run relay:start locally. Publishing broadcasts to managed Relay on DUST Cloud works without it.
Configuration
Relay reads its server address and application settings from environment variables in your .env file. For most local setups, you need to set only your application credentials and can keep the defaults for everything else.
Application credentials
Before a browser or your application can talk to Relay, both sides need matching application credentials to verify WebSocket connections and signed broadcast requests. Add RELAY_APP_ID, RELAY_APP_KEY, and RELAY_APP_SECRET to your .env file:
RELAY_APP_ID=my-app-id
RELAY_APP_KEY=my-app-key
RELAY_APP_SECRET=my-app-secretrelay:start reads the same three variables that the relay broadcast connection uses, so your application and local Relay server stay in sync without duplicating credentials. Set all three values before starting the server, or relay:start exits with an error.
Server address
By default, Relay listens on 0.0.0.0 and port 8080 so it accepts connections on every network interface. If port 8080 is already in use on your machine or you want to bind only to loopback, set RELAY_SERVER_HOST and RELAY_SERVER_PORT in your .env file.
Keep RELAY_SERVER_HOST and RELAY_SERVER_PORT distinct from RELAY_HOST and RELAY_PORT. RELAY_SERVER_HOST and RELAY_SERVER_PORT tell relay:start which address to bind to, while RELAY_HOST and RELAY_PORT tell your application and browsers where to connect. For example, Relay may listen on 0.0.0.0:8080 while your application and browsers connect to localhost:8080:
RELAY_SERVER_HOST=0.0.0.0
RELAY_SERVER_PORT=8080
RELAY_HOST=localhost
RELAY_PORT=8080You may also configure two optional server settings in .env when your local setup needs them:
| Variable | Default | Purpose |
|---|---|---|
RELAY_SERVER_PATH |
Empty | Prefixes every Relay route with a path, such as /relay, when a reverse proxy forwards a subpath to Relay. |
RELAY_MAX_REQUEST_SIZE |
10000 |
Sets the largest HTTP API request body Relay accepts, in bytes. Larger requests receive a 413 response. |
TLS
When your local application serves pages over HTTPS, browsers block insecure ws:// connections from those pages. You may have relay:start serve wss:// and https:// directly by pointing RELAY_SERVER_TLS_CERT at a PEM certificate file in your .env file.
Your application's relay broadcaster trusts your operating system's certificate store, so a certificate signed by a locally trusted certificate authority works for both browsers and your application. For example, you may install a local certificate authority and generate a localhost certificate in your application's root directory with mkcert:
mkcert -installmkcert localhostmkcert localhost creates localhost.pem and localhost-key.pem. Point RELAY_SERVER_TLS_CERT and RELAY_SERVER_TLS_KEY at those files in .env, set RELAY_HOST to a hostname the certificate covers, and set RELAY_SCHEME to https:
RELAY_SERVER_TLS_CERT=localhost.pem
RELAY_SERVER_TLS_KEY=localhost-key.pem
RELAY_HOST=localhost
RELAY_SCHEME=httpsWith RELAY_SCHEME=https, Echo connects over wss:// and your application publishes broadcasts over https://. When RELAY_SERVER_TLS_CERT is set, relay:start accepts only TLS connections on its port and prints Relay running at wss://… when it starts.
Relative paths resolve against your application's base path, and the certificate file may hold intermediate certificates after the server's certificate. You need RELAY_SERVER_TLS_KEY only when the private key is in a separate file. When RELAY_SERVER_TLS_KEY is unset, relay:start reads the key from the certificate file. If the certificate file holds no key, relay:start exits with an error that tells you to set RELAY_SERVER_TLS_KEY.
Allowed origins
By default, Relay accepts WebSocket connections from any origin (*). If you want to mirror stricter origin rules while developing locally, set RELAY_APP_ALLOWED_ORIGINS to a comma-separated list of hostnames:
RELAY_APP_ALLOWED_ORIGINS=localhost,*.myapp.testRelay compares each entry against the hostname of the browser's Origin header, so list hostnames rather than full URLs with schemes or ports. A * wildcard matches any sequence of characters in the hostname. For example, *.myapp.test allows http://app.myapp.test:5173, and it rejects both https://myapp.test and connections without an Origin header.
Connection timeouts and limits
Relay checks that idle connections are still alive and caps message sizes and subscriptions for each application. The defaults work for most local development, and you may override any of them in .env:
| Variable | Default | Purpose |
|---|---|---|
RELAY_APP_PING_INTERVAL |
60 |
Seconds a connection may stay silent before Relay pings it. If the connection stays silent for that long again, Relay closes it. |
RELAY_APP_ACTIVITY_TIMEOUT |
30 |
Seconds browsers wait without hearing from Relay before sending a ping. |
RELAY_APP_MAX_MESSAGE_SIZE |
10000 |
Largest WebSocket message a browser may send, in bytes. |
RELAY_APP_MAX_CONNECTIONS |
No limit | Maximum simultaneous open WebSocket connections for the application. |
RELAY_APP_MAX_CHANNELS_PER_CONNECTION |
1000 |
Maximum channels a single browser connection may subscribe to at once. |
Client events
When browsers send client events such as typing indicators with Echo's whisper method, Relay relays those client- events directly to the other subscribers on the channel. The RELAY_APP_ACCEPT_CLIENT_EVENTS_FROM variable controls which connections may send them:
members(default): Allows only connections subscribed to the channel to send client events. On presence channels, Relay attaches the sender's presenceuser_idso a browser cannot impersonate another member.all: Allows any open connection to send client events, even if it is not subscribed to the channel.none: Disables client events and replies to each one with an error.
For example, to turn off client events for your local application, set the variable to none in .env:
RELAY_APP_ACCEPT_CLIENT_EVENTS_FROM=noneRate limiting
Relay can cap how many messages each browser connection may send in a time window. Rate limiting is off by default, and you may turn it on in .env when testing how your frontend handles throttled connections:
RELAY_APP_RATE_LIMITING_ENABLED=true
RELAY_APP_RATE_LIMIT_MAX_ATTEMPTS=60
RELAY_APP_RATE_LIMIT_DECAY_SECONDS=60
RELAY_APP_RATE_LIMIT_TERMINATE=falseEach window starts when a connection sends its first message and lasts for RELAY_APP_RATE_LIMIT_DECAY_SECONDS seconds (default 60). Within that window, a connection may send up to RELAY_APP_RATE_LIMIT_MAX_ATTEMPTS messages (default 60). When a connection exceeds the limit, Relay replies with a rate-limit error and leaves the connection open by default. Set RELAY_APP_RATE_LIMIT_TERMINATE=true to close the connection instead.
Serving multiple applications
Environment variables configure one application, and that covers most projects. When you develop two applications side by side on your machine, such as a storefront and an admin dashboard, one local Relay server can serve both if you register the second application in a src/config/relay.rs configuration file.
Start from Relay::from_env(env) to keep your primary application's environment settings, build each extra application with App::new, adjust any fields you need, and push it onto relay.apps:
// src/config/relay.rsuse dust::config::relay::{App, ClientEvents, Relay};use dust::config::{self, Env};#[config::section]fn relay(env: &Env) -> Relay { let mut relay = Relay::from_env(env); let mut admin = App::new( env.require::<String>("ADMIN_RELAY_APP_ID"), env.require::<String>("ADMIN_RELAY_APP_KEY"), env.require::<String>("ADMIN_RELAY_APP_SECRET"), ); admin.allowed_origins = vec!["admin.myapp.test".into()]; admin.client_events = ClientEvents::None; relay.apps.push(admin); relay}Declare mod relay; in src/config/mod.rs so your application loads the file.
Running the server
Once you enable the relay feature and set your credentials in .env, start the local Relay server using the relay:start command:
dust relay:startRelay listens on 0.0.0.0:8080 by default and prints its WebSocket URL when it is ready. Press Ctrl+C to stop the server. Relay closes open connections before exiting.
If you need a different host or port for a single run without changing .env, pass --host or --port:
dust relay:start --host=127.0.0.1 --port=9000If your setup serves Relay under a path prefix, pass --path to override RELAY_SERVER_PATH for that run:
dust relay:start --path=/relayDebugging
By default, Relay prints only its startup address. When you troubleshoot a missed event or a failed subscription, pass --debug to watch live server activity:
dust relay:start --debugWith --debug enabled, Relay prints connections opening and closing, channel subscriptions and unsubscriptions, whispers, published events with their recipient counts, and protocol errors.
Running under systemd
A relay started with relay:start is a foreground process, so run it under a supervisor. Give the unit the name dust-relay, which dust restart uses by default, and point ExecStart at your application binary:
# /etc/systemd/system/dust-relay.service
[Unit]
Description=dust relay server
After=network.target
[Service]
WorkingDirectory=/srv/app
ExecStart=/srv/app/bin/your-app relay:start
Restart=always
RestartSec=2
KillSignal=SIGTERM
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reloadsudo systemctl enable --now dust-relaydust restart restarts this unit after restarting the cron daemon, so a deploy that replaces the binary also picks up the new relay code. If you name the unit differently, set RELAY_SERVICE or pass --relay-service as the commands guide describes. dust status reports whether the relay is running.
Troubleshooting
Most missed events come from a credential or address mismatch rather than from Relay itself. Start Relay with --debug and watch whether the browser connects and subscribes before you change application code.
| Symptom | Likely cause | Fix |
|---|---|---|
| The browser never connects | RELAY_HOST, RELAY_PORT, or RELAY_SCHEME points somewhere other than the bind address |
Compare them with RELAY_SERVER_* and the startup URL |
A private channel returns 403 |
The channel is not registered, the callback returned false, or the user is a guest |
Check src/routes/channels.rs and the callback's return value |
| A broadcast never arrives | BROADCAST_CONNECTION is log or discard, or no worker is running |
Set relay and start a queue worker |
| Listening with the wrong event name | A custom name contains dots | Prefix it with a dot in Echo, such as '.order.shipped' |
| The connection drops when idle | A proxy closes idle sockets before Relay's ping interval | Lower RELAY_APP_PING_INTERVAL or raise the proxy timeout |
| The app publishes but Relay rejects it | RELAY_APP_SECRET differs between the app and Relay |
Use the same three RELAY_APP_* values on both sides |
Because broadcasts are queued by default, a missing worker looks exactly like a missing broadcast. Run dust queue:work or check queue:failed before suspecting Relay.
Production
The relay:start server is for local development. It runs in a single process, keeps all connections and channel state in memory, and does not scale across multiple servers.
In production, use managed Relay on DUST Cloud, which handles TLS and scaling for you. Point your production RELAY_APP_ID, RELAY_APP_KEY, RELAY_APP_SECRET, RELAY_HOST, RELAY_PORT, and RELAY_SCHEME variables at your DUST Cloud Relay cluster, and your application will publish to it without running relay:start.