0201. Realtime runtime mechanics: rings, read/commit connections, send-buffer enforcement
Status: Accepted (2026-11-27). Implements 0020; details in ../architecture/realtime.md. Refined by 0204 (bounded backlogs, shed order, send budget) and 0205 (two read lanes, drain over shared memory).
Context
ADR 0020 fixes the shape of the realtime process: gateway threads and room-owner threads joined by SharedArrayBuffer rings, uWS.js native fan-out, per-socket typed-array state, soft and hard send-buffer caps. Building it raised questions that ADR leaves open:
- What happens when a ring is full or a message is larger than a ring.
- How a sleeping consumer is woken without losing a wake-up.
- Whether reads and the group commit can share one Postgres connection.
- How uWS’s
maxBackpressure interacts with an op stream that must never have gaps.
Decision
- Ring = SPSC byte ring. 64-byte header, power-of-two data area, 16-byte record header
[len][type][flags][a][b]. Records never wrap; a PAD marker skips the tail.
- Payloads above a quarter of the ring travel as FRAG records, which the consumer reassembles, so ordering holds for any size (4 MiB OPS frames go through 4 MiB rings).
- Producers reserve in place (
reserve -> write -> commit), so the fast path allocates nothing.
- When the ring is full, the producer appends to a local overflow list, keeping order, and waits on
RSEQ with Atomics.waitAsync. It never blocks its event loop.
- Gateways answer
busy once the overflow to an owner passes 32 MiB.
- Wake-ups. The consumer announces
CSLEEP, re-checks, then sleeps on WSEQ. A producer notifies only when CSLEEP is set. A producer waiting for space re-checks the consumer position after announcing PWAIT. Without that re-check a wake-up was lost and cost a 50 ms timeout per ring-full event (found by the cross-thread ring test).
- Coalescing notifies to one per event-loop turn was tried and rejected: no CPU gain, and stalls under producer bursts.
- Bounded drains. A consumer handles at most 1,024 records or 2 ms per event-loop turn, then yields. Without this, a burst of batches delayed COPY completions and socket I/O on the owner thread (commit p99 went from 100 ms to 50 ms at 10k clients).
- Two Postgres paths per owner.
- One dedicated commit connection: COPY, the pages update, clientId blocks.
- A read pool of at most 2: page lookup, journal tails, index loads, dedupe reads.
- A long tail or index read must never delay every room’s commit. Per instance that is 2 owners x 3 + 1 LISTEN = 7 connections (ADR 0010 said 1 per owner + 1).
- Every query on the commit connection runs through one serial lane, because postgres.js rejects queries while a COPY is in flight (COPY_IN_PROGRESS).
- Send-buffer caps. uWS skips publishes to sockets above
maxBackpressure, which would silently drop ops from a client’s stream.
- uWS’s limit is set to 2 x
SEND_BUFFER_HARD_BYTES with closeOnBackpressureLimit.
- The gateway closes sockets above
SEND_BUFFER_HARD_BYTES itself, from send results and a 250 ms sweep of getBufferedAmount().
- Sockets above
SEND_BUFFER_SOFT_BYTES leave the room’s presence topic until they fall under half of it. Each room has two topics: o<room> for ops and control, p<room> for presence.
- Zero-copy fan-out. uWS reads
Uint8Array views on shared memory, so gateways publish BROADCAST and PRESENCE_BATCH frames straight from the ring record.
- Connection caps across gateways. Per-user and per-IP counts live in a count-min sketch: two hashed Int32 rows per table in a SAB, updated with
Atomics. Collisions can only make a cap stricter. Per-user op buckets are per gateway thread, so the effective cap is up to gateways x USER_OPS_PER_SEC on Linux; the per-connection buckets are exact.
- Aligned presence ticks. Gateways flush presence on 50 ms wall-clock boundaries and owners tick 8 ms later. A cursor then waits for one tick instead of two unaligned ones: measured p99 46 ms instead of ~102 ms. No cross-thread messages are needed.
- Metrics without messages. Every worker thread writes Float64 slots in its own SAB. The main thread renders them with a
thread label on /metrics.
Alternatives
postMessage between threads: structured clone and allocation per message, against ADR 0020.
- Blocking
Atomics.wait in producers: would stall a gateway’s sockets when an owner lags.
- One connection per owner: a cold 682K-node index load or a 20,000-batch tail would hold every room’s commit behind it.
closeOnBackpressureLimit at the hard cap only: acceptable, but the sweep gives a close at the documented cap and a metric.
Consequences
- Rings are correct for any message size and never drop.
- Latency under bursts is bounded by the 2 ms drain budget.
- Each instance uses 7 Postgres connections.
- On macOS loopback the kernel dominates CPU per delivered frame (realtime.md, measured). Linux numbers come from WP-H.