Skip to content

perf(platform): serve realtime streams from one shared reader per process - #4590

Merged
yannickmonney merged 14 commits into
mainfrom
perf/realtime-shared-readers
Oct 9, 2026
Merged

yannickmonney merged 14 commits into
mainfrom
perf/realtime-shared-readers

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What

Realtime cost moves from per open browser tab to per API process. Same events, same order, same authorization.

  • /events (backend/realtime/hint-hub.ts, sse-fanout.ts): one loop per process reads each new outbox row once and fans it out in memory; a ring of recent rows serves Last-Event-ID resumes without a query (an older cursor still reads the database and says resync when it must); the membership/session recheck is one batched pass beside the tail; one timer heartbeats every stream; each stream has an ordered write queue and is ended when it stops reading, so one slow client cannot stall the rest. Streams open with a jittered retry: so a deploy's reconnects spread out.
  • Chat progress lane (backend/domains/chat/generation-watch.ts): one watcher per process does a light read per tick for every watched thread, text and parts only for threads that moved, and reads the settled message alone (not the transcript), shared by every tab of the thread.
  • Browser reopen backoff (use-backend-hints.ts): each wait spreads over the upper half of its interval.

Why

Each /events stream polled the outbox every 300 ms plus two auth reads per 15 s (~3.5 queries/s per tab); each open chat tab polled its generation row every 250 ms. A million tabs would have been millions of queries a second.

