> This page location: Functions > Use cases > Resumable agent streams
> Neon is a serverless backend platform for apps and agents: Lakebase Postgres for transactional data, authentication for user sign-in, a Data API for querying Postgres from the browser, S3-compatible object storage for files, long-running functions for APIs, agents, and webhooks, an AI gateway for LLMs, and realtime for syncing browser state with your database. Every service branches with your data for dev, test, and preview. Pricing: https://neon.com/pricing.md. Plans and limits: https://neon.com/docs/introduction/plans.md.
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

> Summary: Run a Durable Streams server in a Neon Function with @neon/durable-streams so agent and LLM output survives page refreshes and reconnects. Each stream has its own URL; writers append to it, and readers replay history and follow new output from a saved offset. The server uses Postgres for ordered writes, Neon Realtime for live delivery, and Object Storage for sealed history. Covers the durable-streams function template, database initialization, scheduled maintenance, and connecting an AI SDK chat UI.

# Build resumable agent streams with Durable Streams

Keep agent and AI chat output alive across page refreshes, dropped connections, and multiple readers.

Last updated: 2026-12-04

Most AI apps stream output over a single HTTP response. If the page refreshes or the connection drops, that response is gone, and so is everything it carried. The agent may still be running, but the browser has no way to reconnect and nothing to replay.

