惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
爱范儿
爱范儿
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss
B
Blog RSS Feed
博客园 - 聂微东
G
GRAHAM CLULEY
Engineering at Meta
Engineering at Meta
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
WordPress大学
WordPress大学
Scott Helme
Scott Helme
AI
AI
S
Security Affairs
T
Threat Research - Cisco Blogs
M
MIT News - Artificial intelligence
T
Troy Hunt's Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
人人都是产品经理
人人都是产品经理
AWS News Blog
AWS News Blog
T
Threatpost
Cyberwarzone
Cyberwarzone
www.infosecurity-magazine.com
www.infosecurity-magazine.com
U
Unit 42
V
Vulnerabilities – Threatpost
J
Java Code Geeks
博客园 - Franky
月光博客
月光博客
Blog — PlanetScale
Blog — PlanetScale
NISL@THU
NISL@THU
D
Docker
小众软件
小众软件
N
News and Events Feed by Topic
Microsoft Security Blog
Microsoft Security Blog
Y
Y Combinator Blog
A
Arctic Wolf
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
Forbes - Security
Forbes - Security
量子位
PCI Perspectives
PCI Perspectives
美团技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
I
InfoQ
Security Archives - TechRepublic
Security Archives - TechRepublic
有赞技术团队
有赞技术团队
腾讯CDC
P
Proofpoint News Feed
S
Security @ Cisco Blogs
G
Google Developers Blog
C
Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building Real-Time Apps in Node.js with Rivalis: WebSockets, Rooms, Actors, and a Binary Wire
Daniel Kalev · 2026-05-22 · via DEV Community

If you have ever tried to build a multiplayer game, a collaborative editor, or a chat server in Node.js, you have probably written the same boilerplate twice: a ws server, a map of socket → user, a map of room → users, an auth handshake, a heartbeat, a rate limiter, a reconnect loop on the client, and a bespoke binary or JSON protocol gluing it all together.

Rivalis is the framework I wish I had the first time I wrote that boilerplate. It splits into two packages:

  • @rivalis/core — the Node.js server. Rooms, actors, auth middleware, pluggable transports, and a binary wire format.
  • @rivalis/browser — a small typed browser client with reconnect, token-refresh, and Sec-WebSocket-Protocol ticket delivery.

Both are MIT licensed, TypeScript-first, and at v6 on npm. Let's walk through the design and then build a small example.


A small note before we dive in

I want to be honest about what this project is, because I think it matters.

Rivalis is my pet project. I have been working on it since 2022, on and off, in evenings and weekends and the quiet stretches between deadlines. It started because I kept making the same mistakes every time I built a multiplayer backend — the same race conditions, the same auth handshake bugs, the same "why is this socket leaking memory at 3 AM" moments. After the third or fourth time, I realized the lesson was not "be more careful next time." The lesson was "stop rewriting this from scratch."

So the goal of Rivalis is simple: take everything I have learned about building real-time multiplayer servers — the close-code conventions, the timing-safe comparisons, the heartbeat tuning, the way you should never trust the client's clock, the difference between rate limiting at the socket layer and at the room layer — and bundle it into something other people can use without paying the same tuition I did. If it saves even one person a weekend of debugging, that is the project earning its keep.

It is also not just a hobby anymore. The framework has been quietly battle-tested in a handful of companies over the past couple of years, running multiplayer game servers and real-time collaboration backends in production, and the results have been honestly better than I expected. Long-uptime, low-incident, the kind of boring stability you actually want from a real-time layer. That feedback loop — seeing it survive contact with real users — is what pushed me to keep polishing the API and finally write this article.

If you find rough edges, please tell me. The whole point is that you should not have to learn them the hard way.


The mental model

Rivalis gives you four primitives:

Primitive What it is
Rivalis The server entrypoint. Holds your transports, auth, rate limiter, and room manager.
Room A named space you subclass. Binds inbound topics to handlers; broadcasts to its members.
Actor A per-connection handle inside a room. Carries data returned by auth, plus id, send, kick.
AuthMiddleware One method — authenticate(ticket) — returns { data, roomId } or null.

The data flow on every connection:

client.connect(ticket)
        │
        ▼
  AuthMiddleware.authenticate(ticket)
        │
   ┌────┴────┐
   │         │
  null    { data, roomId }
   │         │
  close   join room → Actor