Evidence (load harness, #4589)

5,000 idle tabs + 50 task writers, one api process, same machine and workload:

before after
DB transactions/s 10,961 153
backend CPU 146 s 28.6 s
RSS 1,678 MiB 313 MiB
task create p95 / p99 / max 3.8 s / 6.3 s / 8.5 s 250 ms / 473 ms / 869 ms
errors 1 × 500 0

Testing

  • backend/realtime/* 26 tests (8 new: one tail read per poll for a crowd, targeted hints, other orgs, ring resume without a per-stream read, database resume with resync, batched recheck ending only the revoked stream, jittered retry, loop stops after the last stream); generation-watch.test.ts 5 new; chat routes and the drain test unchanged; use-backend-hints 27.
  • PERF-P17 (manual suite) measures the per-process cost with the harness's connections profile.

Fixes from review and CI (on top of the first push)

  • Resync on a reclaimed cursor, ring path too. CI's integration lane caught it: a resume the in-memory ring could replay skipped the retention check, so a client whose cursor the database had reclaimed was never told to resync. The ring path now asks for the oldest retained id — one read shared by every resume within 250 ms (dropped after the hub's own reclaim) — and sends resync after the replay. Proven locally: the lane reads gapped: resync=true.
  • Hints whose transaction commits late are delivered. An outbox id is taken at insert but visible at commit, so a transaction committing after a later one left a hole the id > cursor read had passed — the hint never reached anyone (main's per-stream loop lost these too, but the shared tail passes other orgs' rows, so more often). The tail now remembers the ids it read past, looks for them each tick for 30 s, and hands late rows to their org's streams framed without an id (a browser's resume position does not move back). A rolled-back id is forgotten after the grace period.
  • A big batch no longer aborts its stream. The writer's ceiling counted queued frames and the hub queued a replay or a tail page frame by frame, so any batch of more than 256 distinct hints aborted the stream before it sent anything — and the reconnect replayed into the same abort. A delivery is now one write; the ceiling also bounds queued characters (1 MiB); a write onto an empty backlog is always taken. New sse-fanout.test.ts covers the ceiling; a 400-hint replay test arrives whole.

@yannickmonney
yannickmonney force-pushed the perf/realtime-shared-readers branch from 56d6ca5 to c4148bf Compare October 9, 2026 03:01
@yannickmonney
yannickmonney force-pushed the perf/realtime-shared-readers branch from c4148bf to 52efcfe Compare October 9, 2026 04:29
…rocess

Each open hint stream ran its own loop: an outbox read every 300 ms and
two authorization reads every 15 s, ~3.5 queries a second per browser
tab. One loop per process now reads each new outbox row once and fans it
out in memory; a ring of recent rows serves resumes without a query; the
authorization recheck is one batched pass beside the tail; one timer
heartbeats every stream; each stream has an ordered write queue, and one
that stops reading is ended so it resumes instead of stalling the rest. A
stream opens with a jittered reconnect delay. Same events, same order.

5,000 idle tabs on one api process: 10,961 -> 153 transactions/s, backend
CPU -80 %, RSS 1,678 -> 313 MiB, task create p95 3.8 s -> 250 ms.
A deploy refuses every tab's handshake in the same second, and the
capped doubling brought them all back in the same second too, attempt
after attempt. Each wait is now spread over the upper half of its
interval.
Every open chat tab polled its thread's generation row every 250 ms, read
the live parts on every tick of a running turn and the whole transcript
when it settled. One watcher per process now does a light read per tick
for all watched threads, the text and parts only for the threads that
moved, and the settled row alone, shared by every tab of the thread.
PERF-P17 checks with the load harness that a crowd of idle tabs costs the
database per process, not per tab; its automation row names the unit
tests that hold the fan-out half.
A resume the in-memory ring could replay skipped the retention check, so
a client whose cursor the database had already reclaimed replayed from
the ring and was never told to resync — the contract the per-stream loop
kept, and one a reconnect to another process would still keep. The ring
path now asks for the oldest retained id, one read shared by every resume
within 250 ms and dropped after the hub's own reclaim, and sends resync
after the replay when the cursor is below it.
An outbox id is taken at insert but visible only at commit, so a
transaction that commits after a later one leaves a hole the tail's
id > cursor read has already passed: that hint never reached anyone,
as it never did from the per-stream loop. The tail now remembers the
ids it read past, looks for them each tick for 30 s, and hands what
commits to every stream of its org, framed without an id so a browser's
resume position does not move back. A rolled-back id is forgotten after
the grace period.
The stream writer's ceiling counted queued frames, and the hub queued a
replay or a tail page frame by frame in one synchronous loop: any batch
of more than 256 distinct hints overflowed on the fastest client and
aborted the stream before it sent anything, and the reconnect replayed
the same batch into the same abort. A delivery is now one write, the
ceiling also bounds queued characters (1 MiB), and a write onto an empty
backlog is always taken.
A late row older than the ring's oldest is no longer put in front of
it: the oldest row is what a resume trusts the ring to reach back to.
The row still reaches every live stream.
Track the newest ids of a big jump, look only just under the first row when the tail starts on an empty outbox, and give holes among the newest rows at startup the same grace. Late rows are coalesced and framed once per org. A writer refuses only a backlog already past its byte ceiling, and the progress lane gets a 16 MiB ceiling for whole-reply snapshots.
@yannickmonney
yannickmonney force-pushed the perf/realtime-shared-readers branch from d4771a5 to 22370b5 Compare October 9, 2026 04:46
The budget was spent in ascending order, so a big older jump in one read used it all and the hole next to the newest rows, the one a transaction still in flight holds, went untracked.
A stream's byte ceiling now leaves its biggest queued write out, so a replay bigger than the ceiling no longer refuses the resync right behind it, which looped a tab through reconnects. A progress snapshot replaces its unsent predecessor in place, carrying its parts, so a tab that stops reading holds one snapshot instead of every tick, and the lane is back on the default ceiling.
Holes an earlier read noted held the whole budget for their grace period, so a hole a later read passed, the one a transaction still in flight holds, went untracked. Holes are noted in ascending order and the oldest give way.
A tab that fell behind on text alone was sent the whole parts payload with every replacement. The progress lane gets its larger ceiling back: replacement holds it to a few frames, and an agentic turn's frames can pass a megabyte each, which refused the settled frame of a tab one snapshot behind.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant