New:Upstash has a remote MCP server

How to Resume AI SDK Streams After a Page Refresh with Upstash Redis

Cahid Arda OzCahid Arda Oz
7 min read

resumable-stream is a package by Vercel on which the AI SDK's guide on Chatbot Resume Streams is based.

Resumable streams allow users to refresh while they are getting a long response to their question from your AI chatbot. Normally, if you have a streamText route and use it with your app, the response would be lost upon the refresh. Even if the AI model is still generating a response on the server, the client doesn't have access to this response anymore and the next request may go to a different serverless instance.

The package gets around a million weekly downloads. It comes with support for node-redis and ioredis, both of which connect over TCP. For Upstash Redis, there are just some empty function stubs to implement your custom publisher and subscriber in the README.

@upstash/agentkit-resumable-stream implements these function stubs for Upstash Redis, allowing users to use Upstash Redis with resumable streams. It connects to Upstash Redis over HTTP, which allows running the same code in both serverless and edge environments. It also includes functionality to cancel generation from any instance.

How does resumable-stream resume an AI SDK stream?

A resumable stream keeps the model running on the server and uses Redis pub/sub to let a new request reconnect to the stream.

The initial request acts as the producer: it always consumes the entire stream, while buffering its output and waiting for readers to connect.

A subsequent request can ask the producer to resume the stream. It receives all buffered data immediately, followed by new chunks as they are generated.

The flow in a Next.js chat app is as follows:

  1. The POST request spins up the model and creates a resumable stream around it with a given ID. It saves the ID in the chat as activeStreamId.
  2. The producer connects to a Redis channel and stays alive even if the browser disconnects (by using Next.js after feature to prevent premature termination).
  3. On reload, useChat with the option resume: true triggers a GET request. The route reads the activeStreamId and asks the producer to resume the stream.
  4. The producer publishes the buffer and then any new chunks to the reader channel.
  5. On completion, the onEnd callback saves the messages and clears the activeStreamId.

If no reload happens (which is most of the time), the producer only runs a few setup commands. It publishes chunks only while a resumed reader is attached.

Install the Upstash provider

npm install @upstash/agentkit-resumable-stream resumable-stream

The package exports the Upstash publisher and subscriber, requestStop and createStopSignal. The stream context itself comes from resumable-stream/generic, so both packages get installed, and resumable-stream needs to be 2.2.10 or later. Create a database in the Upstash Console and copy its REST URL and token into your environment. Every function in the package defaults to Redis.fromEnv():

UPSTASH_REDIS_REST_URL="https://..."
UPSTASH_REDIS_REST_TOKEN="..."

The client: useChat with resume

The client is the same as in the AI SDK guide. resume: true makes useChat call /api/chat/[id]/stream on mount, and the transport sends only the chat ID and the new message:

// app/chat/[chatId]/chat.tsx
"use client";
 
import { useChat } from "@ai-sdk/react";
import { DefaultChatTransport, type UIMessage } from "ai";
 
export function Chat({ chat }: { chat: { id: string; messages: UIMessage[] } }) {
  const { messages, sendMessage, stop } = useChat({
    id: chat.id,
    messages: chat.messages,
    resume: true,
    transport: new DefaultChatTransport({
      prepareSendMessagesRequest: ({ id, messages }) => ({
        body: { id, message: messages[messages.length - 1] },
      }),
    }),
  });
 
  async function stopGeneration() {
    await fetch(`/api/chat/${encodeURIComponent(chat.id)}/stop`, { method: "POST" });
    await stop();
  }
 
  return <div>{/* your chat UI, with a Stop button that calls stopGeneration */}</div>;
}

The stop button calls the server before it stops the local stream. When using resumable streams, the AI SDK handles stop() like a disconnect. Therefore, unless the server takes action to stop the model, the model will still be running.

The POST route creates the stream

This route matches the AI SDK guide, with two changes: the resumable stream context gets the Upstash publisher and subscriber, and createStopSignal gives streamText an abort signal. readChat and saveChat are your own chat storage:

// app/api/chat/route.ts
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  generateId,
  streamText,
  toUIMessageStream,
} from "ai";
import { after } from "next/server";
import { createResumableStreamContext } from "resumable-stream/generic";
import {
  createStopSignal,
  createUpstashPublisher,
  createUpstashSubscriber,
} from "@upstash/agentkit-resumable-stream";
 
export async function POST(req: Request) {
  const { id, message } = await req.json();
  const messages = [...(await readChat(id)).messages, message];
  await saveChat({ id, messages, activeStreamId: null }); // save the user message, clear the old stream
 
  const streamId = generateId();
  const stop = createStopSignal(streamId); // aborts when the stop route runs, on any instance
 
  const result = streamText({
    model: "openai/gpt-5.4-mini",
    messages: await convertToModelMessages(messages),
    abortSignal: stop.signal,
  });
 
  return createUIMessageStreamResponse({
    stream: toUIMessageStream({
      stream: result.stream,
      originalMessages: messages,
      generateMessageId: generateId,
      onEnd: async ({ messages }) => {
        stop.dispose();
        await saveChat({ id, messages, activeStreamId: null });
      },
    }),
    async consumeSseStream({ stream }) {
      const streamContext = createResumableStreamContext({
        waitUntil: after,
        publisher: createUpstashPublisher(),
        subscriber: createUpstashSubscriber(),
      });
      await streamContext.createNewResumableStream(streamId, () => stream);
      await saveChat({ id, activeStreamId: streamId });
    },
  });
}

