---
title: Rethinking streaming for agents
description: Agents need Durable Streams for long-lived output. Run them on Neon
excerpt: >-
  When an agent works on a task for five minutes, it streams its progress back
  to the browser the whole time: tokens, tool calls, intermediate results. What
  happens if, three minutes in, you refresh the page?
date: '2026-12-04T12:00:00'
category: product
categories:
  - product
authors:
  - sam-willis
cover:
  image: https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/cover.jpg
  alt: Rethinking streaming for agents
isFeatured: false
seo:
  title: Rethinking streaming for agents - Neon
  description: Agents need Durable Streams for long-lived output. Run them on Neon
  keywords: []
  noindex: false
  ogTitle: Rethinking streaming for agents - Neon
  ogDescription: Agents need Durable Streams for long-lived output. Run them on Neon
  image: null
---

When an agent works on a task for five minutes, it streams its progress back to the browser the whole time: tokens, tool calls, intermediate results. What happens if, three minutes in, you refresh the page?

The HTTP response that carried the stream is gone, and so is everything that came through it. The agent might still be running on the server, but the browser has no way to reconnect to the stream and nothing to replay.

Apps like ChatGPT and Claude do bring you back to your session after a refresh. They can because they keep the session in their own storage, separate from the stream, and wrote the code that reconnects you to it. Most teams building agents have to write that machinery themselves, because the tool they stream with (a single HTTP response) was made for chat, and agent output has outgrown it.

<video autoPlay muted loop playsInline width="708" height="406" aria-label="The Durable Chat demo keeps streaming a reply after a page refresh and continues the same chat on a laptop and a phone">
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/durable-chat-demo.webm" type="video/webm" />
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/durable-chat-demo.mp4" type="video/mp4" />
</video>

