Helonyxe Realtime

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.

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.

shell
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:

shell
sh scripts/docker-check.sh     # 20 checks, exits 1 on the first failure

Option B: Node for development

Needs Node 22 or later, pnpm and a Redis you can reach.

shell
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:3000

For a production-like run on all cores: pnpm build && node dist/main.js (WORKERS defaults to one per CPU).

Try it end to end

shell
# 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:

ValueExampleWhere it lives
idapp_9f2c…Backend config. Part of the publish URL.
key24 hex charactersFrontend config. Public, part of the socket URL.
secret43 charactersBackend 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.

RoomWho 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 elseOnly 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.

ClaimRequiredMeaning
subYesYour user id (string or number).
iatYesIssued-at time. Every JWT library adds it by default.
expYesExpiry. One hour is a good default. Tokens older than TOKEN_MAX_AGE_SECONDS (24 h) are refused regardless.
roomsNoUp 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.

shell
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

.env
REALTIME_URL=https://realtime.example.com
REALTIME_APP_ID=app_9f2c...
REALTIME_SECRET=...
config/services.php
'realtime' => [
    'url'    => env('REALTIME_URL'),
    'app_id' => env('REALTIME_APP_ID'),
    'secret' => env('REALTIME_SECRET'),
],

2. Issue user tokens

shell
composer require firebase/php-jwt
routes/api.php
use 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

app/Support/Realtime.php
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

js
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

shell
npm install socket.io-client
js
import { 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.

POST

/admin/apps

Registers an app. Returns 201 with the full record, secret included.

FieldTypeRules
namestringRequired, 1–100 characters.
allowedOriginsstring[]Optional, up to 50, each like https://app.example.com. Empty means any origin.
maxEventsPerSecondintegerOptional, 1–100000, default 100. Counted per room delivered.
201 response
{
  "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"
}
GET

/admin/apps

Lists every app, without secrets.

GET

/admin/apps/:id

One app, without its secret. 404 if it does not exist.

PATCH

/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.

POST

/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.

DELETE

/admin/apps/:id

Deletes the app and disconnects all its users. Returns 204.

Publish API

POST

/apps/:appId/events

Called by the app's backend with Authorization: Bearer <app secret>. The secret must belong to the app in the URL.

FieldTypeRules
roomsstring[]Required, 1–100 room names.
eventstringRequired, letters, digits and _ . : -, up to 100 characters. Socket.IO's own names (connect, disconnect, …) are refused.
dataany JSONRequired. The whole body must fit in MAX_PAYLOAD_BYTES (100 KB).
exceptSocketIdstringOptional. Skips one connection, typically the user who made the change and already shows it.
StatusMeaning
202Accepted and fanned out to every machine. Body {"ok":true}.
400Invalid body or reserved event name.
401Missing or wrong secret, unknown app, or another app's secret.
413Body larger than MAX_PAYLOAD_BYTES.
429Over 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

EmitPayloadAcknowledgement
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:

MessageCauseFix
Invalid namespaceThe URL is not /app/<24 hex characters>.Check the app key in the frontend config.
unknown_appNo app has this key, or it was deleted.Check the key, or register the app again.
origin_not_allowedThe page's origin is not in allowedOrigins.Add it with PATCH /admin/apps/:id.
invalid_tokenMissing, 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

GET

/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.

GET

/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.

VariableDefaultDescription
ADMIN_TOKENrequiredAt least 32 characters. Grants full control of every app.
REDIS_URLredis://localhost:6379Shared by every worker and machine. Include the password: redis://:pass@host:6379.
REDIS_PREFIXrt:Prefix for every key, so one Redis can serve other things too.
PORT3000HTTP and WebSocket port.
WORKERSautoWorker processes. auto is one per CPU core; use 1 under Kubernetes.
MAX_PAYLOAD_BYTES100000Largest HTTP body and WebSocket message.
TOKEN_MAX_AGE_SECONDS86400Oldest 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:

Put a reverse proxy with TLS in front. It must pass WebSocket upgrades through. With nginx:

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:

shell
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:

  1. Run more instances with the same REDIS_URL and ADMIN_TOKEN.
  2. Put a load balancer in front with sticky sessions (cookie or client IP), needed for clients on long-polling.
  3. Route only to instances whose /ready answers 200.

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

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

LimitValue
Deliveries per app per secondmaxEventsPerSecond (default 100), each room counts as one, shared across all machines
Rooms per publish100
Rooms per connection100, including the user's own room
Room grants per token100
PayloadMAX_PAYLOAD_BYTES, 100 KB by default
Token ageTOKEN_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

shell
# 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 smoke

The 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

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.