resumable-stream is the library behind the AI SDK’s
Chatbot Resume Streams. While a
model generates an answer, it keeps the stream reachable through Redis pub/sub, so a client that
reloads the page, loses its connection or opens the chat on another device picks up the same
answer where it is, instead of losing it or starting a new generation.
Its built-in providers use the redis and ioredis clients, which hold a TCP connection open. That
does not fit serverless and edge functions, where every invocation is short-lived and some
runtimes cannot open TCP sockets at all. @upstash/agentkit-resumable-stream is a publisher and
subscriber for resumable-stream on @upstash/redis, which talks to
Redis over HTTP, so it runs anywhere fetch does. It also adds a stop signal that works across
instances, since the request that stops a generation rarely reaches the instance that runs it.
| Import | Feature |
|---|---|
createUpstashPublisher, createUpstashSubscriber | The Publisher and Subscriber you pass to resumable-stream/generic’s createResumableStreamContext. |
requestStop, createStopSignal | Stop a generation from any instance, through an AbortSignal the model call listens to. |
Install#
resumable-stream 2.2.10 or later is a peer dependency; you import its context from
resumable-stream/generic. @upstash/redis is only needed for your own code, such as the chat
store below.
AgentKit reads UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN from the environment by default.
Pass your own @upstash/redis client as redis to any function to use a different one.
How to resume AI SDK streams in Next.js#
This is the AI SDK’s Chatbot Resume Streams flow on the App Router, laid out like the example app:
| File | What it does |
|---|---|
lib/chat-store.ts | Stores each chat’s messages and activeStreamId. |
app/api/chat/route.ts | POST: generates the answer into a resumable stream. |
app/api/chat/[id]/stream/route.ts | GET: resumes the chat’s active stream. |
app/api/chat/[id]/stop/route.ts | POST: stops the chat’s active stream, from any instance. |
Store the chat#
The resume and stop routes need to know which stream belongs to a chat. Store its id as
activeStreamId on the chat record, next to the messages, as the AI SDK docs do. This store keeps
one Redis hash per chat:
Any store works, as long as it is shared: the resume and stop routes usually run on a different
instance than the one that started the stream, so activeStreamId cannot live in memory.
On the client, turn resuming on in useChat, and send only the chat id and the new message, which
is what the POST route below reads:
Start the stream#
The POST route generates the answer and hands a copy of its SSE stream to resumable-stream
through consumeSseStream. The context comes from resumable-stream/generic, with the Upstash
publisher and subscriber. The route also creates a stop signal for the stream and passes it to
streamText as abortSignal.
waitUntil: after keeps the function alive until the stream is finished, after the response has
been sent. On a long-running server where nothing is suspended, pass waitUntil: null.
Resume the stream#
With resume: true, useChat calls GET /api/chat/[id]/stream when it mounts. The route looks up
the chat’s active stream and resumes it, or answers 204 when there is nothing to resume.
Stop the stream#
useChat’s own stop() only drops the current tab’s connection; with resumable streams the
generation keeps running for resumed readers. A stop button calls a route instead, and
requestStop sets a flag in Redis that the producer’s createStopSignal picks up on whichever
instance it runs.
The stopped streamText ends its stream, so onEnd still runs (with isAborted: true), saves the
partial answer and clears activeStreamId, and every reader sees the stream finish.
createStopSignal(streamId, { redis?, pollIntervalMs? }) returns { signal, dispose }. It checks
the flag once right away and then every pollIntervalMs (1000 by default) until the flag is set or
dispose() is called, so always call dispose() when the generation ends.
requestStop(streamId, redis?) writes the flag, which expires after an hour.
The publisher and subscriber#
createUpstashPublisher(redis?, { maxMessageBytes? })returns aresumable-streamPublisher.maxMessageBytesdefaults to 256 KiB.createUpstashSubscriber(redis?)returns aresumable-streamSubscriber.
Both default to Redis.fromEnv(). Pass them as publisher and subscriber to
createResumableStreamContext from resumable-stream/generic, alongside its other options
(waitUntil, keyPrefix, doneWatchdogIntervalMs).
Always use the two together. Upstash delivers SUBSCRIBE messages as Server-Sent Events, which
@upstash/redis splits on newlines and JSON-parses, while resumable-stream’s chunks are full of
newlines. The publisher wraps every message in a JSON envelope, {"d":"<text>"}, and the subscriber
unwraps it, so a message arrives exactly as it was sent.
The publisher also handles the problems of running resumable-stream over HTTP:
- Large replays are split. On resume,
resumable-streampublishes everything generated so far as one message, which can exceed the request size your plan allows (vercel/resumable-stream#55). Messages overmaxMessageBytesgo out as ordered pieces on the same channel, and the reader gets the same text in more chunks. - Publishes are pipelined. The producer waits for each publish before it reads the next chunk, which would cost one round trip per chunk (vercel/resumable-stream#52; an upstream fix, vercel/resumable-stream#57, is pending). Publishes are queued per channel and resolve at once; the queue sends them in order, one pipeline request at a time, and the final DONE message waits until its channel is flushed.
- Publishes never reject.
resumable-streamawaits them inside the producer’s read loop, so a rejection would freeze the original reader’s stream as well. A failed send is logged once and the rest of that channel’s messages are dropped: that resumed reader is cut off and closed byresumable-stream’s DONE watchdog, while the producer and other readers carry on.
Cost in commands#
- Starting a stream is a SUBSCRIBE and two SETs (plus an INCR if you use
resumableStreaminstead ofcreateNewResumableStream). Chunks are only published while someone has resumed the stream, one PUBLISH each; pipelining saves round trips, not commands. - Resuming is a GET, a SUBSCRIBE and a PUBLISH, and a resumed reader GETs the stream’s status
every 10 seconds (
doneWatchdogIntervalMs). createStopSignalis one EXISTS perpollIntervalMs: one per second by default, about 31 for a 30-second answer. RaisepollIntervalMsto trade stop latency for fewer commands.requestStopis one SET.
A subscription holds one HTTP request open per channel: the producer’s for the whole generation, and one for each resumed reader.
Limits#
- Acks must arrive within a second. When a reader resumes,
resumable-streamasks the producer for the stream so far and waits one second for an answer. If none comes and the stream has not finished,resumeExistingStreamfails withTimeout waiting for ack. The answer takes a PUBLISH from the reader, a delivery to the producer’s subscription and a PUBLISH back, so keep the database in the same region as your functions. - A dropped subscription is not reopened. If the producer’s subscription drops, later resumes
of that stream time out; if a reader’s drops, that reader stops receiving chunks. The generation
itself and its
onEndare not affected. - Stream ids cannot contain a comma, because of how
@upstash/redisparses subscription messages. Ids fromgenerateId()never do.
Example#
The resumable stream demo is a Next.js chat with the files above. It stores chats in Upstash Redis and falls back to a scripted model without an OpenAI key, so you can reload mid-answer, follow the same answer in a second tab, or stop it from another tab or server instance.