A small, headless WebSocket gateway for application events. It routes arbitrary JSON between trusted backend publishers and authenticated client connections. It keeps connection state in memory and does not store events or call application services.
The Rust code keeps process startup in src/main.rs. src/config.rs loads namespace settings, src/auth.rs validates tickets and publisher credentials, src/protocol.rs owns shared message types and validation, src/hub.rs owns connection registration and event fan-out, src/state.rs composes runtime state, and src/routes.rs handles HTTP and WebSocket traffic.
Requirements are Rust and Cargo 1.88 or newer, Node.js 22 or newer for the examples and client tests, and GNU Make if you want to use the Makefile.
make dev creates .env from the example settings when needed, fills missing development defaults, and generates a local RSA key pair for the demo namespace if it uses the example key path. It keeps existing settings and keys. Change the development publisher secret before using the service outside a local demo. The generated private key stays under the ignored keys/ directory. A production ticket issuer keeps its signing key and supplies only its public key to the gateway.
Run the service and the standard-library demo in separate terminals. The first command prepares local development settings before starting the server.
make dev
make demoOn Windows, use PowerShell to copy the example environment file if cp is unavailable. Run make prod for the optimized server and make test to run Rust and TypeScript client unit tests.
The loopback demo hosts a generic REST snapshot on port 8090 and an explicit POST /mutate route. It runs independently of any application backend.
To observe outage recovery, run make dev in one terminal and make demo in another. Wait for the demo client to report connected, stop the gateway, and call curl -X POST http://127.0.0.1:8090/mutate. The REST state changes even though publishing fails; the client continues polling and logs the new revision. Restart the gateway and wait for connected again. The client takes a fresh snapshot after subscription acknowledgment, then periodic polling stops. Call /mutate once more: the event triggers a REST read, and no additional snapshot reads occur until another event or a connection failure.
The service loads .env when present. In production, provide environment variables through the service manager or deployment platform. GATEWAY_NAMESPACES is a comma-separated set of lower-case namespace names. Each namespace requires a separate configuration group. Hyphens in names become underscores in environment variable prefixes.
| Variable | Default | Purpose |
|---|---|---|
GATEWAY_BIND |
0.0.0.0:8080 |
HTTP listener address |
GATEWAY_NAMESPACES |
required | Namespaces served by this instance |
GATEWAY_HEARTBEAT_INTERVAL_SECS |
15 |
Server JSON heartbeat interval |
GATEWAY_CLIENT_TIMEOUT_SECS |
30 |
Maximum time without a client pong |
GATEWAY_AUTH_TIMEOUT_SECS |
5 |
Time for the first authentication message |
GATEWAY_SUBSCRIPTION_TIMEOUT_SECS |
5 |
Time to set the initial subscription list |
GATEWAY_DRAIN_SECONDS |
5 |
Graceful shutdown window |
GATEWAY_MAX_CONNECTIONS |
10000 |
Maximum concurrent WebSocket connections |
GATEWAY_OUTBOUND_QUEUE |
64 |
Per-connection queued event limit |
GATEWAY_MAX_CONTROL_BYTES |
16384 |
Maximum WebSocket message and frame size |
GATEWAY_MAX_PUBLISH_BYTES |
65536 |
Maximum encoded event body size |
For each name in GATEWAY_NAMESPACES, set NAMESPACE_<NAME>_ISSUER, NAMESPACE_<NAME>_AUDIENCE, NAMESPACE_<NAME>_PUBLIC_KEY_PATH, NAMESPACE_<NAME>_PUBLISHER_TOKEN, and optionally NAMESPACE_<NAME>_ALLOWED_ORIGINS and NAMESPACE_<NAME>_ALLOW_MISSING_ORIGIN. A namespace named example-app uses the prefix NAMESPACE_EXAMPLE_APP_. Publisher tokens must contain at least 32 bytes. Origins are exact origins including scheme and port, with no path. Missing origins are rejected unless explicitly allowed.
Connect with a standard WebSocket upgrade at /v1/namespaces/{namespace}/ws. The client sends an authenticate JSON message as its first WebSocket message.
{"type":"authenticate","ticket":"<short-lived RS256 JWT>"}The gateway validates the fixed RS256 algorithm, signature, issuer, audience, namespace, subject, and expiry. The ticket payload includes a channels array granting exact channel names. The gateway acknowledges authentication with {"type":"authenticated","expires_at":...}. Connections close when the ticket expires so the client can obtain a new ticket and the BFF can re-check access.
After authentication, the client sends the complete desired subscription set, including an empty list when it only needs user-specific delivery.
{"type":"set_subscriptions","request_id":"sub-1","channels":["workspace:42"]}The gateway replaces the subscription set atomically and replies with subscriptions_ack and the same request ID. If any requested channel lacks a ticket grant, it returns subscription_denied and leaves the existing set intact. Before the initial subscription is acknowledged, connections do not receive channel broadcasts.
Application-level ping and pong messages carry a nonce. Clients should echo the nonce from each server ping. This heartbeat is visible to browser and React Native JavaScript APIs. The server also answers client pings. Invalid messages are ignored or receive a generic protocol error. Authentication and subscription failures close the connection.
Use a dedicated gateway issuer and audience. A ticket contains these claims.
{
"iss":"https://identity.example",
"aud":"realtime:example-app",
"sub":"profile-or-service-id",
"namespace":"example-app",
"channels":["workspace:42"],
"iat":1790000000,
"exp":1790000060
}exp, iss, aud, sub, namespace, and channels are required. Use short expirations, a gateway-specific audience, and exact channel grants. The browser WebSocket constructor cannot set arbitrary authorization headers, so the example sends the ticket in the first encrypted WebSocket frame instead of placing it in the URL. Never log tickets or expose a signing key to a client.
The gateway only validates the ticket signature and claims. It does not call the identity provider or check a session database. A consuming BFF should authenticate its existing web cookie or mobile session, enforce that caller's current permissions, and then issue a short-lived gateway ticket. Do not reuse a broad application access token as a gateway ticket.
Publish to POST /v1/namespaces/{namespace}/events with that namespace's publisher bearer token.
{
"id":"a-unique-publisher-event-id",
"name":"resource.changed",
"target":{"type":"channel","channel":"workspace:42"},
"payload":{"resourceId":"42","revision":7}
}Set target to either {"type":"user","subject":"..."} or {"type":"channel","channel":"..."}. User events reach all of that subject's active connections in the namespace. Channel events reach active subscribers in the namespace. Payload may be any JSON value. The example publisher reads its namespace, credentials, target, name, and JSON payload from environment variables.
The gateway responds 202 with {"queued":N} after local connection queues accept the event. This reports local queueing only. A zero count is a successful publish with no active recipient. Slow consumers whose bounded queues fill are disconnected so their clients can recover from their own REST APIs. There is no history, replay, deduplication, or cross-instance delivery.
examples/client.ts exports a framework-free RealtimeClient. Supply the WebSocket URL, desired channels, a ticket provider, a function that fetches the application's REST snapshot, and callbacks for snapshots, events, and state changes. The app owns its REST URL and its existing cookies or mobile session headers.
The client starts REST polling immediately after a connection or heartbeat failure. It retries WebSockets with capped exponential backoff and jitter. Authentication and subscription are repeated after reconnect. It keeps polling until the server acknowledges the requested subscriptions and a fresh REST snapshot succeeds. An event arriving during recovery marks the snapshot dirty and triggers another serialized read before polling stops. Socket events are invalidation hints. REST responses remain the source of application state.
The client prevents overlapping snapshot requests, coalesces invalidations during an in-flight read, ignores stale socket callbacks, aborts its active read on stop(), and clears timers and sockets. A failed recovery read keeps the client in fallback. It refreshes after each new event and deduplicates the most recent 512 event IDs.
The WebSocket connection constructor accepts only a URL and optional subprotocols in the standard browser API. If the gateway uses an Origin allowlist, list each deployed web origin and the public HTTPS gateway origin used by native clients. Configure reverse proxies to pass WebSocket upgrades and set idle timeouts above the heartbeat window.
GET /healthzis a liveness response and remains healthy during drain.GET /readyzreturns503once shutdown starts. New WebSocket upgrades and event publishes also return503during drain.- On
SIGINTorSIGTERM, the process marks itself unready, rejects new work, lets current sockets drain for the configured window minus one second, and closes them with code1001before the listener exits. Give the process manager at least the same termination grace period. - Terminate TLS at a trusted reverse proxy or load balancer, enable WebSocket upgrade forwarding, and configure connection limits and ingress rate limits there. Keep each publisher key in server-side secret storage and rotate it per namespace.
- The service uses one in-memory instance. Connection state and event delivery are lost on restart. The client fallback keeps REST-based applications usable during an outage, but events are best effort.
A healthy socket cannot detect an event that a backend never published. In particular, a committed write followed by a publisher failure can leave a client stale until its next normal REST refresh or reconnect. Do not remove production polling until event publication is verified for every committed write path. For stronger delivery guarantees, add post-commit retries or an outbox in the owning backend. The gateway itself intentionally has no database or broker in this MVP.
The gateway does not define application identities, sessions, data models, or REST APIs. An application should give each trust boundary its own namespace and configure that namespace's issuer, audience, public key, publisher credential, and origin policy. Namespace names and channel names are application choices; none are built into the gateway.
An authenticated application backend should issue a short-lived ticket using its existing session. Derive sub from the application's stable profile identity, and grant only the channels the caller may currently access. Keep the signing key on the backend and install its matching public key in the gateway configuration. A browser frontend and a native app can use the same standard WebSocket protocol; native deployments should configure their reachable gateway host and decide whether to accept missing Origin headers.
Publish an invalidation only after its related state is committed, or write it to an application-owned outbox in the same transaction and retry delivery. Keep payloads compact, such as { "resourceId": "...", "revision": 12 }. Clients treat events as hints and fetch authoritative snapshots from the application's existing REST API. This gateway has no knowledge of that API and never applies event payloads as application state.
For local integration, add the application's namespace names to GATEWAY_NAMESPACES and add a complete NAMESPACE_<NAME>_* settings group for each. Run make dev to fill missing values and generate development key pairs when the configured public key path uses keys/<namespace>-public.pem. Configure each backend's gateway URL and namespace-specific publisher credential to match. Do not reuse development credentials in a deployed environment.
For active-active deployment, add a shared event-distribution layer behind the local routing boundary and an independently designed durable publisher path. This MVP provides no Redis, broker, durable event storage, or horizontal fan-out.