The stop signal and the resumable stream share the same stream ID because the stream ID is created before streamText.

The GET route resumes it

// app/api/chat/[id]/stream/route.ts
import { UI_MESSAGE_STREAM_HEADERS } from "ai";
import { after } from "next/server";
import { createResumableStreamContext } from "resumable-stream/generic";
import { createUpstashPublisher, createUpstashSubscriber } from "@upstash/agentkit-resumable-stream";
 
export async function GET(_: Request, { params }: { params: Promise<{ id: string }> }) {
  const { activeStreamId } = await readChat((await params).id);
  if (!activeStreamId) return new Response(null, { status: 204 });
  const streamContext = createResumableStreamContext({
    waitUntil: after,
    publisher: createUpstashPublisher(),
    subscriber: createUpstashSubscriber(),
  });
  const stream = await streamContext.resumeExistingStream(activeStreamId);
  if (!stream) return new Response(null, { status: 204 }); // finished or expired
  return new Response(stream, { headers: UI_MESSAGE_STREAM_HEADERS });
}

The second check covers a stream that finished between the time the chat is read and the time we resume it. Returning a 204 tells useChat there is nothing to resume.

The stop route ends it from any instance

// app/api/chat/[id]/stop/route.ts
import { requestStop } from "@upstash/agentkit-resumable-stream";
 
export async function POST(_: Request, { params }: { params: Promise<{ id: string }> }) {
  const { activeStreamId } = await readChat((await params).id);
  if (activeStreamId) await requestStop(activeStreamId);
  return new Response(null, { status: 204 });
}

The stopping is typically requested on a separate instance to where the model is running. requestStop will set a flag in Redis that lasts for an hour. createStopSignal polls Redis (by default once a second) and aborts the signal if it detects it.

This triggers streamText to end its stream, so onEnd is called (with isAborted: true) and the partial answer is saved while activeStreamId is set to null. Resumed readers see the stream finish.

What the Upstash provider changes

The package creates an Upstash publisher and subscriber for resumable-stream/generic. They fix some issues people had with default behaviour:

  • The data's wrapped in JSON. Upstash handles SUBSCRIBE via Server-Sent Events over HTTP. @upstash/redis parses SSE on newlines and JSON-parses each message, and resumable-stream's chunks have lots of newlines. To deal with this, every message is published as {"d":"<text>"} and unwrapped.
    • This also prevents a more subtle bug: if you sent a chunk containing only 42, it would come out the other side as the number 42 instead of a string.
  • Large replays are split. resumable-stream sends the entire buffer as a single message on resume, but if that message is too large for the request size limit, it's rejected and the reader silently loses the beginning of the response. The provider will split any messages over 256 KiB into ordered pieces on the same channel.
  • Publishes are queued and pipelined. The producer waits for each message to be published before reading the next chunk, so a resumed stream progresses only one chunk per round trip to Redis. To speed this up, the provider immediately resolves each publish, and instead maintains a per-channel queue of messages to be sent in order one pipeline request at a time. The DONE message is held until the channel has finished.
  • Stop works across instances. requestStop and createStopSignal implement the stop endpoint, which the AI SDK guide leaves as an exercise to the reader.

node-redis over TCP vs the HTTP provider

node-redis or ioredis (TCP)@upstash/agentkit-resumable-stream (HTTP)
ConnectionLong-lived TCP connections for the publisher and subscriberPlain HTTP requests; each subscription is one open HTTP request
Edge runtimesNeed TCP sockets, which edge runtimes restrictWork, because everything is HTTP
Publishing to a resumed readerOne awaited publish per chunkQueued and pipelined, in order
Replay larger than the request limitRejected, reader gets a partial answerSplit into 256 KiB pieces
Stop from another instanceYou build itrequestStop and createStopSignal

The native clients are great when you have a long-running Node.js server with a TCP Redis close by, while the HTTP provider is perfect when deploying the routes on Vercel Functions, edge runtimes, or any situation where you don't want to manage connections.

Commands per stream

Upstash bills per command, so it helps to know what each step costs:

StepCommands
Start a stream1 SUBSCRIBE and 2 SETs (plus 1 INCR with the idempotent resumableStream API)
Each chunk, while nobody has resumedNone
Each chunk, while a reader has resumed1 PUBLISH per reader (pipelining saves round trips, not commands)
Resume1 GET, 1 SUBSCRIBE and 1 PUBLISH, then 1 GET every 10 seconds while reading
Stop signal1 EXISTS per poll: one per second by default, about 31 for a 30-second answer
Stop request1 SET

There is also a pollIntervalMs option that can be passed to createStopSignal. The longer the interval, the less commands are used, but the more time the stop takes.

Limits

  • Messages are chunked by the provider well within the plan's max request size (10MB on Free and Pay as you go). This size can be changed with maxMessageBytes on createUpstashPublisher. Any message larger than the maximum request size is rejected by Upstash.
  • No commas in stream IDs; @upstash/redis parses messages as message,<channel>,<message>.
  • One HTTP request is kept open per subscription. That means one for the producer's generation and one per resumed reader.
  • Dropped subscriptions are not reopened.