Helonyxe Realtime documentation
Everything you need to run the server, connect an app to it, and operate it in production.
Checking server status…
Overview
Helonyxe Realtime is a shared WebSocket server. One deployment serves many applications, whether they run on the same machine or anywhere else on the internet. An app needs only two settings: the server URL in its backend, and the same URL in its frontend.
- Your backend holds the app secret. It signs a token for each signed-in user and publishes events with a plain HTTPS request.
- Your frontend (web, React Native, any socket.io client) connects with that token and receives events for the rooms it belongs to.
- The server keeps apps isolated from each other, checks every token, and delivers each event to every connected user in the target rooms, on every machine.
It is built on NestJS and Socket.IO 4, with Redis shared by every worker and every machine.
Quick start
Option A: Docker (recommended)
Needs Docker with Compose. This starts the server, a password-protected Redis with persistence, this documentation and the home page.
cd socket-server
cp .env.example .env
# Fill in the two secrets, for example:
# ADMIN_TOKEN=$(openssl rand -base64 48)
# REDIS_PASSWORD=$(openssl rand -hex 24)
docker compose up -d --build
curl http://localhost:3000/ready # {"status":"ready"}Open http://localhost:3000 for the home page and http://localhost:3000/docs for this documentation. Change the port with PORT=8080 in .env. The port is published on 127.0.0.1 only; set BIND_ADDRESS=0.0.0.0 to reach it from other devices on your network for testing.
Check that the running stack is healthy and hardened:
sh scripts/docker-check.sh # 20 checks, exits 1 on the first failureOption B: Node for development
Needs Node 22 or later, pnpm and a Redis you can reach.
docker run -d --name realtime-redis -p 6390:6379 redis:7-alpine
pnpm install
export ADMIN_TOKEN=$(openssl rand -base64 48)
export REDIS_URL=redis://localhost:6390
WORKERS=1 pnpm start:dev # reloads on save, http://localhost:3000For a production-like run on all cores: pnpm build && node dist/main.js (WORKERS defaults to one per CPU).
Try it end to end
# 1. Register an app
curl -s -X POST http://localhost:3000/admin/apps \
-H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
-d '{"name":"demo"}'
# 2. Open testhtml/client.html in a browser, paste the app key and a token.
# A token for user 42 (Node):
node -e "console.log(require('jsonwebtoken').sign({sub:'42'}, process.argv[1], {expiresIn:'1h'}))" APP_SECRET
# 3. Publish to that user and watch the event arrive
curl -X POST http://localhost:3000/apps/APP_ID/events \
-H "Authorization: Bearer APP_SECRET" -H 'Content-Type: application/json' \
-d '{"rooms":["user:42"],"event":"hello","data":{"text":"It works"}}'Core concepts
Apps
An app is one tenant of the server. Registering it returns three values:
| Value | Example | Where it lives |
|---|---|---|
id | app_9f2c… | Backend config. Part of the publish URL. |
key | 24 hex characters | Frontend config. Public, part of the socket URL. |
secret | 43 characters | Backend only. Signs user tokens and authenticates publishes. Never ship it to a browser or a mobile app. |
Each app has its own Socket.IO namespace, /app/<key>. Events published by one app can never reach another app's users, even if both use the same room names.
Rooms
A room is a named group of connections inside one app. Your backend publishes to rooms; every connection in those rooms receives the event.
| Room | Who can join |
|---|---|
user:<sub> | Only the user whose token has that sub. Joined automatically on connect. Nobody can join another user's room, whatever the token says. |
public:<name> | Any signed-in user of the app. |
| anything else | Only users whose token grants it, by exact name or by prefix ending in *, such as contract:42:*. |
Room names use letters, digits and _ . : @ -, up to 200 characters.
User tokens
A user token is a JWT signed with HS256 using the app secret. Your backend creates it after the user has signed in to your app.
| Claim | Required | Meaning |
|---|---|---|
sub | Yes | Your user id (string or number). |
iat | Yes | Issued-at time. Every JWT library adds it by default. |
exp | Yes | Expiry. One hour is a good default. Tokens older than TOKEN_MAX_AGE_SECONDS (24 h) are refused regardless. |
rooms | No | Up to 100 room names or prefixes this user may join. |
Register an app
The operator of the server does this once per app, using the admin token.
curl -X POST https://realtime.example.com/admin/apps \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-H 'Content-Type: application/json' \
-d '{
"name": "Contractual",
"allowedOrigins": ["https://app.contractual.cm"],
"maxEventsPerSecond": 500
}'The secret is shown only in this response and when you rotate it. Store it in the app's backend environment straight away.
Laravel backend
1. Configure
REALTIME_URL=https://realtime.example.com
REALTIME_APP_ID=app_9f2c...
REALTIME_SECRET=...'realtime' => [
'url' => env('REALTIME_URL'),
'app_id' => env('REALTIME_APP_ID'),
'secret' => env('REALTIME_SECRET'),
],2. Issue user tokens
composer require firebase/php-jwtuse Firebase\JWT\JWT;
Route::middleware('auth:api')->get('/realtime/token', function () {
$user = auth()->user();
return ['token' => JWT::encode([
'sub' => (string) $user->id,
// Rooms this user may join: one prefix per contract they are a party to.
'rooms' => $user->contracts()->pluck('id')
->map(fn ($id) => "contract:{$id}:*")->all(),
'iat' => time(),
'exp' => time() + 3600,
], config('services.realtime.secret'), 'HS256')];
});3. Publish events
namespace App\Support;
use Illuminate\Support\Facades\Http;
class Realtime
{
public static function publish(array $rooms, string $event, array $data): void
{
$c = config('services.realtime');
Http::withToken($c['secret'])
->timeout(3)
->retry(2, 200)
->post("{$c['url']}/apps/{$c['app_id']}/events", [
'rooms' => $rooms,
'event' => $event,
'data' => $data,
])
->throw();
}
}
// Anywhere, ideally in a queued listener after the DB transaction commits:
Realtime::publish(["contract:{$contract->id}:activity"], 'contract.signed', [
'contractId' => $contract->id,
]);Publish after your database transaction commits. If you publish inside it and it rolls back, users have already been told about a change that never happened.
Node backend
import jwt from 'jsonwebtoken';
const { REALTIME_URL, REALTIME_APP_ID, REALTIME_SECRET } = process.env;
// GET /realtime/token, behind your own auth
export function realtimeToken(user) {
return jwt.sign({ sub: String(user.id), rooms: ['orders'] }, REALTIME_SECRET, { expiresIn: '1h' });
}
export async function publish(rooms, event, data) {
const res = await fetch(`${REALTIME_URL}/apps/${REALTIME_APP_ID}/events`, {
method: 'POST',
headers: { authorization: `Bearer ${REALTIME_SECRET}`, 'content-type': 'application/json' },
body: JSON.stringify({ rooms, event, data }),
});
if (res.status !== 202) throw new Error(`realtime publish failed: ${res.status}`);
}Frontend and mobile
npm install socket.io-clientimport { io } from 'socket.io-client';
const socket = io(`${REALTIME_URL}/app/${REALTIME_APP_KEY}`, {
// A function, not an object: it runs on every reconnect, so an expired token is replaced.
auth: async (cb) => {
const res = await fetch('/api/realtime/token', { credentials: 'include' });
cb({ token: (await res.json()).token });
},
});
// Rooms do not survive a reconnect: join them on every connect.
socket.on('connect', async () => {
const ack = await socket.emitWithAck('subscribe', 'contract:42:activity');
if (!ack.ok) console.warn('subscribe refused:', ack.error);
refetchContract(42); // catch up on anything missed while offline
});
socket.on('connect_error', (err) => console.warn('realtime:', err.message));
socket.on('contract.signed', ({ contractId }) => refetchContract(contractId));The same code works in React Native. Native apps send no Origin header, which is allowed; the token is what authenticates them.
Events sent while a phone is offline are not replayed when it reconnects. Refetch the current state over HTTP in your connect handler.
Admin API
Operator only. Every request needs Authorization: Bearer <ADMIN_TOKEN>; without it the answer is 401. Bodies are JSON and unknown fields are refused with 400.
/admin/apps
Registers an app. Returns 201 with the full record, secret included.
| Field | Type | Rules |
|---|---|---|
name | string | Required, 1–100 characters. |
allowedOrigins | string[] | Optional, up to 50, each like https://app.example.com. Empty means any origin. |
maxEventsPerSecond | integer | Optional, 1–100000, default 100. Counted per room delivered. |
{
"id": "app_9f2c4b7a1e3d5c6f",
"name": "Contractual",
"key": "4e1f0c9b2a7d6e5f8a3b1c2d",
"secret": "Zq8…43 characters…",
"allowedOrigins": ["https://app.contractual.cm"],
"maxEventsPerSecond": 500,
"createdAt": "2026-10-15T16:00:00.000Z"
}/admin/apps
Lists every app, without secrets.
/admin/apps/:id
One app, without its secret. 404 if it does not exist.
/admin/apps/:id
Changes name, allowedOrigins or maxEventsPerSecond. Changing origins disconnects the app's current connections so the new list applies to everyone. Returns the app without its secret.
/admin/apps/:id/rotate-secret
Issues a new secret and returns the full record with it. The old secret stops working on every machine immediately, and every connection of the app is dropped; clients reconnect with tokens signed by the new secret.
/admin/apps/:id
Deletes the app and disconnects all its users. Returns 204.
Publish API
/apps/:appId/events
Called by the app's backend with Authorization: Bearer <app secret>. The secret must belong to the app in the URL.
| Field | Type | Rules |
|---|---|---|
rooms | string[] | Required, 1–100 room names. |
event | string | Required, letters, digits and _ . : -, up to 100 characters. Socket.IO's own names (connect, disconnect, …) are refused. |
data | any JSON | Required. The whole body must fit in MAX_PAYLOAD_BYTES (100 KB). |
exceptSocketId | string | Optional. Skips one connection, typically the user who made the change and already shows it. |
| Status | Meaning |
|---|---|
202 | Accepted and fanned out to every machine. Body {"ok":true}. |
400 | Invalid body or reserved event name. |
401 | Missing or wrong secret, unknown app, or another app's secret. |
413 | Body larger than MAX_PAYLOAD_BYTES. |
429 | Over maxEventsPerSecond this second. Each room counts as one delivery. Retry after a second. |
Socket protocol
Connect
URL: <server>/app/<app key>. Handshake auth: { token: "<user token>" }. WebSocket is used when available, with HTTP long-polling as a fallback on restrictive networks.
Client events
| Emit | Payload | Acknowledgement |
|---|---|---|
subscribe | "room" or { room } | { ok: true } or { ok: false, error } with forbidden or too_many_rooms |
unsubscribe | "room" or { room } | { ok: true } or { ok: false, error: "invalid_room" } |
Clients cannot send events to each other. Send changes to your backend, which validates them and publishes.
Errors
Connection failures arrive as connect_error with one of these messages:
| Message | Cause | Fix |
|---|---|---|
Invalid namespace | The URL is not /app/<24 hex characters>. | Check the app key in the frontend config. |
unknown_app | No app has this key, or it was deleted. | Check the key, or register the app again. |
origin_not_allowed | The page's origin is not in allowedOrigins. | Add it with PATCH /admin/apps/:id. |
invalid_token | Missing, expired, wrong secret, no sub, iat or exp, or older than 24 h. | Return a fresh token from the auth function; check the secret after a rotation. |
Health checks
/health
Liveness. 200 {"status":"ok"} while the process answers. It does not touch Redis, so a Redis outage does not restart every instance at once.
/ready
Readiness. 200 {"status":"ready"} when Redis answers, otherwise 503. Load balancers should route only to ready instances.
Configuration
All settings are environment variables. The server refuses to start if one is invalid.
| Variable | Default | Description |
|---|---|---|
ADMIN_TOKEN | required | At least 32 characters. Grants full control of every app. |
REDIS_URL | redis://localhost:6379 | Shared by every worker and machine. Include the password: redis://:pass@host:6379. |
REDIS_PREFIX | rt: | Prefix for every key, so one Redis can serve other things too. |
PORT | 3000 | HTTP and WebSocket port. |
WORKERS | auto | Worker processes. auto is one per CPU core; use 1 under Kubernetes. |
MAX_PAYLOAD_BYTES | 100000 | Largest HTTP body and WebSocket message. |
TOKEN_MAX_AGE_SECONDS | 86400 | Oldest user token accepted, whatever its exp. |
Deployment
One server with Docker Compose
The Quick start setup is production-ready behind HTTPS. What the compose file already does:
- Both containers run as non-root users, with a read-only root filesystem, every Linux capability dropped, privilege escalation blocked, and memory and process limits.
- The runtime image contains Node and the built app only: no npm, yarn or compiler. App files are owned by root, so the server process cannot modify its own code.
- The socket port is published on
127.0.0.1by default, for a reverse proxy on the same machine. - Redis is not published at all. Its passwordless default user is disabled, and the server's own Redis user cannot run dangerous commands such as
FLUSHALL,CONFIGorKEYS. Data is persisted in a volume with append-only logging.
Put a reverse proxy with TLS in front. It must pass WebSocket upgrades through. With nginx:
server {
listen 443 ssl http2;
server_name realtime.example.com;
# ssl_certificate ... ssl_certificate_key ...
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 3600s;
}
}With Caddy the whole configuration is realtime.example.com { reverse_proxy 127.0.0.1:3000 }.
Kubernetes
deploy/k8s/ contains a Deployment, Service, HorizontalPodAutoscaler and an ingress-nginx Ingress. Create the secret first, then apply:
docker build -t registry.example.com/realtime:1.0 . && docker push registry.example.com/realtime:1.0
kubectl create secret generic socket-server \
--from-literal=ADMIN_TOKEN="$(openssl rand -base64 48)" \
--from-literal=REDIS_URL="redis://:password@redis-host:6379"
# set the image in deploy/k8s/deployment.yaml and the host in ingress.yaml
kubectl apply -f deploy/k8s/Use a managed or replicated Redis with persistence. Every pod must reach the same one.
Scaling
Vertical: every core of one machine
With WORKERS=auto the main process starts one worker per CPU and hands each new connection to the least busy one. Connections are sticky: every request of a long-polling session reaches the worker that holds it. A worker that crashes is replaced after one second; its users reconnect automatically.
Horizontal: more machines
All workers and all machines share rooms through Redis Streams, so an event published on any machine reaches users connected to any other. To add machines:
- Run more instances with the same
REDIS_URLandADMIN_TOKEN. - Put a load balancer in front with sticky sessions (cookie or client IP), needed for clients on long-polling.
- Route only to instances whose
/readyanswers200.
Automatic
On one machine, scaling across cores is automatic. Across machines, the Kubernetes autoscaler keeps 2 to 10 pods and adds one when average CPU passes 70%. Shutdown is graceful: a stopping pod closes its connections and clients move to another pod at once.
Redis is required, not optional. Without a shared Redis, an event reaches only the users on the machine that received it, and nothing reports the loss.
Security model
- Apps are isolated by Socket.IO namespaces. An event published by one app cannot reach another app's connections.
- User tokens are verified with HS256 only, which blocks unsigned tokens and algorithm swaps.
iatis mandatory and tokens older than 24 hours are refused. - Private user rooms can be joined only by their own user. No token grant, even
*, can open another user's room. - Secrets are compared in constant time. They are never returned by list or get, and never logged.
- Revocation reads the app from Redis on every connection and every publish, so a rotated secret or deleted app is refused on every machine immediately.
- Missed-event replay is off. Socket.IO's connection-state recovery restores rooms and replays events before authentication runs, which would let one app read another's events. A test guards against it coming back.
- Origins are checked per app as an extra layer for browsers. They are not authentication: non-browser clients can send any origin.
- HTTP headers: a strict Content-Security-Policy (scripts from this server only), no framing,
nosniff, no referrer, HSTS once TLS is in front, and noX-Powered-By. API responses carryCache-Control: no-storeso no cache keeps a secret. - Secrets and PATCH: the secret is stored apart from the app record, so an admin update can never write an old secret back over a rotated one.
- Dependencies:
pnpm audit --prodreports no known vulnerabilities in what the image ships.
Rate limiting by IP is left to the reverse proxy. Every request is authenticated with a long random token, so guessing is not practical, but a proxy limit stops floods of rejected requests from reaching the server at all.
Protect Redis. It stores every app's secret in readable form, because verifying a signature needs the secret itself. Keep it on a private network with a password. Anyone who can read it can act as any app.
Limits
| Limit | Value |
|---|---|
| Deliveries per app per second | maxEventsPerSecond (default 100), each room counts as one, shared across all machines |
| Rooms per publish | 100 |
| Rooms per connection | 100, including the user's own room |
| Room grants per token | 100 |
| Payload | MAX_PAYLOAD_BYTES, 100 KB by default |
| Token age | TOKEN_MAX_AGE_SECONDS, 24 h by default |
Not available yet: presence and member lists, per-app connection caps, Prometheus metrics, webhooks to apps, client-to-client events and missed-event replay.
Testing
# a throwaway Redis for the end-to-end suite
docker run -d --rm --name socket-server-test-redis -p 6390:6379 redis:7-alpine
pnpm lint && pnpm build
pnpm test # room rules, token checks, configuration
pnpm test:e2e # two server instances, real Redis, real socket clients
# load check: 1000 clients on all cores, half on long-polling
WORKERS=auto PORT=3055 REDIS_URL=redis://localhost:6390 ADMIN_TOKEN=$ADMIN_TOKEN node dist/main.js &
SMOKE_URL=http://localhost:3055 CLIENTS=1000 pnpm smokeThe end-to-end suite covers isolation between apps, room permissions, wrong and foreign secrets, validation, payload and rate limits, delivery across instances, secret rotation and deletion on every instance, and the session-recovery leak.
Troubleshooting
The server exits with "ADMIN_TOKEN must be set"
Set an admin token of at least 32 characters, for example openssl rand -base64 48.
/ready answers 503
The server cannot reach Redis. Check REDIS_URL, including the password, and that Redis is running.
Users connect but receive nothing
- Check the publish answered
202, not429. - Check the user subscribed to the room after their latest connect. Rooms are not kept across reconnects.
- With several machines, check they all use the same Redis.
Long-polling clients keep reconnecting behind a load balancer
Sticky sessions are off. Enable cookie or IP affinity, or connect with transports: ['websocket'].
Every client was disconnected at once
Expected after rotating the secret, deleting the app or changing its allowed origins. Clients reconnect on their own; after a rotation they need tokens signed with the new secret.