[Durable Streams](https://durablestreams.com/) is an open HTTP protocol that fixes this. Each stream has its own URL. Writers append to it, the server stores what they write, and readers replay history and follow new output from wherever they left off. Any reader can open the same stream, so a second tab, a phone, or a background worker can follow along too.

The `@neon/durable-streams` library runs a Durable Streams server inside your own [Neon Function](https://neon.com/docs/compute/functions/overview). Stream data lives in your project's Postgres database and Object Storage bucket, next to the rest of your app's data, and you control access with your app's own auth.

To see it working, try the [Durable Chat demo](https://br-frosty-sunset-bgioxtua-chat.compute.c-9.eu-central-1.aws.neon.tech/) ([source](https://github.com/samwillis/neon-durable-chat-demo)): start a long answer, refresh mid-response, and the output picks up where it stopped.

## How it works

The server uses four Neon services:

| Service | Role |
| - | - |
| [Neon Functions](https://neon.com/docs/compute/functions/overview) | Serves the Durable Streams HTTP API and holds live readers' long-poll and SSE connections open. |
| Postgres | Commits each append in a transaction, so writes are ordered and durable before the writer is acknowledged. |
| [Neon Realtime](https://neon.com/docs/realtime/overview) | Delivers committed appends to the function as they happen, so live readers get new output without polling. |
| [Object Storage](https://neon.com/docs/storage/overview) | Holds sealed history. A maintenance job moves older appends out of Postgres into immutable objects. |

Realtime is the fast path. Postgres and Object Storage are the source of truth: when a live connection drops or a reader falls behind, the function replays from stored history and subscribes again.

A stream supports six operations:

| Operation | Request | What it does |
| - | - | - |
| Create | `PUT /v1/stream/<path>` | Create a stream, optionally with initial data |
| Append | `POST /v1/stream/<path>` | Add data, optionally closing the stream |
| Read | `GET /v1/stream/<path>?offset=...` | Return a page of history from an offset |
| Follow | `GET` with `live=long-poll` or `live=sse` | Wait for, or continuously receive, new data |
| Inspect | `HEAD /v1/stream/<path>` | Return metadata |
| Delete | `DELETE /v1/stream/<path>` | Remove the stream |

The protocol also covers idempotent producers (retried appends never duplicate), JSON mode, stream closure and expiry, forks, and webhook subscriptions. See the [Durable Streams protocol](https://durablestreams.com/) for the full interface and client libraries.

## Before you start

- A Neon project on **Postgres 18** in a region that supports Functions: AWS US East (Ohio) (`aws-us-east-2`), AWS US East (N. Virginia) (`aws-us-east-1`), AWS Europe (Frankfurt) (`aws-eu-central-1`), or AWS Asia Pacific (Singapore) (`aws-ap-southeast-1`).
- Node.js 24 and the latest [Neon CLI](https://neon.com/docs/cli/install). Upgrade with `npm install -g neon@latest`.
- A local directory [linked](https://neon.com/docs/cli/link) to the project.

**Warning: Enabling Realtime restarts your computes**

Enabling Realtime turns on logical replication, which restarts the branch's computes. On an existing project, schedule this for a time when a brief interruption is acceptable.

## Set up the server

The `durable-streams` [function template](https://neon.com/docs/compute/functions/templates) gives you a working server with bearer-token authentication, an authenticated health check, and scheduled maintenance. It doesn't run a model or agent; you add your own producer.

## Enable Realtime

Enable Realtime and pull its credentials before you add the template, so they're available on the first deploy:

```bash
neon login
neon link
neon realtime enable
neon env pull --service postgres --service realtime
```

This writes `NEON_REALTIME_URL` and `NEON_REALTIME_SECRET` to `.env.local`.

## Add the template

```bash
neon functions new durable-streams --slug durablestreams --install
```

The CLI writes `functions/durablestreams/index.ts`, installs the pinned dependencies, and declares the function in `neon.ts`. `--install` makes it install even when no terminal is attached, for example when a coding agent runs the command.

## Create an access token

The template authenticates callers with a single bearer token. Generate one and append it to `.env.local`, keeping the values already there:

```bash
export DURABLE_STREAMS_TOKEN=$(openssl rand -hex 32)
echo "DURABLE_STREAMS_TOKEN=$DURABLE_STREAMS_TOKEN" >> .env.local
```

The token must be 32 to 1024 characters. It grants every stream operation, so keep it on your backend and out of the browser.

## Declare the services

Add Realtime and a private bucket to `neon.ts`, keeping its existing `functions` entry:

```ts filename="neon.ts"
preview: { realtime: true },
buckets: { 'durable-streams': { access: 'private' } },
```

Then check that the maintenance trigger is there. Some CLI releases don't scaffold template triggers, so add it if it's missing:

```ts filename="neon.ts"
triggers: {
  'durable-streams-maintenance': {
    type: 'schedule',
    function: 'durablestreams',
    cron: '* * * * *',
    functionPath: '/_maintenance',
  },
},
```

The template expects a `durable_streams` schema and a `durable-streams` bucket. If you change either name, change it in both the function and the initialization step below.

## Deploy

```bash
neon deploy --env .env.local
neon env pull
```

The first deploy provisions the bucket and trigger. `--env .env.local` forwards your token and the Realtime variables to the function. `neon env pull` refreshes the service credentials in `.env.local` without removing your token.

The function rejects stream requests until you initialize the database in the next step.

## Initialize the database

Run this once from your project root. It creates the `durable_streams` schema using the direct (unpooled) connection, with the same branch and bucket as the function:

```bash
node --env-file=.env.local --input-type=module <<'JS'
import { Pool } from 'pg';
import { migrate } from '@neon/durable-streams/migrations';
import { createS3ChunkStorage } from '@neon/durable-streams/s3';

for (const name of ['DATABASE_URL_UNPOOLED', 'NEON_BRANCH_ID', 'AWS_ENDPOINT_URL_S3', 'AWS_REGION']) {
  if (!process.env[name]) throw new Error(`Missing initialization configuration: ${name}`);
}
const databaseUrl = new URL(process.env.DATABASE_URL_UNPOOLED);
databaseUrl.searchParams.set('sslmode', 'verify-full');
const pool = new Pool({ connectionString: databaseUrl.href, max: 1 });
const objects = createS3ChunkStorage({
  endpoint: process.env.AWS_ENDPOINT_URL_S3,
  region: process.env.AWS_REGION,
  bucket: 'durable-streams',
});
try {
  await migrate(pool, {
    schema: 'durable_streams',
    environmentId: process.env.NEON_BRANCH_ID,
    storageIdentity: objects.identity,
  });
  console.log('Durable Streams initialized');
} finally {
  objects.close();
  await pool.end();
}
JS
```

Ordinary requests never create tables. Running this again validates the existing schema and keeps your stream data.

## Write and read a stream

Start the function locally:

```bash
neon dev
```

Set the URLs, then create a stream, append to it, and read it back. To test the deployed function instead, get its URL with `neon functions get durablestreams`.

```bash
export FUNCTION_URL=http://localhost:8787
export STREAM_URL="$FUNCTION_URL/v1/stream/example"

curl --fail-with-body "$FUNCTION_URL/health" \
  -H "Authorization: Bearer $DURABLE_STREAMS_TOKEN"

# Create a stream with initial data
curl --fail-with-body -i -X PUT "$STREAM_URL" \
  -H "Authorization: Bearer $DURABLE_STREAMS_TOKEN" \
  -H 'Content-Type: text/plain' --data-binary 'hello'

# Append more data
curl --fail-with-body -i -X POST "$STREAM_URL" \
  -H "Authorization: Bearer $DURABLE_STREAMS_TOKEN" \
  -H 'Content-Type: text/plain' --data-binary ' world'

# Replay the whole stream
curl --fail-with-body -i "$STREAM_URL?offset=-1" \
  -H "Authorization: Bearer $DURABLE_STREAMS_TOKEN"
```

Each read returns a `Stream-Next-Offset` header. Save it, append again, and read with `?offset=<saved-offset>` to get only the new data. Treat offsets as opaque strings, and keep reading pages until the response includes `Stream-Up-To-Date: true`.

To follow new appends live, open a reader in one terminal and append from another:

```bash
curl --fail-with-body -N "$STREAM_URL?offset=now&live=sse" \
  -H "Authorization: Bearer $DURABLE_STREAMS_TOKEN"
```

`offset=now` starts at the current end of the stream. To resume after a disconnect, pass the last offset you saved instead.

## Connect an AI chat UI

The server works with any Durable Streams client. To make an AI chat session survive refreshes, use a Durable Streams transport for your AI framework:

- [Vercel AI SDK transport](https://durablestreams.com/vercel-ai-sdk)
- [TanStack AI transport](https://durablestreams.com/tanstack-ai)

Point the transport at your function's `/v1/stream` URL, and save the stream's identity so the browser can reconnect after a refresh. Keep generation running on the server when a reader disconnects: Durable Streams keeps committed output, but it doesn't restart a crashed agent or model call.

The [Durable Chat demo](https://github.com/samwillis/neon-durable-chat-demo) is a complete example with Claude Haiku, Durable Streams, and Neon Functions.

## Before you go to production

The template is a starting point for one trusted backend. Before you open it to real users:

- **Replace the auth hooks.** The template's single token grants access to every stream. Replace both `authenticate` (who's calling) and `authorize` (whether they can read or write a given stream) with your app's identity and per-stream permission checks. Derive the tenant from verified credentials.
- **Allow browser origins explicitly.** For browser access, set `allowedOrigins` on the server and use short-lived credentials. Keep the Realtime and storage secrets on the server.
- **Keep the maintenance trigger.** Appends start background maintenance, but the every-minute trigger recovers interrupted work and seals history during quiet periods. Check it with `neon triggers list` and `neon logs query --source function --since 1h`.
- **Plan for branches.** A new branch created from one with an existing installation needs the library's branch adoption and recovery procedure before it serves traffic.
- **Size for your workload.** Tune the database pool, live-reader limits, and maintenance capacity for your traffic.

Webhook subscriptions and physical deletion of sealed objects are off in the template. See the library's operator and recovery guides before you turn them on.

## Add Durable Streams with an AI agent

To add Durable Streams to an existing app with a coding agent, start from a prompt like this:

```text
Add resumable agent output to this app using Durable Streams on Neon.

1. Read the README and AGENTS.md at
   https://github.com/neondatabase/neon-pkgs/tree/main/packages/durable-streams
   and use the function template as the deployment reference:
   https://github.com/neondatabase/examples/tree/main/registry/durable-streams
2. Use Node.js 24 and check that my Neon project uses Postgres 18 in a region
   that supports Neon Functions. Ask me before enabling Realtime, because it
   turns on logical replication and restarts computes.
3. Create a private Object Storage bucket for sealed chunks.
4. Deploy the Durable Streams handler as a Neon Function. Wire its authenticate
   and authorize hooks to this app's existing auth, and configure allowedOrigins
   for browser access. Keep service credentials on the server.
5. Run the library's migrations as an explicit deployment step, using a direct
   (unpooled) connection.
6. Add a cron Function Trigger that runs maintenance every minute.
7. Connect the chat UI with the Durable Streams transport for our AI framework
   (Vercel AI SDK or TanStack AI). Keep generation running when a reader
   disconnects, and save the stream identity needed to reconnect after a refresh.
8. Verify: create a stream, append to it, read it back with offset=-1, then
   reload the page mid-response and confirm the output resumes without duplicates.
```

## Related resources

- [`@neon/durable-streams` library](https://github.com/neondatabase/neon-pkgs/tree/main/packages/durable-streams): configuration, architecture, operations, and recovery
- [`durable-streams` template source](https://github.com/neondatabase/examples/tree/main/registry/durable-streams)
- [Durable Streams protocol](https://durablestreams.com/)
- [WebSockets and SSE on Neon Functions](https://neon.com/docs/compute/functions/websockets)
- [Schedule a function](https://neon.com/docs/compute/functions/triggers/schedule)
- [Neon Realtime](https://neon.com/docs/realtime/overview)

---

## Related docs (Use cases)

- [Backend API for a frontend app](https://neon.com/docs/compute/functions/frontend-api)
- [AI agents](https://neon.com/docs/compute/functions/agents)
- [WebSockets and SSE](https://neon.com/docs/compute/functions/websockets)
- [Build an MCP server](https://neon.com/docs/compute/functions/mcp-server)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/docs/compute/functions/durable-streams"}` to https://feedback.neon.tech/ (no auth required).
