Linora

Realtime tier (apps/realtime)

Owner: WP-B, wave 3 R1. ADRs 0019 (validation authority), 0020 (runtime, capacity), 0021 (topology), 0011/0023 (auth, security), 0201 (rings, connections, send-buffer enforcement), 0202 (dedupe, retry floor, ordering), 0203 (presence interest management), 0204 (overload control), 0205 (owner memory, read lanes, drain, access re-check), 0803 (realistic load profile). Protocol: shared/src/messages.ts, codec.ts. Limits: shared/src/limits.ts.

Wave 3 (R1) changes in one place

Current (wave 1, implemented)

The full pipeline runs over real sockets and threads and is covered by 49 tests (npm test -w @linorahq/realtime): auth, role/scope, ScanBatch, StructIndex, sequencing, COPY journal, ACK/BROADCAST, presence, revocation, drain and crash recovery.

Target (unchanged) and how it is built

One Node 26 process per box runs uWebSockets.js in worker threads. It never materializes a document.

apps/realtime/src/
  main.ts            process entry: config (refuses to start without secrets), SIGTERM/SIGINT -> drain
  supervisor.ts      main thread: SAB rings, spawn owners then gateways, LISTEN linora_auth/linora_file, /metrics, drain
  config.ts          LINORA_REALTIME_* knobs (+ DATABASE_URL, LINORA_TOKEN_KEYS, LINORA_BLOB_DIR from server-common)
  auth.ts            subprotocol token, rt/svc verification, denylist (iat-based), count-min connection caps
  ring.ts            SPSC SharedArrayBuffer ring: in-place reserve/commit, FRAG reassembly, overflow, waitAsync
  msgs.ts            ring message types and payload layouts
  presence.ts        typed-array presence tables: zero-copy validate + merge, delta/full encoding
  stats.ts           per-thread metrics in SABs, rendered by the main thread
  validation.ts      the only entry to rule code (ScanBatch, StructIndex) + scan-summary transport
  gateway/           uWS app per thread: upgrade auth, typed-array conn table, buckets, scan, presence, fan-out
  owner/             rooms, dedupe, sequencing, journal COPY, catch-up rings and tails, index loads, presence ticks

Threads

