ADR-0027: Resuming an answer after a dropped connection
- Status: Accepted on 2026-11-25 (task z1), as built by r1, r2, r3a and r3b (below). Decision 5's check on Vercel is still open: it needs a preview deployment, and is a step before 0.6 is released.
- Date: 2026-11-23
- Evidence: spike S7, question 6 and probe p5 (findings); the tasks' tests (below).
Context
When a visitor's connection drops in the middle of an answer (a train tunnel, a phone switching networks, a proxy timeout), the chat shows an error and the rest of the answer is lost to them, although the server finishes it: stream-turn.ts runs the model call on the turn's deadline signal, not the request's, and the finished answer lands in the conversation. Today the visitor gets it back only by reloading.
S7 asked whether resume belongs in the ConversationStore (ADR-0024). It doesn't: resume needs the protocol events of a running turn for a few minutes, written at the rate of text deltas, with a way to wake a waiting reader. The conversation store keeps model items for months and is written once per step. The OpenAI default, which has no store of ours, needs resume too.
S7's Postgres prototype worked (400 deltas written one by one in 186 ms, or in 20 batched flushes in 12 ms; 150 events read in 2.2 ms; a LISTEN/NOTIFY wake-up in 6 ms), but it needs a listening connection per waiting reader, which serverless Postgres poolers handle poorly.
Decision
-
A separate port,
TurnEventLog, shaped likeRateLimitStore:append(turnId, events),read(turnId, afterSeq)andwait(turnId, afterSeq, timeoutMs), with a time to live of the turn timeout plus a grace period, after which a turn's events are gone;- it holds protocol events only, numbered per turn, never raw provider events (ADR-0002);
- the turn writes them in batches (a flush every few events or milliseconds, the exact numbers set by the implementing task), never one write per delta.
-
Implementations:
memoryTurnLog(), the default: bounded in size and time. A reconnect resumes only when it reaches the same instance; otherwise the client falls back to reloading history, which is today's behaviour.upstashTurnLog({ redis })in@boldare/askdare-upstash, next to the rate-limit store: a Redis stream per turn (XADD,XRANGE,PEXPIRE), entry IDs<seq>-0, each append and each read oneEVAL(the sequence check, the batch and the expiry are atomic). Upstash's REST API doesn't supportXREAD BLOCK(its Redis compatibility page: streams are supported "except blocking versions of XREAD and XREADGROUP"), sowaitpolls, by default every 150 ms (pollMs). The writer flushes at most every 100 ms, so a resumed reader sees a batch at most 150 ms plus one round trip after it is written: under about 250 ms while the database is in the app's region (round trips of tens of ms), at about 7 commands a second per waiting reader. Not yet measured against a real database: the add-on's tests have a gated latency check (ASKDARE_TEST_UPSTASH=1).- Postgres (an unlogged table with batched flushes) is not in 0.6. The port lets a site that runs only Postgres add it later.
- Chosen in
createChatHandler({ resume: { log } }), on the server only.
-
Protocol (additive within v1):
- Every event frame of
POST /messagescarries an SSEid:with its sequence number. - A new
POST /resumetakes{ botId, resumeToken, messageId, after }and answers an event stream: the events afterafter, then the live ones untilmessage.endorerror. The client reads it withfetch, as it doesPOST /messages, so this replaces theLast-Event-IDheader thatEventSourcewould send. - The turn is found from the conversation in the visitor's resume token, never from the request alone. A turn of another conversation, or one whose events expired, answers
404withnot_found; the client then reloads history.
- Every event frame of
-
The client retries a stream that ends without
message.endorerrorthroughPOST /resumea few times with backoff, then reloads history. Text already shown stays; resumed events continue it without duplicates, since each carries its sequence number. -
Keeping the turn alive: a turn has to keep running after its response closes. The handler already has a
waitUntiloption. The implementing task verifies this on Vercel (after()orwaitUntil) and on Heroku; a platform where it fails gets no resume, and the docs say so.- Long-running Node.js (
next start, as on Heroku): verified bye2e/resume.spec.tsagainst the production build (r3a): a stream dropped mid-answer resumes with the rest, and the turn finishes upstream. - Vercel: verified. The turn's remaining work (the model call, the log's last flush, the hooks) is handed to Next.js
after(), which on Vercel extends the function withinmaxDuration. It was checked on 2026-11-26 on askdare.vercel.app (Vercel withupstashTurnLog()): streams cut after 1, 5, 12 and 30 text deltas each resumed with every event once, in order, endingcompleted, and the text matched the stored answer.
- Long-running Node.js (
-
Privacy: the log holds answer text for minutes. The implementations log nothing about the values they hold, and
docs/privacy.mdnames the log and its time to live. -
Public surface (added to ADR-0006 when this is accepted):
@boldare/askdare: theTurnEventLogport withTurnEvent, andmemoryTurnLogwithMemoryTurnLogandMemoryTurnLogOptions;@boldare/askdare/next: theresume: { log }option ofcreateChatHandler, typedChatHandlerResumeOptions;@boldare/askdare/testing:turnEventLogContractandTurnEventLogContractOptions(called as(name, create, { describe, it, expect, ttlMs?, elapse? })since z1, like the other suites);@boldare/askdare-upstash:upstashTurnLogandUpstashTurnLogOptions;- the protocol: the
id:field of event frames andPOST /resume.
The batching writer stays internal: only the server writes turns.
As built (r3a)
- The turn's key in the log is an HMAC (the token service's pseudonym key) of the bot, the conversation and the answer's
messageId.POST /resumederives it from the conversation in the verified resume token and themessageIdin the body, so another conversation's answer can't be named, and a shared log holds no conversation IDs. - Numbering: every event of
POST /messagesis numbered from 1, frames included when there is no log. Logging starts once the conversation is known, with any events sent before it, and goes on after the visitor left. The log is flushed right aftermessage.start(the first moment a client can resume) and at the end of the turn insidewaitUntil. With output checks, only what was released to the visitor is logged. - Time to live: the bot's
turnTimeoutMsplus one minute, refreshed by each batch. - A failed append is tried twice more, the same batch in order (after 200 and 400 ms), so a passing error doesn't leave the log short of the answer's end. After that the writer stops logging the turn, and a resume of it ends without
message.endafter the bot's turn timeout; the client then reloads history. POST /resumechecks same origin, the access token, the resume token's owner, the conversation store's owner and its own rate limit (30 per visitor per minute). It reads from the event beforeafter, so a client that already sawmessage.endorerrorgets an empty stream at once. The resume tokens the turn logged (inconversation.createdandmessage.end) name whoever started it, so it sends one issued for the session that resumes in their place: a visitor who signed in during the answer gets their own, not the anonymous one (0.6.x). It then waits for live events until the answer ends, the events expire (the stream ends, and the next attempt answers404), or the bot's turn timeout passes.
As built (r3b)
- The client (
chat/chat-client.ts) keeps the last eventidand the answer'smessageId, and ignores an event whoseidisn't above the last one. A stream that ends withoutmessage.endorerror, fails, or trips the 45 s watchdog is resumed after 0.5, 2 and 8 s: three attempts in a row that bring nothing new, ten in all for one answer, well under the server's 30 per minute. A turn the chat aborted itself is never resumed. - Giving up: any status other than
200from/resume(a404doesn't forget the conversation), the attempts running out, or a drop beforemessage.start. The store then loads the latest history page and replaces only what follows the visitor's last message, so older pages and the oldest message shown stay. It does so only when the page's last visitor message is the one sent and its answer isn't the one shown before it; otherwise the chat shows the connection error as before. - The status is the existing
activity, set tostatus.reconnectingand announced politely byStatus: no new state field or React code. - Size: about 420 bytes gzipped. The room came from:
- a missing
/* @__PURE__ */onmemo()inmarkdown.tsx, which kept the Markdown renderer in headless pages (−1.2 KB); - the client's English fallbacks for its own errors, which never showed because the store always passes the bot's full dictionary;
- the React build cutting the bundled marked down to its classes (
scripts/marked-lexer-only.ts): we use onlyLexer, but marked's default instance andmarked()kept its Parser and Renderer in the entry (about −3.1 KB).src/marked-lexer-only.test.tschecks that the cut Lexer reads markdown exactly as marked's.
- a missing
- Measuring:
react-size.mjsgzips with Node's zlib. Official Node builds (CI) bundle zlib 1.3.1; a Node linked against an older system zlib (1.2.12) measured this entry 112 B smaller from the same bytes. CI's figure is the one that counts. - Checked by unit tests of the client and the store, and
e2e/resume.spec.ts: the widget and the chat inside a page finish an answer whose stream was cut mid-answer, and take it from the history when/resumeanswers404.
Evidence
turnEventLogContractpasses formemoryTurnLog()and, against a fake Redis that runs the same two scripts, forupstashTurnLog()(r1, r2). WithASKDARE_TEST_UPSTASH=1it also passed, wake-up check under 250 ms included, against Redis 7.4 behind Upstash's REST proxy (serverless-redis-http), and the scripts ran on Upstash itself in the Vercel check below. The contract itself hasn't been run against an Upstash database directly.e2e/resume.spec.tsagainst the production build (next start): the protocol driven withfetch(r3a), then the widget and the chat inside a page finishing an answer whose stream was cut mid-answer, and taking it from the history when/resumeanswers404(r3b, 20 of 20 with--repeat-each 5).- Resume on Vercel with
upstashTurnLog()(decision 5): checked on 2026-11-26 on askdare.vercel.app (Vercel withupstashTurnLog()): streams cut after 1, 5, 12 and 30 text deltas each resumed with every event once, in order, endingcompleted, and the text matched the stored answer.
Consequences
- A dropped connection no longer costs the visitor the answer, on hosts where the turn outlives its response and a shared log is configured.
- Sites on several instances need Upstash (which many already run for rate limits) for resume to work across instances.
- Each turn writes its events a second time, into the log. Batching keeps that to a few writes per turn.
- The client gets a reconnect path that needs tests for duplicates, gaps and expired turns.
Alternatives considered
- Resume inside
ConversationStore: a different lifetime and write rate, and the OpenAI default would get no resume. - Postgres as the main implementation: a listening connection per waiting reader doesn't suit serverless poolers. It stays possible as a later adapter.
- Only reloading history after a drop: that's today. It works only once the turn has finished, and shows nothing in between.
- Resuming at OpenAI (a streamed background response, resumed with
starting_after, per the background mode guide): it exists only on OpenAI, only for responses OpenAI stores, its docs warn of a later first token, and it resumes provider events, which we would still have to map again for the client.