oficina / docs Public
Live push: a collaborator's typing in about one round trip
Status: revision 3, 2026-11-26.
- Revision 1 (4ce1a1b) was reviewed by Claude Fable 5.2 on oficina/docs #172: APPROVE AFTER FIXES, 18 findings. Revision 2 answers all of them; the table at the end maps each finding to where it is answered.
- Fable re-reviewed revision 2 (9319c64): APPROVE AFTER FIXES, ready to become a plan, no further round. Revision 3 (this) applies those eight fixes (second table at the end).
- Paul's rulings on revision 1's questions are below. The warm handle and push were prototyped to measure them (§4.2); figures are labelled measured or projected throughout.
Paul's rulings, 2026-11-26 (binding):
- The 50 ms floor between uploads: yes.
- Visible web tabs stay live: yes (§3.6 sets the bound).
- Keep the 250 ms window on cellular and other expensive paths: yes (also on Low Data Mode, §3.8).
- A timing check through the real edge with his own session: yes (§10; the snippet is
native/benchmarks/live-push/edge-timing.js).
Prototype (measurement only, never to merge): branch proto/live-push, the warm handle and the push stream behind DOCS_PROTO_WARM / DOCS_PROTO_PUSH (internal/docs/proto_live_push.go) and the probe's push and shared-document modes.
Branch: spec/live-push (this spec, and the measurement harness under native/benchmarks/live-push/, internal/docs/live_push_probe_test.go and native/apple/Tests/DocsKitTests/LivePushLatencyTests.swift; every probe skips unless its environment variable is set). Nothing here changes what the apps or the server do.
Background: 2026-09-01-live-sync-design.md (SSE announces a seq, the client fetches ?since=), the realtime audit (oficina/native-levelup/docs-realtime-audit.md) and its phase 1 (main 80d4989, discussion #146: echo skip, held announcements, 250 ms native upload pacing like the web's).
Why
Paul, 2026-11-26, Docs native 0.1.12: typing locally is instant, but "the lag is when I have two versions of the doc open and I'm looking at the other one catching up". He estimates it at up to 500 ms and wants it imperceptible. He asked whether we need a WebSocket, and whether making it faster would "risk essentially DDOS'ing ourselves for essentially nothing", given each Oficina instance is self-contained.
Answers, in short:
- The lag is the protocol, not rendering. Today, at a 50 ms round trip, a keystroke shows on the other copy in 274–330 ms at the median and 439–497 ms at p95, on every web/native combination (§1.1). About 120–140 ms of that is the sender waiting for its 250 ms upload window, and one whole round trip is the receiver fetching what the stream already told it exists. Applying and drawing take the web ~5–10 ms and the native app 10–45 ms.
- No WebSocket. The existing SSE stream can carry the bytes. A socket buys no latency here (both are one trip each way on the edge's HTTP/2 connection) and costs a dependency, a handshake path and a second reconnect policy (§3.6).
- Not a DDoS. Pushing bytes removes the receiver's fetch per change (one request per watcher per change). Sending when nothing is in flight instead of every 250 ms raises uploads from ~3.5/s to ~6/s per active typist at normal speed (one per keystroke), self-limited to one in flight. Requests for a typist and one watcher stay about the same and fall for every extra watcher (§4). With a warm replayed handle per active document, the prototype measured less server CPU than today: 20 against 42 ms/s for one typist, and 249 against 529 for twenty. A shared document with five typists and five watchers costs about the same as today (§4.2). The new costs are local WAL writes (~25 KB per commit, ~60 KB/s more per typist; replicated bytes should not grow, §4.3) and warm-handle memory (2.7 MB per active 20-page document).
1. Measurements
Machine: Apple M1 Max, macOS 27.0, shared with other sessions (load average 10–970 during the runs, so CPU timings are ±20%; the network-shaped numbers are much less sensitive to it). Server: the real authenticated app on loopback (TestLivePushProbeServer), HTTP/1.1, optionally behind a loopback proxy that holds every chunk RTT/2 in each direction. Typing: "Q"s at a human cadence, 60 ms + an exponential (mean 150 ms, ~6 keys/s), with a 0.7–1.5 s pause every 30–60 keys. Documents from fixtures/generate-large-doc.mjs (p20 = 20 pages, 72 KB of Yjs) unless stated.
Production path. From this Mac (Paul's network) to docs.oficina.works: TCP connect to the CARLOS edge 37–62 ms, a warm request on a reused HTTP/2 connection 45–56 ms to first byte. The edge speaks HTTP/2 to clients and HTTP/1.1 to the instance. Its reverse proxy flushes text/event-stream immediately (Go's httputil.ReverseProxy does for that type) and its compression layer excludes it (carlos/platform internal/edge/compress.go), so the edge should not buffer the stream. That could not be confirmed end to end without Paul's session (every stream needs one); the 20/50/100 ms rows below stand in for it, and 50 ms is the closest to Paul's path.
1.1 What a person sees (real clients)
Keydown on copy A to the character on copy B: the browser's DOM updated (MutationObserver; paint follows at the next frame, ≤ 16.7 ms), or the native app's publication rendered and reconciled into the text view's storage. Native ↔ native is two XCTest processes, i.e. two apps with their own main threads, as two devices are. Production DocsModel and sealed store; real web editor in headless Chrome; 120 keys each.
Measured in the quietest windows available (1-minute load average 20–230; an earlier run at load ~850 was 1.5–2.5× slower on the native side and is not used). p50 / p95 ms, 120 keys each:
| Document, RTT | web → web | native → native | native → web | web → native | |---|---|---|---|---| | 20 pages, 0 ms | 190 / 319 | 231 / 396 | 218 / 421 | 224 / 334 | | 20 pages, 50 ms | 279 / 439 | 296 / 484 | 274 / 446 | 330 / 497 | | 1 page, 50 ms | 292 / 437 | 289 / 460 | 283 / 463 | 274 / 392 |
So Paul's "heading toward 500 ms" is today's p95 at his distance, on every combination. The same runs split with the server's log (breakdown.py; medians, 20 pages, 50 ms):
| | wait to send | server | stream event → GET reaches server | GET | GET answered → shown | |---|---|---|---|---|---| | web → web | 138 | 8 | 54 | 1 | 32 | | native → native | 120 | 8 | 55 | 1 | 50 | | native → web | 123 | 10 | 57 | 1 | 29 | | web → native | 139 | 9 | 56 | 1 | 71 |
(Plus the 25 ms one-way trip up, which "wait to send" excludes.) The last column is the 25 ms trip down plus the receiver's work: the web applies and draws in ~5–10 ms; the native app needs 25–45 ms at 20 pages and ~10 ms at one page, almost all of it replica.presentation with a fresh source, which re-decodes the whole document (audit finding 2; the per-block drawing after it is 1–3 ms, S1a). Pushing the bytes removes the middle two columns; sending at once removes most of the first.
1.2 Where the time goes (protocol)
Simulated clients that follow the web's and the native app's exact rules (live_push_probe_test.go): web250 is save-queue.mjs (a key starts a 250 ms timer, not reset); native250 is DocsOfflineAccount.pace (the first send after a pause goes at once, POST starts ≥ 250 ms apart); idleN sends when nothing is in flight and N ms have passed since the last send, and coalesces otherwise. "Fetched" is today: the watcher's ?since= fetch completes. "Announced" is when the watcher's stream delivered the seq, which is when pushed bytes would arrive: a stand-in in revision 1, confirmed by the prototype's direct measurement (§4.2: 56 ms against the stand-in's 64 at 50 ms). Add receiver apply + draw (§1.1) to both. 200 keys per row, p20; median / p95 in ms.
| RTT | Policy | Sender wait | POST answered | Send → announced | Announced → fetched | Key → fetched (today's path) | Key → announced (push) | Uploads/s | |---|---|---|---|---|---|---|---|---| | 0 | web250 | 171 / 255 | 7 / 27 | 8 / 25 | 1 / 4 | 178 / 270 | 178 / 268 | 2.7 | | 0 | native250 | 118 / 232 | 6 / 10 | 7 / 10 | 0 / 2 | 127 / 243 | 127 / 242 | 3.6 | | 0 | idle0 | 0 / 0 | 8 / 21 | 8 / 22 | 1 / 4 | 8 / 24 | 8 / 22 | 6.1 | | 0 | idle50 | 0 / 0 | 9 / 20 | 9 / 22 | 1 / 5 | 10 / 24 | 9 / 22 | 6.1 | | 20 | web250 | 157 / 252 | 29 / 33 | 29 / 33 | 23 / 27 | 211 / 308 | 188 / 283 | 3.0 | | 20 | native250 | 117 / 231 | 30 / 42 | 30 / 42 | 24 / 30 | 171 / 284 | 149 / 260 | 3.6 | | 20 | idle0 | 0 / 0 | 33 / 50 | 33 / 49 | 24 / 32 | 57 / 77 | 33 / 49 | 6.1 | | 20 | idle50 | 0 / 0 | 32 / 45 | 32 / 46 | 25 / 33 | 57 / 76 | 32 / 46 | 6.1 | | 50 | web250 | 108 / 253 | 63 / 81 | 63 / 81 | 56 / 75 | 237 / 390 | 173 / 327 | 3.8 | | 50 | native250 | 117 / 232 | 62 / 79 | 62 / 79 | 54 / 66 | 235 / 352 | 177 / 297 | 3.6 | | 50 | idle0 | 0 / 3 | 63 / 88 | 63 / 88 | 54 / 67 | 117 / 152 | 63 / 99 | 6.0 | | 50 | idle50 | 0 / 0 | 64 / 80 | 64 / 80 | 55 / 66 | 119 / 140 | 64 / 82 | 6.1 | | 50 | idle100 | 0 / 69 | 64 / 79 | 64 / 80 | 55 / 66 | 127 / 199 | 70 / 137 | 6.0 | | 100 | web250 | 91 / 252 | 111 / 129 | 111 / 129 | 104 / 115 | 313 / 476 | 207 / 369 | 3.9 | | 100 | native250 | 125 / 237 | 112 / 130 | 112 / 128 | 105 / 113 | 344 / 458 | 239 / 351 | 3.6 | | 100 | idle0 | 7 / 98 | 112 / 127 | 112 / 127 | 105 / 115 | 228 / 322 | 122 / 217 | 5.7 | | 100 | idle50 | 4 / 84 | 111 / 126 | 111 / 126 | 105 / 114 | 229 / 304 | 122 / 200 | 5.7 |
How much each change buys (medians, today's native policy as the base):
| RTT | Today (native250, fetch) | Push only (keep pacing) | Pacing cut only (idle50, fetch) | Both (idle50, push) | |---|---|---|---|---| | 20 ms | 171 | 149 (−22) | 57 (−114) | 32 (−139) | | 50 ms | 235 | 177 (−58) | 119 (−116) | 64 (−171) | | 100 ms | 344 | 239 (−105) | 229 (−115) | 122 (−222) |
The pacing window is the larger cost at every round trip up to ~100 ms; the fetch is one round trip, so it grows with distance. Neither alone gets under ~100 ms at Paul's distance; both together give about one round trip plus ~12 ms at the median. The receiver's own work adds 1–25 ms (§1.1).
1.3 Causes, ranked
- Upload pacing (120–170 ms median, up to 250). Both platforms hold a key for up to 250 ms. The web's timer starts at the first key and is not reset, so an isolated key always waits the full 250 ms. The native app sends the first key after a pause at once but holds every key typed within 250 ms of the last POST's start.
- The receiver fetches what it was told about (one full round trip). The stream carries only a seq; bytes come from
GET ?since=. At 50 ms that is 54–56 ms; at 100 ms, 105. - Every POST replays the whole document on the server (
Store.ApplyUpdate→replay: a fresh WASM instance, the newest snapshot and up to 255 tail rows applied, then the update). 1.6 ms at 1 page, 10.8 ms median and 77 ms p95 at 20 pages (TestLivePushProbeApplyCost), 13–14 ms of server CPU and ~8 MB of allocation per POST in the full app at 20 pages. It is in every change's path, and with the garbage it makes it is about a third of the server's CPU (§4). - The web sender downloads most of its own changes back. The server broadcasts before it answers the POST, so the sender's stream event usually arrives before the POST's
Docs-Seq, andnoteOwnSeqcomes too late: at 20–100 ms round trip, 77–93 of ~100–130 POSTs per 200 keys were fetched back (web250rows). Phase 1 gave the native app a hold for this (heldRemoteSequence), the web has none. It costs requests, not latency. - Not causes: the edge (flushes SSE, h2, no compression of the stream), Nagle (Go and URLSession set
TCP_NODELAY), the heartbeat (15 s), native drawing after S1a (1–3 ms per peer change, pageless; paged waits for S1b). - Two windows of one document in one app do not exist on the Mac.
DocsWindows.reservebrings the existing window forward for the same account and document, so Paul's two copies are two devices, two apps or app + browser, which all go through the server. No in-process fan-out is needed (§3.8). - A web copy nobody touches stops updating after two minutes.
live-updates.mjscloses a visible tab's stream afterIDLE_MS(2 min) with no local activity and no stream event, and reopens only on activity. So Paul stops typing for two minutes, types again, and the copy he is watching stays stale until he moves the mouse over it. The same happens after every deploy or restart (hub.draincloses every stream) and at the server's 5 min TTL. Native reconnects at once.
2. Targets
Measured against these by the release step (§9.3), never by shared CI:
- p50 ≤ RTT + 30 ms, p95 ≤ RTT + 80 ms, key on A to character drawn on B, at a normal typing cadence, for a web receiver at any size and a native receiver up to ~5 pages. At Paul's ~50 ms that is ≤ 80 ms median.
- A native receiver at 20 pages: p50 ≤ RTT + 60 ms, until its fresh-source presentation (25–45 ms, audit finding 2) is made incremental, which is engine work outside this spec.
- Measured in the prototype at 50 ms (protocol only, bytes in the watcher's hand): 56 / 67 ms, and 58 / 66 ms with five typists and five watchers in one document (§4.2). Projected with the receivers' own work: ~65 ms median for a web receiver and ~80–100 ms for a native one at 20 pages, from 274–330 ms today (§1.1).
- No more requests per change than today, and server CPU per active typist within today's ±20% (§4.2 says how close the prototype comes).
3. Design
3.1 The stream carries the bytes
A client that understands push asks for it: GET /d/{sqid}/stream?push=1&since=N. hello and bye are sent only on a push=1 stream; a stream without push=1 is exactly today's.
Frames:
event: hello
data: <stream id> <the log's current seq> <log epoch>
id: 43.<tag>
event: push
data: 43 <base64 of row 43's bytes>
id: 44.<tag>
event: own
data: 44 <the client's counter from Docs-Stream>
event: update
data: 45
event: resync
data: <the log's current seq>
event: bye
data: <reason: ttl | lease | drain>The <tag> is the row's digest (16 hex digits of SHA-256 over its seq and bytes; branch review #175, finding 3, below).
pushcarries a row this client did not post.ownmarks one it did (§3.4); no bytes.updateis today's seq-only event. The server sends it instead ofpushfor a row over 32 KiB, a row it cannot open, or a client more than 256 rows / 512 KiB behind. The client then fetches?since=as today.updateframes never carryid:, because their bytes were not delivered.- As built: - The far-behind case is decided from the rows' count and stored lengths before any row is read, and a row too large to push is never loaded or cached. - The first row a flush cannot push ends it with one
update <current>, since the client's fetch brings that row and everything after it. - Reading. The stream reads rows with the same query and
openContentUpdateasupdatesGet(seq > sent ORDER BY seq, log rows only, never a snapshot). Seq isMAX+1inside the single-writer transaction, so the committed log is gapless when read. No ring buffer is needed and no reordering. The hub stays a one-slot "something happened" notification. Each stream keepssent: it reads everything aftersentand writes all the frames with one write and one flush. After anupdateframe,sentmoves to that seq. - Where it starts.
Last-Event-ID(sent byEventSourceon its own reconnects) wins oversince. Rows after the start arrive as frames, so the connect-time GET goes away. With neither, the stream starts at the current seq and still sends today's connect-timeupdate <current>right afterhello(stream.gocalls it load-bearing: it heals a cursor that failed to advance).helloalways comes first. - A rewound log (the database restored from a backup, a team re-provisioned, a later version restore). The client resyncs from 0 (the web's resync controller; native's catch-up from the start) when any of these holds: -
hello's seq is below its cursor; -hello's log epoch differs from the one it holds; - the stream sendsresync(the server's own check, below). - The server checks the cursor itself (branch review #175, findings 3 and 5), because the epoch misses the likeliest restore. A Litestream point-in-time restore is from after the last start, and a volume snapshot carries the file beside the database. So: - push and own frames carry
id: <seq>.<tag>; - fetch responses carryDocs-Seq-Tagfor the row theirDocs-Seqnames; - a resume names its cursor's tag (Last-Event-ID: <seq>.<tag>, whichEventSourcesends by itself, orsince=<seq>with aDocs-Seq-Tagrequest header). Never in the query string: access logs keep URLs, and the tag is an unkeyed digest of the row's plaintext, so on a sealed instance a log reader could confirm a guess at a small row (branch review #175, approval note 6); - the stream answersresyncand ends when the row it holds at that seq has another tag or is missing, and when the cursor is ahead of the log; - a cursor without a tag is checked by seq and epoch only.
The seq alone misses a restore that new commits have already passed: a log restored to 90, twenty new commits, and a client at 100 sees 110 and skips the new 91–100. Litestream's loss window makes that possible. The log epoch is a random value stored in the instance database. It is rotated by any operation that rewinds a log, and at startup when the database is not where the last start left it. - As built in slice 1b (logepoch.go): a boot counter, kept in the database and in a file beside it (<db>.log-epoch), compared and bumped at every start. The spec first said "a clean-shutdown marker written at the end of a clean drain". That would rotate the epoch at every deploy that overlaps generations (CARLOS_SWAP=overlap), where the new process starts before the old one has drained. - A move to another box (no file beside the database) and a restore from a copy older than the last start rotate it, so every open client resyncs once. - An ordinary deploy, overlapped or not, and a process crash (which loses no committed row) do not. - Not caught: a restore from a copy taken after the last start, onto the same disk. The seq check still catches a log that is behind, and a restore runbook can delete the file. - Clients learn the epoch from hello. Fetch responses carry it too (Docs-Log-Epoch), so a non-push client can check it on its next fetch.
- Base64 on the stream costs ~33% on 15–30 bytes per keystroke: noise. An oversized update still goes by fetch.
3.2 Client rules for frames (web and native alike)
- One fetch in flight. Frames that arrive while it is in flight are queued. When it lands, the queue is checked against the new cursor: drop everything ≤ cursor, apply cursor + 1 in order, and if the next frame is still ahead, make one more fetch.
pushwith seq = cursor + 1: apply it, cursor = seq. Seq ≤ cursor: drop. Seq > cursor + 1: a gap, so fetch.ownwith seq = cursor + 1 and a counter this client sent on this stream (§3.4): cursor = seq, nothing to apply. Anything else: treat asupdate(fetch).update: fetch, as today.- On a push stream the cursor moves only by frames and fetches. The POST's
Docs-Seqis not used there (noteOwnSeqand the native ≤ 1 s hold stay for non-push streams, i.e. old servers).
3.3 Sending: when nothing is in flight
> Send when nothing is on the wire and at least 50 ms have passed since > the last send started. While a send is on the wire, coalesce everything > typed into the next one, which goes when the answer arrives (and the 50 ms > have passed).
- Only after
hello, per connection. A client uses this rule only while its current stream for the document has saidhello. Otherwise it keeps today's 250 ms window. "Has saidhello" belongs to one connection and resets on every reopen. So a server restarted withDOCS_LIVE_PUSHoff sends clients back to 250 ms and toDocs-Seqon their next stream. A POST in flight across a reopen carries the old stream id; it arrives on the new stream aspushand is applied as nothing. Sending at once to a server without push is §4.1's "send at once, fetch" row: ~1.8× the CPU and more fetches. One native build talks to every team's instance, including lagged ones, so this is not only a rollback case. - On an expensive or constrained path (
NWPath.isExpensiveorisConstrained; on the web,navigator.connection.saveDataor acellulartype where reported), keep 250 ms (Paul, ruling 3). - Rate: uploads/s ≤ min(keys/s, 1 / (RTT + server time), 20). Measured at ~6 keys/s:
| RTT | Today, web | Today, native | Send when idle (50 ms floor) | A 12 keys/s burst | |---|---|---|---|---| | 20 ms | 3.0 | 3.6 | 6.1 | ≤ 12 | | 50 ms | 3.8 | 3.6 | 6.1 | ≤ 12 (1/RTT ≈ 15) | | 100 ms | 3.9 | 3.6 | 5.7 | ≤ ~8.5 (1/RTT) |
A 50 or 100 ms floor gives the same rate as none at typing speed. It only caps key-repeat and bursts on a LAN (≤ 20/s).
- Durability is unchanged: every keystroke reaches the outbox (native) or the queue (web) first. Save, close, blur and background still send at once.
- Native:
DocsOfflineAccount.sendIntervalbecomes 50 ms when the open model's stream has saidhello, andpaceno longer holds the drainer after a POST that leaves the lane non-empty. Web:save-queue.mjsgains the leading edge (schedule(0)when nothing is in flight and the floor has passed), switched on bylive-updates.mjsonhello.
3.4 Own updates: own, checkable
A client must be able to check an own frame. Adopting one wrongly skips an update for good, silently: seq N is exactly next, so no gap ever shows, and later updates that depend on it park invisibly. That would come from ordinary bugs (a stale id after a reconnect, the native drainer's "holds every entry" check being wrong once, two tabs) more than from forgery.
hellogives the stream a random id (16 bytes, base64url). The server binds it to the session that opened the stream. ADocs-Streamheader from a different session is ignored, as if absent.- A POST may carry
Docs-Stream: <stream id>.<counter>. The counter is the client's, one per POST on that stream. Store.ApplyUpdaterecords(doc, seq) → (stream id, counter, SHA-256 of the bytes)inside the transaction, before commit, in the hub's small per-document registry (the last 64). A stream that reads row N therefore always finds the entry (rows become visible only at commit). It writesownonly when the stream id matches and the row's bytes hash to the recorded hash. A seq reused after a rolled-back transaction can never match.- The client adopts
own N conly for a countercit sent on this stream and only at cursor + 1 (§3.2). Anything else is a fetch. - Native: the drainer is per account, the stream per open document. The model registers its stream id with
DocsOfflineAccountfor its lane. The drainer sends the header only when the open model holds every entry in the batch (the checkDocsModel.sentmakes today) and keeps the counter. Otherwise there is no header, and the model gets the bytes and applies them as nothing.
3.5 The server keeps a warm handle per active document
Today Store.ApplyUpdate replays the whole document for every POST. The rules for keeping the replayed core.Handle between POSTs:
- Taken under a per-document lock. POSTs to one document already serialise on the single SQLite writer.
- Applied before the transaction, as today's replayed handle is. - Any error from
Applydrops the handle. A rejection (RejectedError) answers 400 as today, but it is not clean. yrs integrates an update's structs one at a time, so an update whose later struct is refused (InvalidParent,ERR_APPLY) leaves the earlier ones in the store, and the core's transaction commits them. A kept handle would carry that content into the next snapshot with no row holding it (branch review #174, finding 1). -ErrUpdateLogFull, a trap orRecoveredError: also replay cold inside the same POST, then carry on as today. The cache never fails a POST that a replay would take. - A request cancelled mid-Apply drops the handle quietly and is not retried. - An "applied, not committed" flag set beforeApplycloses the handle on every way out short of a commit, a panic included. - Making the core apply into a scratch transaction it can roll back would make a refused update change nothing. That is a core change with its own ABI test, not part of this spec. - Committed, or dropped. Any failure after a successful
Applydrops the handle: the in-transaction permission check refusing (a writer revoked mid-request), a cancelled context, a database error, the team guard. The handle's seq advances only after commit. IfMAX(seq)inside the transaction is not the handle's seq, the row is still inserted (today's behaviour with a stale replay) and the handle is dropped. - Re-seeded at the snapshot cadence. When the handle is 256 rows past its snapshot, the POST does this, in order: 1. write the snapshot from the warm state at the handle's seq (D3's placement, unchanged); 2.
Applythe update to the same handle; 3. commit; 4. drop the handle.
The next POST replays from that snapshot. A failed snapshot write (outside team mode: logged, not fatal, as today) keeps the handle, and rule 2 is the backstop at 4,096. A warm handle therefore never retains more than ~257 updates, far from core.MaxRetainedUpdates (4,096). Without this, one typist reaches the cap in ~11 minutes and the POST answers 400, which save-queue.mjs treats as final.
- Memory, measured (
TestLivePushProbeWarmMemory, RSS per warm handle): 1.8 MB at 1 page, 2.7 MB at 20 pages, 16.5 MB at 200 edited pages. Cap: 128 MB of warm handles per process (from the handle's linear-memory size) and 64 handles, LRU. A single handle larger than the byte cap is not kept; that document takes the cold path every time. - Dropped on delete, restore, any change to the document's grants, team or sealing state (no sealed plaintext stays resident after access changes), after 60 s without a POST, and at shutdown (
hub.draincloses them). As built in slice 1a: - grants, revoke, visibility, delete, drain and close drop it; - sealing is activated offline with the app stopped; - team roster changes arrive from outside and drop nothing, and nor does a grant changed by a second process during a deploy overlap. That is retention for at most 60 s, not access: permission is checked on every POST and inside the transaction. Dropping on a roster refresh is a candidate for slice 1b, which touches the team guard anyway. - There is no version restore yet. When there is, it must drop the handle: a restore that rewrites rows could leaveMAX(seq)where it was, which rule 3 cannot see. - Swept by POSTs and by the stream's heartbeat.
stream.gohas no timer outside a live connection. Each POST sweeps the cache, and so does every open stream's 15 s heartbeat, which is a timer inside a live connection. A document whose last writer stopped while a tab still watches it is therefore dropped within ~75 s. With no stream and no POST, the instance hibernates within 15 minutes and the memory goes with it. - Two processes on one database (a deploy overlap) stay correct, because validity is checked inside the transaction.
3.6 Keeping a visible web copy live (Paul, ruling 2)
This rule is how long a visible, untouched tab may hold its instance awake. Paul ruled that visible tabs stay live. The bound and the reopen rule:
- A visible tab keeps its stream while it is visible, up to 8 hours since the last local activity (Paul's call, open question 1: 2 hours fixes his complaint equally and halves the awake time; nothing in the design depends on the value). Then it closes, and any activity reopens it. The clock resets on local activity and on
push/ownframes (real frames mean POSTs are keeping the instance awake anyway), never on heartbeats. - Hibernation (checked against
carlos/platform internal/activator): an instance hibernates when nothing is in flight and 15 minutes have passed since the last request. An open stream is in flight, so an untouched visible tab holds its instance for up to 8 h + 15 min, against 2 min + 15 min today. A tab left open on Friday evening releases it early on Saturday. A closed lid or a dead connection holds nothing: the client never reopens, and the server's 5-minute TTL stays the hard bound. The TTL stays 5 minutes for exactly that reason. - Hidden tabs keep today's 30 s close. A tab that is hidden when its stream ends stays closed; showing it is activity, which reopens it.
- Reopen after any end of the stream. The server has four ends (TTL, drain, the team lease deadline, and a failed write or authorisation check), and the network has more. A visible tab inside its 8 h reopens with
since=<cursor>after any end,byeor not.byeonly chooses the first delay: -ttlorlease: at once; -drain: 1–5 s with jitter, so a whole team does not reconnect in the same instant to a process that is still starting; - nobye(a failed check, the network, an old server): 1 s. - When the reopen fails. The tab first fetches
?since=<cursor>, which shows the statusEventSourcehides: - 401, 403 or 404: stop and show the access state, as today; - anything else (a 502 while the instance starts, a network error): capped exponential backoff with jitter, 1 s doubling to 60 s.
So a tab never retries a dead instance at a fast rate, and never for longer than its 8 hours.
- The same rule on a non-push stream (an old server, or
DOCS_LIVE_PUSHoff). There is nobye, so the TTL close arrives as an error and the tab reopens after 1 s. That fixes cause 7 everywhere, not only where push is on. Only the frames and the 50 ms floor depend onhello. - The server sends
bye ttl,bye leaseandbye drainbefore those three closes. Team-mode streams end at the lease deadline; every team instance runs in team mode, and all of them will after Alta.
3.7 Receivers
- Web (
live-updates.mjs):openStreamadds?push=1&since=<cursor>.pushframes go toonUpdatesin order (decode,prepareRemote,free,applyServerLog), with the queue rules of §3.2;helloswitches the save queue's leading edge on (§3.3) and checks the cursor (§3.1). A diverged document ignores frames as it ignores fetches today. A resync replaces the subscriber (cursor and stream together). - Native (
DocsModel.listen): the same events. Apushframe is applied withreplica.applyand published asrefreshdoes after its GET today (publish first, persist debounced), without the GET. A burst of queued frames is applied as oneapplyof their concatenation, as a?since=response is today.
3.8 Mobile, background, cellular
- The iPhone closes the stream in the background (phase 1) and reopens with
since=. What it missed arrives as frames, or as oneupdateif it is far behind, with no extra GET. - A remote change costs the radio one downstream frame instead of a frame, a request and a response.
- Expensive and constrained paths keep the 250 ms window (§3.3).
3.9 Why not a WebSocket
- Latency: none to gain. A change takes one trip up (POST) and one down (stream frame) either way. With HTTP/2 to the edge, the POST rides the same connection as the stream, with no new handshake.
- Cost: - rastrillo has no WebSocket helper, so a new dependency; - a hand-written Origin check on the upgrade; - auth and per-document authorisation on a long-lived socket; - a second reconnect, heartbeat and idle policy beside the stream's; -
NativeHTTPhas no socket either. - When it pays: presence (cursors, selections): many small, ephemeral, two-way messages.
3.10 Windows in one app
None today: on the Mac, one account has one window per document (DocsWindows.reserve). Out of scope.
4. Cost: are we DDoSing ourselves?
4.1 Today's paths (measured, revision 1)
Simulated typists against the real server at 20 pages (run-probe.py, loopback, ~6 keys/s each, each typist in its own document with one watcher). One run of 200 keys per row, on a machine at load 10–970, so treat these as ±20%:
| Typists | Policy | Uploads/s | Fetches/s | Server CPU | Allocation | |---|---|---|---|---|---| | 1 | today, native (250 ms) | 3.4 | 3.4 | 48 ms/s | 24 MB/s | | 1 | today, web (250 ms) | 2.9 | 5.1 | 42 ms/s | 20 MB/s | | 1 | send at once, fetch | 5.5 | 8.9 | 87 ms/s | 46 MB/s | | 5 | today, native | 15.7 | 15.7 | 211 ms/s | 111 MB/s | | 5 | send at once, fetch | 26.3 | 33.6 | 382 ms/s | 227 MB/s | | 20 | today, native | 58.2 | 57.6 | 714 ms/s | 407 MB/s | | 20 | send at once, fetch | 99.0 | 107.5 | 1,349 ms/s | 842 MB/s |
CPU profile (5 typists sending at once, 20 pages):
- per-POST replay: 19%;
- garbage collection, mostly the replay's ~8 MB per POST: 14%;
- SQLite with its WAL lock calls: ~25%;
- GETs: 3%;
- the stream's per-write authorisation: 4%.
4.2 The prototype (measured)
Branch proto/live-push implements the warm handle (§3.5 rules 2–4, lazy eviction) and the push stream (hello, push, own with the hash check, update fallback). It does not implement session binding, late answers, bye or the byte cap. Probe: 20 pages, sealed rows, ~6 keys/s, 150 keys per run, three runs each on fresh servers; median [range]. "Arrived" is the bytes in the watcher's hand. Add the receiver's apply and draw (web 5–10 ms, native 25–45 ms at 20 pages). The machine's load average was 180–850, which is where the wide ranges come from.
Server cost, loopback (CPU ms per second of typing; ms per upload; allocation):
| Case | Today (native 250 ms, fetch) | Push, cold replay | Push + warm handle | |---|---|---|---| | 1 typist | 42 ms/s; 11.5; 22 MB/s | 73; 12.0; 44 MB/s | 20 ms/s; 3.3; 1 MB/s | | 5 typists, own documents | 173; 10.3; 103 MB/s | 330; 11.6; 205 MB/s | 75; 2.6; 5 MB/s | | 5 typists + 5 watchers, one document | 436; 25.9; 165 MB/s | 678; 23.7; 263 MB/s | 421; 14.7; 12 MB/s | | 20 typists, own documents (one run) | 529; 9.3; 343 MB/s (p95 1,014 ms: saturating) | 928; 9.9; 647 MB/s (p95 802 ms) | 249; 2.3; 19 MB/s (p95 11 ms) |
Latency, 50 ms round trip (key → arrived, p50 / p95 ms):
| Case | Today, native | Today, web | Push + warm handle, 50 ms floor | |---|---|---|---| | 1 typist, 1 watcher | 246 / 369 | 271 / 414 | 56 / 67 | | 5 typists + 5 watchers, one document | 264 / 509 | – | 58 / 66 |
What this settles:
- The warm handle is the prerequisite. It cuts server CPU per upload 3.5× (11.5 → 3.3 ms) and allocation ~40×. With it, push and sending at once cost less CPU than today for typists in their own documents: - 20 against 42 ms/s for one typist; - 249 against 529 ms/s for twenty, where today's path saturates.
A shared document costs about the same (421 against 436). Without the warm handle, push and sending at once cost 1.6–1.9× today. So slice 1a ships first (§10).
- In a shared document the cost is the fan-out (finding 13): ~12 ms of server CPU per upload with 10 open streams, about 1.2 ms per stream per frame. That covers the authorisation re-check, the row read, the unseal and base64, and today's fetch path pays about the same per watcher. Slice 1b adds a per-document frame cache (each seq read and unsealed once, for every stream) and measures this case with and without it. If the authorisation re-check is most of what remains, it moves to at most once per second per stream, and at once on a grant change. That is a decision for 1b's review with the numbers, not a default.
- Push measured: 0 GETs from watchers, 0 echo fetches, and every own update arrived as
own. - Twenty typists at once in one instance cost ~0.25 of a core with the design, against ~0.5 today.
4.3 Requests, the edge, storage
- Requests through the edge (measured, real clients, 120 keys, 50 ms): - today web → web: 68 POSTs and 126 GETs (the watcher's 68, plus 58 of the sender's own updates fetched back); - today native → native: 72 POSTs and 72 GETs; - push with the 50 ms floor (projected; the prototype measured 0 GETs): ~115–120 POSTs and no GETs.
Each extra watcher costs a GET per upload today and nothing with push. Frames are bytes on a connection that is already open: ~80–100 bytes per keystroke per watcher.
- Storage (measured, sealed rows,
TestLivePushProbeRowSize): - a keystroke row costs ~180 bytes of database (16 bytes of update, the seal, the row and its indexes, snapshots amortised); - each commit writes ~25 KB to the local WAL (about six 4 KB pages: the row, its index,documents.updated_at, the suite feed's revision). That is local disk and checkpoint work: ~60 KB/s more per active typist than today. - Replicated bytes, measured in slice 1b (replica-bytes.py: Litestream v0.5.14, the versioncarlos/platformmain pins, local file replica, default 1 s sync; one typist for 60 s at 20 pages, sealed rows, two runs each):
| Pacing | Uploads/min | Replica bytes/min | Replica files/min | |---|---|---|---| | Today's native (250 ms) | ~210 | 490–610 KB | ~65 | | Push, 50 ms floor | ~360 | 835–860 KB | ~65 |
The review expected the replica to get about the same pages whatever the commit rate (LTX ships each changed page once per sync). Measured, it grows ~1.5×. The number of files (an S3 PUT each) is the same, about one per second. Per active typist that is ~+300 KB a minute: ~33 MB an hour of continuous typing today, ~51 MB with push. - No server-side coalescing of commits in this spec: it would cost the latency the spec removes, and the cost above is bytes, not requests. Open question 2 is back for Paul with these numbers. - The log grows ~3.9 MB per hour of continuous typing (today ~2.3 MB); compaction remains deferred (docs spec §4.1).
- Per instance: see §4.2. Nothing is shared between instances except the edge, which sees no more requests than today.
5. Limits and safety rails
- Max update over the stream: 32 KiB (raw). Larger goes as
update(fetch). That keeps every native SSE line well underNativeStreamLines' 256 KiB line and 1 MiB event limits. - Slow receivers. A stream never queues: it reads from the log, from its own cursor, when it can write. A stream more than 256 rows / 512 KiB behind gets one
updateand catches up by fetch. The write deadline (30 s) still ends a stalled connection. - Late answers, bounded. Clients keep one upload in flight, so the server can rate-limit by answering later. A session that has posted more than 30 updates to a document in the last second has its next answer delayed: - before it takes the document lock or the writer, never while holding either; - for at most 1 s; - ended by request cancellation and by
hub.draining(); - at most 2 answers per session may be waiting; beyond that,503withRetry-After: 1. The web queue retries a 5xx and the native drainer honoursRetry-After. Never a 4xx: the web save queue drops any 4xx batch. - Authorisation is re-checked once per flush (
nativeStreamAllowed, the team guard), not per frame. - Warm handles: 128 MB and 64 per process (§3.5).
6. Security
- Only a member who may read the document gets bytes. The stream route is the same reader-scoped route (
getDocumentForUpdates), every flush re-checks the session and the document, and a stranger gets the same 404. A reader's stream receives frames; the reader still cannot post. - The bytes are the rows
GET ?since=already serves the same person. Sealed rows are opened with the sameopenContentUpdate. owncannot cause a silent skip (§3.4): the stream id is bound to the session that opened it, the entry is matched by the row's bytes, and the client adopts only a counter it sent on that stream at cursor + 1. A forged or stale header yields apush(bytes applied as nothing) or a fetch, never an adopted seq the client does not hold.sinceandLast-Event-IDare parsed likeparseSince(400 on garbage). A cursor ahead of the log is caught byhello(§3.1).- A warm handle holds the document's decrypted state in memory for up to ~75 s after its last write (§3.5 rule 7), and is dropped at once on any access or sealing change. The process holds the content key anyway.
7. Compatibility and rollout
| Client \ Server | Old server, or new server with push switched off | New server | |---|---|---| | Old web / old native | today | today: no push=1, so seq-only update events and no hello; POST unchanged; the warm handle and late answers are invisible | | New web / new native | push=1 ignored, no hello: fetch, and the 250 ms window stays (§3.3) | push, the 50 ms floor |
Old native parses any data: line as an Int64. It never asks for push=1, so it never sees a frame.
8. Switches
DOCS_WARM_HANDLE(server): on by default once slice 1a is proven; off means today's cold replay per POST.DOCS_LIVE_PUSH(server): off meanspush=1is ignored, so every client goes back to today's path (fetch, 250 ms window) without a release.
9. Tests
9.1 CI, deterministic
- Go: - one POST yields exactly one flushed
pushframe per watcher, and no GET; -ownreaches only the poster's stream, and only with a matching session and hash; - frames come in seq order under concurrent POSTs; - resume fromsinceand fromLast-Event-ID(which wins); -hellocarries the current seq; - oversized and far-behind rows becomeupdate, andsentmoves; -bye ttl,bye lease(team mode) andbye drainbefore those closes; - a push stream withoutsincesends the connect-timeupdate; -hellocarries the log epoch, and the epoch rotates after an unclean start but not after a clean drain; - a reader's stream receives frames and its POST is refused; - access revoked between two frames ends the stream; - an old (non-push) client sees exactly today's events, checked with the native line parser's rules. - Go, warm handle: - more than 4,096 POSTs to one warm document, none refused (finding 1); - a writer revoked between apply and commit, after which the next snapshot equals a cold replay (finding 2); - a property test that warm and cold give the same state for random update sequences, with injected failures; - re-seeding at the snapshot cadence; - the byte and count caps; - dropping on delete, restore and grant change.
- JS (
live-updates.test.mjs,save-queue.test.mjs, fake clocks): - a key after idle is sent with zero wait; - keys coalesce while a send is in flight; - the 250 ms window stays withouthello; - uploads ≤ 1.2 × keys; - the queue rules of §3.2 andownadoption; - the reopen rule (§3.6): after any end,byechoosing the delay; a fetch first; stop on 401/403/404; backoff capped at 60 s; the 8 h clock reset by activity and frames, not heartbeats; the same on a non-push stream; -helloresetting per connection, and a POST in flight across a reopen. - Swift (
RealtimeSyncTests, fake clock): the same as JS, plusownonly when the model holds the batch, and the old-server path.
9.2 CI, timing (relative, never absolute)
The probe in-process with a 20 ms injected round trip, three runs. In the same process and the same runs:
- push's server-added p50 (measured minus injected) must be ≤ the fetch path's, best of three. Push removes a request, so it must not be slower.
- uploads must be ≤ 1.2 × keys.
It fails, and it never skips.
9.3 Release step
run-clients.shwith real web and native clients, at 0 and 50 ms, against the §2 targets.- Today's path (
DOCS_LIVE_PUSHoff) and push are run interleaved, three times each, in the same session (asrealtime/run-matrix.shdoes). - The result file, with the load average recorded, is committed beside the release.
- No load ceiling: this Mac has not met one in any run so far. Interleaving is what makes a loaded run comparable.
- A run that cannot be completed or recorded, or misses the targets, blocks the release. It is never skipped or passed.
10. Slices and deploy order
- Before native work starts: restore
RealtimeAuditE2ETests.testEndToEndRemoteUpdates(n = 0 since S1a: it observesprojection, which S1a made@ObservationIgnored; observeprojectionGeneration). - 1a, server: the warm handle alone, behind
DOCS_WARM_HANDLE, with rules 1–8 of §3.5 and the tests of §9.1. Deploy, then re-runload-p1/load-p20and the 5-typist, 5-watcher shared document against the real implementation. - 1b, server: push, behind
DOCS_LIVE_PUSH: -hello/push/own/update/bye; -Docs-Streamand the session binding; - late answers.
Deploy with the switch on for Paul's team. 1b is done when: - Paul's edge check (edge-timing.js) has been run on production, before slice 2 ships, since edge buffering is unverified; - the fan-out measurement (5 typists + 5 watchers in one document) has been re-run on the real implementation in team mode as well (guard.check() per flush), before deciding on the frame cache or on throttling the authorisation re-check; - replica bytes per minute of typing have been measured: LTX files of a local file replica on CARLOS' Litestream version, 1 s sync, today's pacing against the 50 ms floor.
- 2, web: the push receiver;
helloswitching on the leading-edge send (so it cannot go live before the push stream is checked on production); the visible-tab rule (§3.6). It ships with a server deploy, so it is ordered after 1b is checked. - 3, native: the push receiver in
DocsModel.listen, the 50 ms floor afterhello, stream-id registration,isExpensive/isConstrained. A native release after 1b is live. Independent of S1b (pagination).
11. Paul's edge check
native/benchmarks/live-push/edge-timing.js, pasted into the browser console on a scratch document. It works against today's server and a push server alike. Run it now for a baseline: it answers the open question (does the edge buffer the stream?) on today's server, because today's server already announces each upload on the stream. Run it again after slice 1b, when it also reports the own frame.
Instructions for Paul:
- Sign in to Docs in Safari or Chrome. Create a document named "Edge timing (scratch)" and open it.
- Open the console: Safari, Develop → Show JavaScript Console (turn on Settings → Advanced → Show features for web developers if Develop is missing); Chrome, View → Developer → JavaScript Console (Chrome may ask you to type
allow pastingfirst). - Paste the whole file and press Return. It takes about ten seconds and prints
DOCS EDGE TIMING { … }. Copy that and send it back. - Delete the scratch document. The script added three empty updates (two bytes each, no visible change) to its history.
The snippet only makes same-origin requests from that page. It sends no data anywhere else and changes nothing visible.
12. Open questions for Paul
- The bound for an untouched visible tab (§3.6). The spec uses 8 hours (a working day) as the default. 2 hours fixes the lag complaint equally and halves how long an instance stays awake. Unbounded is also possible. His call.
- Litestream traffic (§4.3, measured in 1b): sending at once replicates ~1.5× the bytes of today's pacing (835–860 against 490–610 KB per minute of one person typing; ~51 against ~33 MB an hour), with the same number of files (S3 PUTs). Fine as it is (recommended), or should the server coalesce one session's commits over a short window, at the cost of up to that window in latency?
Review findings (Claude Fable 5.2, #172) and where they are answered
| # | Finding | Answer | |---|---|---| | 1 | Warm handle reaches MaxRetainedUpdates; the web drops the save | §3.5 rules 2 and 4 (re-seed at the cadence, cold replay in the same POST); test in §9.1 | | 2 | Applied but not committed poisons the handle | §3.5 rule 3; test in §9.1 | | 3 | own can silently skip; the registry race | §3.4 (counter, session binding, hash, recorded inside the transaction), §3.2, §6; own wins on push streams | | 4 | bye alone does not fix the 2-minute close | §1.3 cause 7, §3.6 (Paul's ruling, the 8 h bound, bye on drain with jitter), question 1 | | 5 | Frames during a fallback fetch | §3.2 (queue and re-check), §3.1 (sent moves after update) | | 6 | Cursor ahead of the log; Last-Event-ID | §3.1 (hello carries the seq; Last-Event-ID wins; no id: on update) | | 7 | New client on an old server | §3.3 (the floor only after hello), §7 | | 8 | Warm-handle memory and eviction | §3.5 rules 5–8 (measured, byte cap, drops, lazy sweep) | | 9 | Projections, worst case not run | §4.2 (prototype: warm handle and push, 5 typists and 5 watchers in one document, three runs), labels throughout, §10 slice 1a re-run, §10 edge check as a condition | | 10 | The latency gate would flake | §9 (deterministic CI, relative timing, release step) | | 11 | Late answers need bounds | §5 | | 12 | Split slice 1, switches | §8, §10 (1a, 1b, the web's leading edge gated on hello) | | 13 | W watchers, W reads and unseals | measured in §4.2 (shared document); the cache decision follows from it | | 14 | Real per-row storage | §4.3 (~180 B per sealed row; ~25 KB of WAL per commit), question 2 | | 15 | Low Data Mode | §3.3, §3.8 (isConstrained) | | 16 | Two processes on one database | §3.5 rule 8; old-process streams get bye on drain (§3.6) | | 17 | More stream tests | §9.1 | | 18 | Restore the native e2e probe | §10 slice 0 |
Notes on the measurements
- Revision 2's prototype measurements: branch
proto/live-push,native/benchmarks/live-push/proto-table.py, and the probe testsTestLivePushProbeWarmMemoryandTestLivePushProbeRowSizethere. The raw summaries are innative/benchmarks/live-push/results-2026-11-26/proto/.
- The harness:
native/benchmarks/live-push/(gen-typing.mjs,run-probe.py,run-clients.sh,browser-probe.mjs,breakdown.py,server-costs.py,join.py),internal/docs/live_push_probe_test.goandnative/apple/Tests/DocsKitTests/LivePushLatencyTests.swift. Every probe skips unless its environment variable is set. The native probe needs the release test build with-DDOCS_PROBES -DDEBUG(ReplicaDirtyLogTestsuses a#if DEBUGhook; no other#if DEBUGexists in DocsKit). - Headless Chrome has no display link here, so "DOM updated" is the web figure; paint is at most one frame later. The native watcher timestamps the publication (when per-block drawing starts) and does not lay out pages (S1b's subject).
- The machine was shared and heavily loaded (load average 10–970); every CPU figure is ±20% and the end-to-end runs used the quietest windows.
- Not measured: the CARLOS edge end to end (needs a session), iPhone hardware, documents over 20 pages.
- Aside:
RealtimeAuditE2ETests.testEndToEndRemoteUpdatesno longer sees any publication (it observesprojection, which S1a made@ObservationIgnored), so it reports n=0; it should observeprojectionGeneration.
Re-review findings (Claude Fable 5.2 on 9319c64, #172) and where they are answered
| # | Finding | Answer | |---|---|---| | 1 | Team streams end at the lease deadline with no bye; reopen policy | bye lease; a visible tab reopens after any end, bye only chooses the delay; fetch first, stop on 401/403/404, backoff capped at 60 s (§3.1, §3.6, §9.1) | | 2 | Visible-tab rule on a non-push stream; hello per connection | §3.6 (the same rule, TTL close as error, 1 s reopen), §3.3 (hello per connection, the in-flight POST across a reopen), §9.1 | | 3 | WAL bytes are not replicated bytes | §4.3 rewritten (local WAL cost; the review's LTX reasoning attributed; CARLOS pins v0.5.14 on main), no coalescing, replica-bytes measurement in 1b's done list (§10), question 2 withdrawn pending it | | 4 | Eviction swept only by POSTs; a handle over the cap; the plaintext sentence | §3.5 rules 5 and 7 (heartbeat sweep, ~75 s; one handle over the cap is not kept), §6 sentence fixed | | 5 | Re-seed order | §3.5 rule 4: snapshot, Apply, commit, drop; a failed snapshot keeps the handle | | 6 | Gate details | §9.2 (push ≤ fetch path's server-added p50, best of three), §9.3 (interleaved A/B, no load ceiling, a run that cannot be recorded blocks the release) | | 7 | Connect-time update; restored log | §3.1 (connect-time update kept without since; log epoch in hello and Docs-Log-Epoch, rotated on any start without a clean-shutdown marker) | | 8 | 1b fan-out re-run in team mode | §10, 1b's done list |