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.
Right above is a clip from Durable Chat, a demo that works differently. It's built on Durable Streams, 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.)
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:
- 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."
- 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.
- 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.
Durable Streams: an open protocol for agents #
At Electric we built Durable Streams 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:
Two requests do most of the work:
- Writing: the agent sends a
POSTto the URL with its next piece of output, and the server adds it to the end of the stream. - Reading: a client sends a
GETto 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.
- The browser reads the stream and receives
AandB. - Each response carries a
Stream-Next-Offsetheader with the position just after the last thing received. The browser saves it, so it now holds the position afterB. - The connection drops.
- The browser reconnects and sends
GET ?offset=<saved value>. The server returnsC, the only part it missed. - To keep following, the browser adds
live=sseorlive=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 withlive=long-poll orlive=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 for TypeScript, Python, Go, Rust, and other languages, plus transports for the Vercel AI SDK and 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 has a backend primitive for each of these pieces:
- Lakebase Postgres (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 holds older history. Once part of a stream no longer needs to sit in Postgres, it moves to a bucket
- Neon Realtime 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 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.
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.
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:
- A worker claims the chunk, with a lease that expires if the worker dies.
- It uploads the chunk to Object Storage as one immutable object.
- It downloads the object again and verifies every byte.
- In one Postgres transaction, it records where the object is and deletes the original rows.
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 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, it subscribes to a live query on the stream's new appends:
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:
- 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.
- Rows from Realtime can arrive out of order. The Function buffers them by offset and only sends data once everything before it has arrived.
- 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.
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 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
useChatwith@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
How to get started #
The fastest way to start is the Function template: 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:
You can also wire things up yourself. Start here:
- The package : the README covers installation and configuration.
- The 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 .
- Durable Streams protocol (Electric docs): the HTTP protocol from Electric, client libraries, and theVercel AI SDK andTanStack AI integrations.