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.
LINORA_TRUSTED_PROXIES (SR-05). IPv6 caps are per /64 (SR-10)./metrics binds LINORA_REALTIME_METRICS_HOST (127.0.0.1 by default, SR-18). Subscribe needs files:read (SR-24).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.
@linorahq/doc/scan, @linorahq/doc/struct-index) through src/validation.ts.svc: 'api' tokens), role/scope per OPS frame, page-to-file binding, connection caps, clientId allocation caps, control and frame size caps, presence validation, revocation and the denylist, slow consumers.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
LINORA_REALTIME_GATEWAYS threads, default 5 on Linux and 1 on macOS (no SO_REUSEPORT balancing there). Each is a uWS app on the shared port.
LINORA_REALTIME_PORT=0 (tests, tools) and several gateways, gateway 0 learns a free port from a port-0 bind and binds it again by number, so the others can join it.uv_loop_close() while having open handles).{slot} (upgrade-time data is dropped in open).LINORA_REALTIME_OWNERS (2). A file maps to owner fnv1a(fileId) % owners./metrics (LINORA_REALTIME_METRICS_PORT), LISTEN linora_auth and linora_file (fanned out to gateways with postMessage; rare), drain.LINORA_REALTIME_RING_BYTES, 4 MiB). Record header [len u32][type u8][flags u8][2][a u32][b u32]. Payloads are written in place.
reserveDirect writes into the ring or fails./v1/realtime?file=). Sec-WebSocket-Protocol: linora.v1, linora-rt.<token>. authenticate runs before any allocation:
typ: 'rt') or a service token (typ: 'svc', only svc === 'docworker').fid must equal ?file.iat.USER_CONNECTIONS) and per-IP (LINORA_REALTIME_MAX_CONN_PER_IP) caps.
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).svc: 'api', 429 caps, 503 draining. The linora.v1 subprotocol is selected on success.protocol and rulesVersion must match (else version_mismatch, close 4009).
clientGrant (cg token, same file and user) reclaims its clientId.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].hello wait for welcome (at most 8).rate_limited, close 4029; reconnects with a grant allocate nothing.need_client_id is answered at most 4 times per socket.max(page_ops.seq). Concurrent subscribers wait on that one load.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).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.sinceSeq + 1, the answer is snapshot_stale.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.read_only.files:write (else read_only).MAX_MESSAGE_BYTES (else too_large; above +64 KiB uWS closes with 1009).not_found).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.USER_OPS_PER_SEC for ops and USER_IDS_PER_SEC for node ids (SR-03).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.backlog + payload to the owner would exceed 8 MiB.{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.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.fromStructure, then journal-tail replay.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.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.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.mergeDiff merges each delta into the peer’s full state and marks the fields that changed. Unchanged updates stop here (idle suppression).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.MAX_VISIBLE_CURSORS;VIEWPORT_RELAY_MS;ROOM_IDLE_EVICT_MS once nothing is in flight; this frees its index, ring and presence.STRUCT_INDEX_IDLE_MS is dropped.COPY page_ops (...) FROM STDIN (FORMAT binary) in flight. A new one starts once 10 ms have passed since the last start, or at 1 MiB, on the dedicated commit connection.busy when the oldest waiting batch is > 200 ms old or the backlog is > COMMIT_BACKLOG_BYTES.UPDATE pages SET head_seq = greatest(...), tail_ops/tail_bytes/tail_deletes += delta, last_op_at runs at most once per second, batched with unnest. tail_deletes counts accepted DELETE ops (the compactor’s delete rule, ADR 0312).@linorahq/server-common auth-events.ts). All events also enter the gateways’ denylist for one token TTL, keyed by iat <= event time, so tokens minted after a re-add work again.
cred_revoked: error unauthorized + close 4001 for sockets with that sid.member_removed: file_event: access_revoked + close 4003.project_deleted / file_deleted: file_event: file_deleted + close 4003.role_changed: lowers the live role (ops then get read_only), file_event: role_changed; an upgrade needs a re-minted token.file_event{pages_changed|file_renamed} is published to the file topic f<fileId>.LINORA_REALTIME_RECHECK_S (300 s), the main thread collects the open sockets’ (credential, user, project, file, role) tuples from the gateways.
iat <= at + 2 s (SR-09).going_away{retryAfterMs uniform in [0, DRAIN_SPREAD_MS)} (fatal), close 4010.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.
busy/rate_limited on j, nothing after j is processed until j is resent.validation.ts is the only module that imports rule code: scanBatch and createBatchScan from '@linorahq/doc/scan', structIndexFactory from '@linorahq/doc/struct-index'.
scanBatch(bytes, start, end, client, scan) covers the op list n op*n. Offsets are absolute in the frame. The gateway scans the received frame in place.check exactly once per batch (the index bumps its own seq iff an op passed) and replay once per journal row when loading. Failing ops are no-ops in replay.LINORA_REALTIME_PORT (8788), LINORA_REALTIME_HOST (127.0.0.1 in dev, 0.0.0.0 in production).LINORA_REALTIME_METRICS_PORT (9464, -1 = off), LINORA_REALTIME_METRICS_HOST (127.0.0.1; deploys set the private interface).LINORA_REALTIME_GATEWAYS, LINORA_REALTIME_OWNERS, LINORA_REALTIME_RING_BYTES (4 MiB).LINORA_REALTIME_MAX_CONN_PER_IP (2000), LINORA_TRUSTED_PROXIES (CIDRs, default none), LINORA_REALTIME_RECHECK_S (300).DATABASE_URL, token keys (LINORA_TOKEN_KEYS master or the per-purpose LINORA_TOKEN_KEYS_RT, _CG, _SVC_DOCWORKER), LINORA_BLOB_DIR./metrics, per thread label)read_only, rate_limited, protocol_error, busy, duplicates.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.
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:
Reports: tools/loadtest/results/2026-11-28--100000c-docker-.md.
test/crash.test.ts, SIGKILL during a pending commit).test/overload.test.ts:
test/drain.test.ts).test/backpressure.test.ts).