Connection lifecycle

  1. Upgrade (/v1/realtime?file=). Sec-WebSocket-Protocol: linora.v1, linora-rt.<token>. authenticate runs before any allocation:
    • HMAC verify of a realtime token (typ: 'rt') or a service token (typ: 'svc', only svc === 'docworker').
    • fid must equal ?file.
    • Denylist check by iat.
    • Then the per-user (USER_CONNECTIONS) and per-IP (LINORA_REALTIME_MAX_CONN_PER_IP) caps.
      • The client address is the TCP peer, unless the peer is in LINORA_TRUSTED_PROXIES. Then it is the PROXY v2 source, or else the rightmost X-Forwarded-For hop that is not a trusted proxy (SR-05).
      • IPv6 addresses count per /64 (SR-10).
    • Rejections: 400 bad file id, 401 bad/expired/missing token, 403 wrong file / revoked / svc: 'api', 429 caps, 503 draining. The linora.v1 subprotocol is selected on success.
  2. hello. protocol and rulesVersion must match (else version_mismatch, close 4009).
    • A valid clientGrant (cg token, same file and user) reclaims its clientId.
    • Otherwise the owner hands one out from the file’s block of 1,024 (update files set next_client_id = next_client_id + 1024, one write per block).
    • welcome carries a fresh 24 h grant, role, color PEER_COLORS[clientId % 10].
    • Control messages pipelined behind hello wait for welcome (at most 8).
    • Service subscribers get clientId 0.
    • Every allocation consumes the file’s 16M id space, so new clientIds are capped per (file, user): burst 60, then 60/min. Over the cap -> rate_limited, close 4029; reconnects with a grant allocate nothing.
    • need_client_id is answered at most 4 times per socket.
  3. subscribe(pageId, sinceSeq, pendingFromClientSeq?, mode?).
    • The owner creates the room on first use: page lookup (page, file and parent file not deleted), durable head = max(page_ops.seq). Concurrent subscribers wait on that one load.
    • Errors: a page of another file or a missing page -> not_found; sinceSeq > head -> seq_ahead; duplicate -> protocol_error; over MAX_ROOM_SUBSCRIBERS -> room_full.
    • pendingFromClientSeq loads that client’s journal rows first (ADR 0202).
    • subscribed{room, peers (<= 50 most recently active), others}, then the tail, then synced{seq}. Only at synced does the gateway subscribe the socket to the room topics o<room> (ops, peer events) and p<room> (presence).
    • Tails come from the room’s catch-up ring (<= ROOM_RING_BYTES) when it covers sinceSeq + 1, else from Postgres. Waiting subscribers are batched into one read from the smallest sinceSeq; batches committed during the read are queued per subscriber and sent after the tail.
    • If the journal no longer holds sinceSeq + 1, the answer is snapshot_stale.
    • Writer mode (mode: 'write', API op forwarding, ADR 0303): editor + files:write required. The server answers subscribed{peers: []} + synced{head} at once, then only ACKs and errors. The socket is invisible to peers and gets no broadcasts or presence.
    • Service subscribers (doc workers) are live but hidden: no peer events, no presence, ops refused with read_only.
  4. OPS (gateway, per frame):
    • Header parse.
    • Role >= editor and files:write (else read_only).
    • Frame <= MAX_MESSAGE_BYTES (else too_large; above +64 KiB uWS closes with 1009).
    • Room subscribed on this socket (else not_found).
    • Retry floor and floor probe (ADR 0204). After busy or rate_limited on j, batches above j are refused here. Resent j travels alone, and later batches wait until it is answered.
    • Buckets:
      • OPS_MSGS_PER_SEC, with a burst of 64 so an in-flight window fits.
      • OPS_BYTES_PER_SEC, with debt allowed, so one 4 MiB batch passes a full bucket.
      • Per user and gateway thread: USER_OPS_PER_SEC for ops and USER_IDS_PER_SEC for node ids (SR-03).
      • Over a bucket -> rate_limited + floor, with retryAfterMs = max(bucket refill time, exponential backoff).
    • ScanBatch over the op list in place, timed into linora_rt_scan_ns_per_op. Malformed framing, or more than 1,048,576 ids + block nodes -> protocol_error with clientSeq; the socket stays open.
    • Busy when backlog + payload to the owner would exceed 8 MiB.
    • The ring record {clientId, clientSeq, scan summary, op-list bytes} goes to the owner. The summary is the BatchScan arrays as raw bytes, copied once. Above 65,536 ids it is a 16-byte header, and the owner re-scans the op bytes.
  5. Owner:
    • Retry floor. busy after commit lag (> 200 ms) or a commit backlog, an owner-to-gateway backlog over 8 MiB, a full room queue (256), or a full index budget. It travels as a binary O2G.BUSY record; the gateway sets the floor and the retry delay.
    • Dedupe (ADR 0202).
    • Lazy index load, on the slow read lane:
      • The newest snapshot structure section at or below head, from the blob store or PG chunks.
      • Gunzipped with a cap of 14 B x MAX_NODES_PER_PAGE + 1 MiB (SR-16), then fromStructure, then journal-tail replay.
      • Index budget STRUCT_INDEX_BUDGET_BYTES / owners, LRU eviction of idle indexes, busy when full of active rooms.
    • StructIndex.check, timed into linora_rt_check_ns_per_op. seq = ++next if any op passed.
    • Accepted op ranges are sliced into one BROADCAST frame whose op list is also the journal row. The ACK is encoded once.
    • After the COPY commit: the ACK goes to the author (and to any duplicate that arrived meanwhile), and one PUBLISH per gateway with live subscribers. The author’s gateway publishes from the author’s socket, so the author is skipped.
  6. Presence (ADR 0203):
    • Gateway, inbound: validates and merges frames into the socket’s slot (PRESENCE_MSGS_PER_SEC bucket; invalid or over-rate frames are dropped silently). It also keeps the socket’s own viewport and follow target, and forwards merged deltas once per PRESENCE_TICK_MS. A delta the ring cannot take stays merged and goes next tick.
    • Ticks are phase-aligned to wall-clock boundaries: gateways flush at t % 50 == 0, owners publish 8 ms later. Exactly one tick per boundary, never before it: a timer can fire up to about 1 ms early by Date.now(), and then waits for the boundary instead of ticking twice.
    • Owner merge: mergeDiff merges each delta into the peer’s full state and marks the fields that changed. Unchanged updates stop here (idle suppression).
    • Owner tick: each tick (every 4th for rooms > LARGE_ROOM_SUBSCRIBERS) the owner writes one internal record per gateway with live members (O2G.PRESENCE_ROOM). It holds at most MAX_RELAYED_CURSORS changed peers, with their interest data, plus refresh groups for that gateway’s members whose viewport or follow target changed.
    • Gateway fan-out: one PRESENCE_BATCH per live recipient, corked with its pending broadcasts:
      • no own entry;
      • cursor/drag only in view (+ margin), from a followee, or one exit update, at most MAX_VISIBLE_CURSORS;
      • selection, tool and drag end to all;
      • viewports to followers every tick, others every VIEWPORT_RELAY_MS;
      • refresh entries for that recipient.
    • Joiners get one unicast batch with the full state of up to 50 peers (ended drags and hidden cursors omitted; follow never relayed).
    • Never journaled. Shed first under backpressure.
  7. Close / unsubscribe:
    • The socket leaves its rooms: peer_left, presence slot freed.
    • A room with no subscribers is evicted after ROOM_IDLE_EVICT_MS once nothing is in flight; this frees its index, ring and presence.
    • An index with no ops for STRUCT_INDEX_IDLE_MS is dropped.