4001       (onJoin fires)

Enter fullscreen mode Exit fullscreen mode

That is the whole shape. Everything else — heartbeats, rate limiting, presence, reconnects — is configured, not coded.


Hello world: an echo chat server

The server, in full:

import http from 'http'
import {
    Rivalis, Transports, Room, AuthMiddleware,
    type AuthResult, type Actor
} from '@rivalis/core'

type ActorData = { name: string }

class ChatRoom extends Room<ActorData> {
    protected override presence = true   // auto __presence:join / __presence:leave

    protected override onCreate() {
        this.bind('chat', this.onChat)
    }

    protected override onJoin(actor: Actor<ActorData>) {
        actor.send('welcome', JSON.stringify({ youAre: actor.data?.name ?? '' }))
    }

    private onChat(actor: Actor<ActorData>, payload: Uint8Array) {
        this.broadcast('chat', payload)
    }
}

class Auth extends AuthMiddleware<ActorData> {
    override async authenticate(ticket: string): Promise<AuthResult<ActorData> | null> {
        const name = ticket.trim()
        if (!name || name.length > 20) return null
        return { data: { name }, roomId: 'global' }
    }
}

const server = http.createServer()
const rivalis = new Rivalis<ActorData>({
    transports: [new Transports.WSTransport({ server })],
    authMiddleware: new Auth()
})
rivalis.rooms.define('chat', ChatRoom)
rivalis.rooms.create('chat', 'global')
server.listen(8080, () => console.log('ws://localhost:8080'))

process.on('SIGINT', async () => { await rivalis.shutdown(); process.exit(0) })

Enter fullscreen mode Exit fullscreen mode

The browser side is just as small:

import { WSClient } from '@rivalis/browser'

const ws = new WSClient<'chat' | 'welcome'>('ws://localhost:8080')
const enc = new TextEncoder()
const dec = new TextDecoder()

ws.on('client:connect', () => console.log('connected'))
ws.on('welcome', (p) => console.log('welcome:', dec.decode(p)))
ws.on('chat', (p) => console.log('chat:', dec.decode(p)))

ws.connect('alice')
ws.send('chat', enc.encode('hello world'))

Enter fullscreen mode Exit fullscreen mode

That is a complete real-time chat. No express, no socket.io, no Redis. Run it.


Rooms are where the logic lives

A Room is a class you subclass. It has lifecycle hooks (onCreate, onJoin, onLeave, onDestroy) and a small API surface:

Method Purpose
bind(topic, listener) Register inbound topic handler.
bindAny(listener) Wildcard fallback for unbound topics.
send(actor, topic, payload) Unicast.
broadcast(topic, payload) Fan-out.
each(fn) Iterate room actors.
kick(actor, payload?) Disconnect with a reason.
destroy() Tear down the room.

A few details worth knowing:

  • maxActors and joinable are simple instance fields. Set maxActors = 4 and the fifth joiner gets closed with room_full.
  • presence = true auto-broadcasts __presence:join and __presence:leave with a JSON payload describing the joining/leaving actor. You can override presencePayload(actor) to scrub server-only fields out before the broadcast.
  • Reserved topics. The __ prefix is reserved for framework events. bind/unbind throw if you try to claim one.
  • unknownTopicPolicy defaults to 'kick' — an actor sending a topic nobody bound is treated as misbehaving. Switch to 'drop' for permissive apps.

The Room API is deliberately small. Game state, lobbies, turn logic — that is all just code you write inside your subclass.


Actors carry your auth payload

Whatever your AuthMiddleware.authenticate returns in data is stamped on the Actor for the lifetime of the connection. That means after auth, the room never needs to look up "who is this user" — the data is already on the actor:

class JWTAuth extends AuthMiddleware<{ userId: string; tier: 'free' | 'pro' }> {
    override async authenticate(ticket: string) {
        const claims = await verifyJwt(ticket)
        if (!claims) return null
        return {
            data: { userId: claims.sub, tier: claims.tier },
            roomId: claims.room
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Inside the room:

private onChat(actor: Actor<{ userId: string; tier: 'free' | 'pro' }>, payload: Uint8Array) {
    if (actor.data?.tier !== 'pro' && payload.byteLength > 256) return
    this.broadcast('chat', payload)
}

Enter fullscreen mode Exit fullscreen mode

Actor also has save<T>(key, value) and get<T>(key) for per-actor scratch state — handy for in-room counters, last-seen timestamps, anti-spam buckets.

One security note from the docs that is worth repeating. Any secret comparison inside authenticate — HMACs, signatures, session tokens — must use crypto.timingSafeEqual or an equivalent constant-time comparator. === and Buffer.compare short-circuit on first mismatch and leak the prefix length under enough samples. The framework cannot enforce this for you; if you compare a signature with ===, you have built a timing oracle.


The wire is binary, but opaque

Every frame on the wire is { topic: string, payload: bytes }. The framework does not inspect payload. You encode it however you want — JSON, protobuf, msgpack, raw bytes, a hand-rolled struct.

For a chat app, JSON over TextEncoder is fine:

const enc = new TextEncoder()
const dec = new TextDecoder()

export const encode = <T>(v: T): Uint8Array => enc.encode(JSON.stringify(v))
export const decode = <T>(p: Uint8Array): T => JSON.parse(dec.decode(p)) as T

Enter fullscreen mode Exit fullscreen mode

For a 60 Hz multiplayer game, swap in @bufbuild/protobuf or msgpackr. The wire layer does not care. It does enforce one thing: frames are binary. Send a text frame and the server closes the connection with INVALID_FRAME (4002).


Security defaults that exist on purpose

A lot of WebSocket tutorials end at "and now you have real-time!" without ever mentioning that you have also just opened a fresh attack surface. Rivalis ships defaults for the boring stuff:

  • Token-bucket rate limiting, on by default — 30 tokens, 30/sec refill. Subclass RateLimiter to swap it out, pass null to opt out.
  • Heartbeats — 30-second ping with a 2-miss kick. Configurable on WSTransport.
  • Frame and topic size capsmaxPayload (64 KiB default) and maxTopicLength (256 default). Anything bigger gets dropped at the transport.
  • Backpressure handling — a per-socket outbound buffer cap (1 MiB default); the onBackpressureDrop hook fires on every dropped frame so you can escalate (e.g. kick the slow actor).
  • Origin allow-list — pass allowedOrigins to WSTransport and any other Origin header is rejected before auth runs. Required for CSWSH protection if you ever decide tickets ride on cookies.
  • Pre-handshake connection limiting — subclass ConnectionLimiter to cap how many sockets a single IP can open per second. Rejected with RATE_LIMITED (4005) before any auth code runs.
  • Ticket via subprotocol — set ticketSource: 'protocol' on both the server and browser client, and the ticket rides on Sec-WebSocket-Protocol instead of ?ticket=. Keeps credentials out of URL access logs and browser history.
  • Tickets are never logged in plaintext — only an 8-char SHA-256 fingerprint, so a leaked log file does not become a session-takeover.

None of those need code from you on the happy path. The defaults are sane; the knobs exist when you need them.


The browser client is small on purpose

@rivalis/browser has five methods: connect, disconnect, send, on/once/off. Everything else is a configuration choice.

Typed events

The client:* events have typed payloads, and you can constrain user topics through a generic:

type Topics = 'lobby:state' | 'chat' | 'game:tick'

const ws = new WSClient<Topics>('wss://example.com/ws')

ws.on('chat', (p) => { /* p: Uint8Array */ })
ws.on('typo:state', (p) => { ... })            // type error
ws.on('client:kicked', ({ code, reason }) => { ... })

Enter fullscreen mode Exit fullscreen mode

Reconnection done right

const ws = new WSClient(url, {
    reconnect: { maxAttempts: 8, baseDelayMs: 250, maxDelayMs: 5000 }
})

Enter fullscreen mode Exit fullscreen mode

Exponential backoff with jitter. Importantly, reconnect skips terminal close codes. If the server kicked you with INVALID_TICKET, KICKED, or ROOM_REJECTED, the client treats that as a final answer and does not retry. Those mean "the server does not want you back" — silently looping is just noise.

Refreshing short-lived tickets

If your tickets are short-lived JWTs, the getTicket hook is called before every reconnect attempt:

const ws = new WSClient(url, {
    reconnect: true,
    getTicket: async () => {
        const res = await fetch('/api/realtime-token', { credentials: 'include' })
        if (!res.ok) throw new Error('token endpoint failed')
        return await res.text()
    }
})

ws.connect(initialTicket)   // first call still uses its argument verbatim

Enter fullscreen mode Exit fullscreen mode

If getTicket throws, the loop terminates with client:reconnect_failed. You cannot reconnect without a ticket, so there is nowhere to retry to.


Close codes you will actually see

Knowing the close codes is the difference between a useful error UI and "connection lost":

Code Meaning
4001 INVALID_TICKET — bad/missing ticket; auth rejected
4002 INVALID_FRAME — non-binary frame received
4003 KICKED — server-initiated kick (reason in payload)
4004 ROOM_REJECTEDroom_full or room_not_joinable
4005 RATE_LIMITED — pre-handshake connection limiter

The browser client emits client:kicked with { code, reason } parsed for you, so you can route each case to the right UI without peeking into the close payload yourself.


Graceful shutdown

A real deployment needs a clean SIGTERM path. rivalis.shutdown() destroys every room (firing onDestroy and kicking remaining actors with room_destroyed), then disposes every transport (closing live sockets with KICKED + 'server_shutdown'):

process.on('SIGINT',  async () => { await rivalis.shutdown({ timeoutMs: 5000 }); process.exit(0) })
process.on('SIGTERM', async () => { await rivalis.shutdown({ timeoutMs: 5000 }); process.exit(0) })

Enter fullscreen mode Exit fullscreen mode

The timeoutMs is the upper bound for transport disposal. Sockets that have not closed by then get torn down.


When to reach for Rivalis

It is a good fit for:

  • Multiplayer games — turn-based or real-time, where you want a GameRoom subclass holding authoritative state and broadcasting deltas.
  • Chat / presence / collaborative cursorspresence: true and a couple of bound topics get you most of the way.
  • Collaborative editors — the binary-frame primitive plays well with CRDT payloads. Just plumb Yjs or Automerge updates into a topic.
  • Live dashboards with per-tenant rooms — roomId from your auth payload routes each tenant to their own room.

It is not a queue, an SFU, or a Pub/Sub between Node instances. If you need horizontal fan-out, you compose it — one Redis stream feeding many Rivalis nodes, each broadcasting to its locally-joined actors. The framework deliberately stays inside one process; that is what makes the room/actor model cheap.


A 60-second tasting menu of the surface area

// Server
const rivalis = new Rivalis({ transports: [...], authMiddleware: new MyAuth() })
rivalis.rooms.define('chat', ChatRoom)
rivalis.rooms.create('chat', 'global')
rivalis.connections                       // joined actors
rivalis.sockets                           // open sockets (incl. pre-handshake)
rivalis.logging.level = 'debug'           // built-in logger
await rivalis.shutdown({ timeoutMs: 5000 })

// Room
class GameRoom extends Room<MyData> {
    override maxActors = 4
    override joinable = true
    protected override presence = true
    protected override unknownTopicPolicy = 'drop'
    protected override onCreate() { this.bind('move', this.onMove) }
    protected override onJoin(actor) { actor.send('state', JSON.stringify(state)) }
    protected override onLeave(actor) { /* cleanup */ }
    private onMove(actor, payload) { this.broadcast('state', nextState) }
}

// Browser
const ws = new WSClient<MyTopics>(url, {
    reconnect: { maxAttempts: 8 },
    ticketSource: 'protocol',
    getTicket: refreshJwt
})
ws.on('client:connect', ...)
ws.on('client:kicked', ({ code, reason }) => ...)
ws.connect(jwt)
ws.send('move', encode({ dx: 1 }))

Enter fullscreen mode Exit fullscreen mode


Install and play

npm install @rivalis/core ws @toolcase/base @toolcase/logging @toolcase/serializer
npm install @rivalis/browser

Enter fullscreen mode Exit fullscreen mode

Both packages declare their @toolcase/* and ws dependencies as peers, so you control the versions in your app.

If you build something on top of it — a game, a tutorial, a CRDT bridge — please open an issue or a PR. Feedback on the security defaults and the binary-frame design is especially welcome.

Happy broadcasting.