Right above is a clip from [Durable Chat](https://br-frosty-sunset-bgioxtua-chat.compute.c-9.eu-central-1.aws.neon.tech/), a demo that works differently. It's built on [Durable Streams](https://durablestreams.com/), so the agent's output is stored as it's written instead of living in the connection, and any tab or device can pick up the reply where it left off ([here's the code](https://github.com/samwillis/neon-durable-chat-demo).)

But let's not get ahead of ourselves.

## Streaming was built for chat

A model writes its answer one token at a time. If the app waited for the whole answer before showing anything, the user would stare at a spinner for ten or twenty seconds. So LLM apps stream instead: each token goes to the browser as soon as the model produces it, and the answer appears word by word.

The usual way to do this is simple:

- The browser sends one HTTP request.
- The server starts the response but doesn't finish it: it keeps the response open and writes each new token into it, usually in the server-sent events (SSE) format.
- When the model is done, the server closes the response.

While the model is still writing, the open response is the only place the output exists. The server passes tokens through as they arrive, and the app usually saves the reply to its database only once it's finished. Until then, the browser holds whatever it has received, and nothing else holds the rest.

Ordinary events end that response. A page refresh, a phone switching from Wi-Fi to cellular, a laptop going to sleep, and a server restarting during a deploy all close the connection.

When it closes mid-reply, three things are true:

1. The browser can't pick up where it stopped. It has no way to tell the server "I already have everything up to here, send me the rest."
2. There's nothing to send even if it could ask. The in-progress output was never saved, so the server can't replay what the browser missed. At best, the app saves the finished reply later.
3. Nobody else can watch the output as it's written. The response belongs to one connection, so a second tab, a teammate, or a background worker can't open it too.

For a chat reply, this was a reasonable tradeoff. The reply took a few seconds and was only text. If the connection dropped, the user lost a few seconds of in-progress output, and the app could show the saved reply once the model finished.

## Agents changed what a stream is

An agent run is a different kind of thing, and each difference raises the cost of losing the stream:

- **Runs are long.** An agent can work for minutes or hours. The longer the run, the more likely the connection drops at least once.
- **Runs take actions.** Agents call tools, write files, open pull requests, and send messages. Asking again means running those actions again, which is expensive at best and unsafe at worst.
- **Runs have many readers.** The user follows along on a laptop and then checks in from a phone. A teammate joins to review. A worker acts on the output, and another agent picks up where the first one stopped. A single HTTP connection has exactly one reader.
- **The stream is the record.** The ordered sequence of what the agent saw, said, and did is often the only account of the run.

Taken together, these mean an agent's stream is much more than a way to show progress: it holds the session itself.

So apps that take agents seriously store that output. Usually that means running two systems side by side: a stream that carries output to the browser, and a database that keeps it. Then there's the code that ties them together: saving each piece of output as it's produced, tracking how far each reader got, and replaying what a reader missed after it reconnects. Durable Streams puts transport and storage in one place. The stream itself is stored, ordered, and addressable, and anyone with permission can read it from wherever they left off.

<video autoPlay muted loop playsInline width="708" height="388" aria-label="Streaming over one connection loses everything when the connection drops, while a durable stream lets a worker, laptop, reviewer agent and phone each read from their own offset">
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/streaming-vs-durable-stream.webm" type="video/webm" />
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/streaming-vs-durable-stream.mp4" type="video/mp4" />
</video>

## Durable Streams: an open protocol for agents

At Electric we built [Durable Streams](https://durablestreams.com/) to fix this. A durable stream replaces the single long HTTP response with stored output that has its own URL. With a normal streaming response, the agent's output exists only while the connection is open; with a durable stream, the agent writes its output to the stream and the server keeps it. Readers ask the server for that output, starting from wherever they left off.

Each stream is a URL:

```text
https://api.example.com/v1/stream/runs/run-42/events
```

Two requests do most of the work:

- Writing: the agent sends a `POST` to the URL with its next piece of output, and the server adds it to the end of the stream.
- Reading: a client sends a `GET` to the URL with an offset, a marker for where to start reading.

Here's what happens when a connection drops. Say the agent has appended three pieces of output: `A`, `B`, and `C`.

1. The browser reads the stream and receives `A` and `B`.
2. Each response carries a `Stream-Next-Offset` header with the position just after the last thing received. The browser saves it, so it now holds the position after `B`.
3. The connection drops.
4. The browser reconnects and sends `GET ?offset=<saved value>`. The server returns `C`, the only part it missed.
5. To keep following, the browser adds `live=sse` or `live=long-poll`, and new output arrives as the agent writes it.

With a single HTTP response, step 4 is impossible. Nothing stored `A`, `B`, and `C`, and the browser had no position to send.

Those two requests are the core. The full interface adds four more:

| Operation | Request                                   | What it does                                  |
| --------- | ----------------------------------------- | --------------------------------------------- |
| Create    | `PUT /<path>`                             | Create a stream, optionally with initial data |
| Append    | `POST /<path>`                            | Add data, optionally closing the stream       |
| Read      | `GET /<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 /<path>`                            | Return metadata                               |
| Delete    | `DELETE /<path>`                          | Remove the stream                             |

Any client can talk to any server that implements the protocol, and a conformance suite checks that a server does. There are [client libraries](https://durablestreams.com/clients) for TypeScript, Python, Go, Rust, and other languages, plus transports for the [Vercel AI SDK](https://durablestreams.com/vercel-ai-sdk) and [TanStack AI](https://durablestreams.com/tanstack-ai) that make a `useChat` session survive refreshes. Each one is written once and works with every conforming server.

The protocol also covers the parts that get hard in production:

- Safe retries: a write can commit even if its response is lost. Writers can tag appends with a producer ID and sequence number, so retrying the same append never duplicates it.
- JSON mode: a stream can carry JSON messages, which readers get back as arrays.
- Lifecycle: streams can be closed, so readers know the output is complete. They can also expire.
- Forks: a new stream can start from another stream's history at a given offset, without copying it.
- Subscriptions: a server can wake a webhook or a worker when streams change.

## Architecture

What a durable stream asks of a server is mostly a database problem (commit writes in order, keep history cheaply as it grows, tell readers when something changes). That makes the database the natural place to build one.

Specifically, a Durable Streams server needs four things:

- Durable, ordered writes that are committed before they're acknowledged
- Cheap storage for history that can grow large
- A way to tell live readers about new writes as soon as they commit
- An HTTP server that can hold connections open for minutes

[Neon](https://neon.com/) has a [backend primitive](https://neon.com/blog/neon-backend-is-ga) for each of these pieces:

- [Lakebase Postgres](https://neon.com/lakebase) (the Neon database) stores every write. Each append is a transaction, so writes are ordered and committed before the writer hears back
- [Neon Object Storage](https://neon.com/object-storage) holds older history. Once part of a stream no longer needs to sit in Postgres, it moves to a bucket
- [Neon Realtime](https://neon.com/docs/realtime/overview) tells the server about new writes. It turns a SQL query into a live query, so the server hears about new rows as soon as they commit, without polling
- [Neon Functions](https://neon.com/functions) run the server itself. They're long-running and support SSE, so they can hold readers' connections open. They also run in the same region as your database, with the Postgres and Object Storage credentials injected for you

So, the Durable Streams server is a library that runs inside your own Neon project. You add it to a Function you already deploy and mount it on a route of your own API. You supply two hooks: `authenticate` checks who's calling, and `authorize` decides whether they can read or write a given stream. Stream data lives in your project's Postgres and bucket, next to the rest of your app's data, and you control access to it with the same auth your app already uses.

<video autoPlay muted loop playsInline width="708" height="457" aria-label="Architecture: writers and readers call your Neon Function, which stores data in Lakebase Postgres and Neon Object Storage, while Neon Realtime pushes live updates">
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/architecture.webm" type="video/webm" />
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/architecture.mp4" type="video/mp4" />
</video>

A deeper dive of the different components:

### Writes

Each append is one Postgres transaction. Inside it, the Function checks the caller with your hooks, locks the stream so writers to the same stream go one at a time, checks that the stream is still open and the write isn't a duplicate, then inserts the append and moves the stream's tail forward. The writer gets its acknowledgement only after the commit. It doesn't wait for readers or for Object Storage.

### Storage

If every append stayed a Postgres row, the database would grow with every token every agent ever streamed. So history moves through two stages.

<video autoPlay muted loop playsInline width="708" height="183" aria-label="One stream's history: sealed chunks in Object Storage followed by a hot tail in Lakebase Postgres that receives new appends">
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/stream-history.webm" type="video/webm" />
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/stream-history.mp4" type="video/mp4" />
</video>

New appends are hot: they're rows in Postgres. Once a stream's hot tail reaches 4 MiB, 8,192 appends, or an hour old, a maintenance job seals it:

1. A worker claims the chunk, with a lease that expires if the worker dies.
2. It uploads the chunk to Object Storage as one immutable object.
3. It downloads the object again and verifies every byte.
4. In one Postgres transaction, it records where the object is and deletes the original rows.

<video autoPlay muted loop playsInline width="708" height="279" aria-label="Sealing a chunk: claim, upload, verify and publish, with reads falling back to Postgres rows if a worker crashes before publish">
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/sealing-a-chunk.webm" type="video/webm" />
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/sealing-a-chunk.mp4" type="video/mp4" />
</video>

Postgres and Object Storage can't share a transaction, so the order of these steps is what makes it safe. Until step 4 commits, the rows are still in Postgres and reads keep using them. If the worker crashes, another one retries.

Maintenance runs in the background after writes, and a [Function Trigger](https://neon.com/docs/compute/functions/triggers/overview) runs it every minute to pick up anything left behind.

### Reads

To serve a read, the Function looks the stream up in one Postgres snapshot and splits the requested range in two: the hot part, which it reads from Postgres, and the sealed part, which it reads from Object Storage. Each sealed object is divided into 64 KiB blocks with their own SHA-256 checksums, so the Function fetches only the blocks it needs, using HTTP range requests, and verifies each one before sending it.

### Live updates

Live readers are the hard part. Without Realtime, the Function would have to poll Postgres for new rows. With [Realtime](https://neon.com/docs/realtime/overview), it subscribes to a live query on the stream's new appends:

```sql
SELECT stream_id, start_offset, end_offset, payload, message_ends
FROM durable_streams.appends
WHERE stream_id = $1::uuid AND end_offset > $2;
```

When an append commits, Realtime sends the new row, payload included, to the Function over a WebSocket. The Function forwards it to the reader over SSE or long-poll without running another query.

Turning those rows into a correct stream takes care in three places:

1. A reader catches up from stored history first, and only then does the Function subscribe. An append could commit in between, so once the subscription is ready, the Function checks history again and skips anything it has already sent.
2. Rows from Realtime can arrive out of order. The Function buffers them by offset and only sends data once everything before it has arrived.
3. When maintenance seals a chunk, Realtime reports its rows as removed. The Function knows that data now lives in Object Storage and doesn't treat it as lost.

The rule underneath all three: Realtime is the fast path, and Postgres and Object Storage are the source of truth. Whenever something doesn't line up, such as a dropped WebSocket, a reader too slow to keep up, or an unexpected row, the Function replays from stored history and then subscribes again.

<video autoPlay muted loop playsInline width="708" height="591" aria-label="Following a stream live: the reader catches up from durable history, subscribes to Realtime, checks history again, and receives only contiguous data">
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/following-a-stream-live.webm" type="video/webm" />
<source src="https://cdn.neonapi.io/public/images/pages/blog/rethinking-streaming-for-agents/following-a-stream-live.mp4" type="video/mp4" />
</video>

### Retries and webhooks

The protocol's production features build on the same Postgres transactions:

- **Retries:** the producer's latest sequence number is saved in the same transaction as the append. If a writer retries an append whose response was lost, the Function recognizes it and returns success without writing it twice.
- **Webhooks:** when a subscribed stream changes, the Function either sends a webhook, signed with Ed25519 so receivers can verify it, or appends a wake-up message to a stream your workers follow. Delivery is at least once, so a receiver should use its own idempotency key before doing anything with side effects.

## See an example: the Durable Chat demo

The [Durable Chat demo](https://br-frosty-sunset-bgioxtua-chat.compute.c-9.eu-central-1.aws.neon.tech/) from the top of this post is a shareable chat with Claude Haiku that runs entirely on Neon: Neon Functions serve the frontend and API, and Haiku runs through Neon AI Gateway. The Function embeds `@neon/durable-streams`, so everything described above runs inside it.

On top of that,

- **Each reply is its own stream.** The browser uses the Vercel AI SDK's `useChat` with `@durable-streams/aisdk-transport`. Each generation writes standard AI SDK message chunks to its own durable stream, and the transport replays and follows that stream across refreshes and reconnects.
- **Other devices find the active reply.** A small notification stream tells other devices when a turn starts or finishes, so they can find the active generation and resume it through the same transport. The notification stream carries no generated text.
- **Generation doesn't depend on readers.** Each turn is recorded with an idempotency key before it's acknowledged, and generation runs under `waitUntil`, so closing the tab doesn't stop it. The server writes the model's output in bounded batches under a run lock, which also stops an abandoned worker from writing once recovery has taken over.
- **A crash leaves readable output.** If the generation process dies, the output committed so far stays readable, and the run is marked interrupted once its lease expires. The demo doesn't rerun the model call; the saved partial output goes into the context of your next message.
- **Maintenance cleans up.** A scheduled job recovers abandoned runs and removes expired data. Chats and their streams expire together after 30 days.

Each chat's link carries an unguessable sharing token, and anyone with the link can read and write the conversation. There are no user accounts, so treat the link like a password and don't put anything sensitive in the public demo.

Repo: [https://github.com/samwillis/neon-durable-chat-demo](https://github.com/samwillis/neon-durable-chat-demo)

## How to get started

The fastest way to start is the [Function template](/functions/templates/durable-streams):

```bash
neon functions new durable-streams
```

You'll need a Neon project with:

- Postgres 18 and Realtime enabled
- A private Object Storage bucket for sealed chunks
- A region where Functions are available

To add Durable Streams to an existing app, you can let your agent set it up with a prompt like this:

```text filename="Prompt your agent" shouldWrap
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
   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 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 using the Durable Streams transport for our AI SDK:
   @durable-streams/aisdk-transport for Vercel AI SDK, or the TanStack AI integration.
   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 duplication.
```

You can also wire things up yourself. Start here:

- **[The package](https://github.com/neondatabase/neon-pkgs/tree/main/packages/durable-streams)**: the README covers installation and configuration.
- [The Durable Chat demo](https://github.com/samwillis/neon-durable-chat-demo): a complete chat app on Neon Functions, with the Vercel AI SDK transport, Neon AI Gateway, and conversations that survive refreshes and move across devices. [Try it live](https://br-frosty-sunset-bgioxtua-chat.compute.c-9.eu-central-1.aws.neon.tech/).
- [Durable Streams protocol](https://durablestreams.com) (Electric docs): the HTTP protocol from Electric, client libraries, and the [Vercel AI SDK](https://durablestreams.com/vercel-ai-sdk) and [TanStack AI](https://durablestreams.com/tanstack-ai) integrations.