Journal commit

Revocation, file events, drain

Close codes

4001 unauthorized/revoked (do not retry with the same token), 4002 protocol (control message too large), 4003 access revoked or file deleted, 4009 version mismatch (reload), 4010 going away (retry after retryAfterMs), 4029 too many new clientIds (reconnect with the grant), 1009 frame too large (uWS). Sockets closed for exceeding the hard send-buffer cap get no close frame: reconnect and catch up.

Guarantees clients rely on (tested)

Validation

validation.ts is the only module that imports rule code: scanBatch and createBatchScan from '@linorahq/doc/scan', structIndexFactory from '@linorahq/doc/struct-index'.

Configuration

Metrics (/metrics, per thread label)

How it protects the targets

Memory grows with sockets (typed-array slots, interned strings, uWS) and per room. Structural indexes exist only for rooms being edited, within a budget. Nothing per node or per property is kept outside the index. CPU: zero-copy scan, one encode per broadcast, native fan-out straight from the ring, coalesced presence, no per-message allocation on the ring path. Latency: 10 ms commit window, bounded drains.

Measured (local harness, wave 1)

node --env-file-if-exists=.env apps/realtime/bench/harness.ts --clients 10000 --runs 3 --seconds 10 --presence.

Metric (10,000 subscribed sockets, 2,600 editors) Median of 3 Range
Server RSS growth per socket, whole population / marginal second half 6.3 KB / 4.2 KB 5.3-6.6 / 2.3-5.0 KB
of which JS per socket (V8 heap + typed arrays, all threads, after GC) 0.72 KB + 1.31 KB  
Total RSS with 10k sockets (4 threads incl. 4 V8 isolates) 325 MB 310-336 MB
Idle CPU with 10k sockets 1.5% of one core 1.4-1.9%
Op load handled 26.0k ops/s, 5.2k batches/s, 48k frames out/s  
CPU per op, total / user space 25.6 us / 5.5 us 23.8-25.6 / 5.0-5.6
CPU per batch (5 ops, avg fan-out 9.2), total / user space 128 us / 27.6 us  
CPU per delivered frame, total (macOS loopback kernel dominated) 13.9 us 12.9-13.9
ScanBatch p50 (A1, server histogram) <= 100 ns/op  
StructIndex.check p50 (A1, server histogram) <= 100 ns/op  
Journal COPY p50 / p99 5 / 50 ms p99 50-100
Owner receive -> ACK sent, p50 / p99 (server histogram) 15 / 100 ms p99 50-200
ACK seen by the client, p50 / p99 27 / 96 ms p99 93-237
Presence: 35k cursor msgs/s in, 3.2k batches/s out; CPU per msg total / user 6.9 / 1.2 us  
Cursor latency sender -> peer, aligned ticks, p50 / p99 (test, 3 runs) 26 / 46 ms p99 45-47
Revocation (real NOTIFY) to socket closed 10-40 ms (tests)
Ring, cross-thread, per message ~0.3-0.4 us (test)

Projection to the ADR 0020 load (100k sockets, 40k batches/s, ~416k presence msgs/s): user-space RSS ~0.4-0.65 GB for sockets plus rooms, indexes and isolates, within the 4 GB budget. User-space CPU ~1.1 cores for ops (27.6 us x 40k) plus ~0.5 cores for presence, which matches ADR 0020’s 1.9-core estimate. Kernel cost per frame must be measured on Linux (WP-H). The local p99 ACK latency (100 ms) misses the 50 ms target on this shared Mac with Docker Postgres (COPY p99 50-100 ms while other agents’ suites hit the same database; a plain commit takes ~1 ms). It must be re-measured on the reference setup.

What the numbers mean:

Measured at 100k (wave 3, R1; Docker Desktop Linux VM, server pinned to 8 vCPU, generator on the remaining 6)

Reports: tools/loadtest/results/2026-11-28--100000c-docker-.md.

Acceptance (WP-B, final numbers with WP-H)