Open History to see the last commit
1---
2title: How Persistence Works (Advanced)
3id: internals
4description: "How persistence works: the two durability layers, thread and run identity, who owns history, what a reload restores, and the middleware lifecycle."
5keywords:
6 - persistence internals
7 - delivery durability vs state persistence
8 - threadId runId
9 - server authoritative
10 - middleware lifecycle
11---
12
13This page describes the calls a reload makes. To set persistence up, use [the overview](./overview).
14
15## The short version
16
17- **Two layers.** Delivery durability replays a live stream. State persistence stores the conversation. They share no code, and most apps want both.
18- **Two ids.** A thread is the conversation. A run is one execution inside it. Restore starts from the thread.
19- **Merge by id.** `withPersistence` merges the incoming messages into the stored thread by message id, then saves the full list.
20- **Isolation is your job.** Store methods take a bare `threadId`. Authorize the user before you load or save.
21
22## How it works
23
24### Two layers
25
26| Layer | Answers | Lives in | Docs |
27| --- | --- | --- | --- |
28| **Delivery durability** | "How do I reconnect to a stream that still runs?" | A log per run, keyed by `runId` | [Resumable Streams](../resumable-streams/overview) |
29| **State persistence** | "What is the conversation, and is it still there later?" | A durable store, on the client, the server, or both | This section |
30
31Delivery durability replays a live byte stream, so a dropped connection resumes where it stopped. State persistence stores the conversation itself, so it survives a reload and opens on another device. A replayable stream is not a saved conversation. A saved conversation is not a live stream.
32
33### Threads and runs
34
35A **thread** (`threadId`) is the conversation. It is stable, survives reloads, and exists on every device. A **run** (`runId`) is one execution inside the thread, made fresh for each streamed answer. A thread collects many runs. Delivery durability logs one run. State persistence stores the whole thread.
36
37```mermaid
38flowchart TB
39 subgraph thread ["One thread, threadId (stable, the conversation)"]
40 direction LR
41 run1["run r1
42completed"] --> run2["run r2
43completed"] --> run3["run r3
44running"]
45 end
46
47 subgraph delivery ["Delivery durability, one byte log per run"]
48 log["log for r3
49replays the live stream to a reconnecting client"]
50 end
51
52 subgraph state ["State persistence, durable store per thread"]
53 store["transcript, run records, interrupts"]
54 end
55
56 run3 -. "a dropped connection tails" .-> log
57 thread -- "saved on finish, loaded on mount" --> store
58```
59
60A reloading client does not always know the current run id, so it cannot reconnect by run. It reconnects from the stable `threadId`. The store answers "does this thread have a live run?" with `findActiveRun`. Only then does the client read that run's log. [Id map](./id-map) is the short version of both ids.
61
62### Isolation is yours to enforce
63
64Store APIs take a bare `threadId` string. That keeps adapters simple, and it makes multi-user isolation your job:
65
661. Derive `Scope.userId` and `Scope.tenantId` on the server, from session state.
672. Authorize before `loadThread`, `saveThread`, and `reconstructChat`. Use `reconstructChat(persistence, request, { authorize })`.
683. Never treat a thread id from the client as proof of ownership. Thread ids are easy to guess.
69
70`Scope` is re-exported from `@tanstack/ai-persistence`, next to the store contracts.
71
72### Who owns history when both sides persist
73
74`withPersistence` merges the incoming `messages` into the stored thread by id:
75
76- **Empty `messages`**: the server loads its stored transcript and continues from it.
77- **Non-empty `messages`**: the last incoming id that already exists in the stored thread is a cutoff. Stored messages after it are dropped. On the same id, the incoming message wins. New ids are appended.
78
79`saveThread` then replaces the stored thread with the merged list.
80
81There are two postures:
82
83- **Client-authoritative**, close to a pure single-page app. The client sends its full in-memory list. The merge keeps stored messages that the client left out, unless a shared id cuts the stored tail (a reload).
84- **Server-authoritative**: the same thread opens on another device. With `history: { pageSize }`, the client posts only the new turn. A reload posts the last user message. A resume posts from that user message through the assistant message on screen. The merge keeps stored messages before the cutoff.
85
86### What a reload restores
87
88With a client storage adapter, `useChat` reads the client record on load. Then it does one of three things:
89
901. **The run had finished.** The record has the transcript and no resume pointer. The conversation paints from storage, with no network.
912. **The run had paused on an interrupt.** The resume pointer holds the pending interrupts. The transcript paints, and the approval UI comes back as it was.
923. **The run was still streaming.** The transcript paints from storage. Then the client rejoins the live run through the durability log, and the reply finishes in place. Only this case needs both layers.
93
94If the connection drops while the page stays open, delivery durability reconnects by itself. Persistence matters when the page itself is gone.
95
96In server-authoritative mode, the client paints from a server read, not from `localStorage`. A `GET` with `limit` returns the newest window and a `page` object. An older window uses `before`. The delivery log cannot supply that history, because it holds one run, not the thread.
97
98Both layers expect the work to be over when the client comes back. Replaying a log and reading a transcript both read something that already exists. A long-running **sandboxed agent** is different: the run still goes on, and its producer was the host that disappeared. That needs a later request that adopts the run and keeps driving it. See [Takeover & Detached Runs](../sandbox/takeover).
99
100### Why server-authoritative is the recommended default
101
102- **One source of truth.** History lives on the server, so two copies cannot drift apart. The same conversation opens on any device and survives a restart.
103- **A light client.** The browser never parses or stores a long transcript. There is no storage quota and no parse cost at startup, even for very long threads.
104- **Reloads still work.** The mount `GET` paints the transcript again and reports any `activeRun`. The client rejoins that run and restores pending interrupts.
105- **No wasted work.** That `GET` shares the route with the stream resume. `loadThread` returns ready messages, so nothing replays a stream to rebuild them.
106
107```mermaid
108sequenceDiagram
109 participant Hook as useChat (persistence: true)
110 participant Route as GET /api/chat
111 participant Store as Durable store
112 participant Log as Delivery log
113
114 Note over Hook: page reloads while a run is streaming
115 Hook->>Route: ?threadId=support-chat
116 Route->>Store: reconstructChat, loadThread + findActiveRun
117 Store-->>Route: messages + activeRun (runId)
118 Route-->>Hook: transcript + activeRun cursor
119 Note over Hook: transcript paints
120 Hook->>Route: ?runId=...&offset=-1
121 Route->>Log: resumeServerSentEventsResponse
122 Log-->>Hook: replay + live tail of the run
123 Note over Hook: reply finishes in place
124```
125
126## Advanced
127
128### Separate boundaries
129
130Server state persistence is one of three boundaries that share no code:
131
132- **Server state** (this page): `AIPersistence` stores that the middleware lifecycle drives. This is the authoritative record.
133- **Client hydration**: the browser restores a rendered conversation. See [Client persistence](./client-persistence).
134- **Stream delivery**: replay of an in-flight SSE response. See [Resumable Streams](../resumable-streams/overview).
135
136State middleware never changes chunks to add delivery offsets. It stores server event state, not the messages that the client rendered.
137
138### Chat middleware lifecycle
139
140`withPersistence(persistence)` makes a plan from the stores that are present. Then it acts at these hooks:
141
1421. **`setup`** provides the persistence capability, a run-completion capability, and the core metadata and interrupts capabilities when those stores exist. It does not provide locks.
1432. **`onConfig`** creates or resumes the run and seeds usage from the run record. It loads pending interrupts and validates the resume batch of the request against them. Then it merges stored messages into the request by id. An empty list loads the stored thread.
1443. **`onStart`** saves the pending turn, so a reload during generation still shows the question. This save is best-effort.
1454. **`onUsage`** adds up the usage of each provider terminal.
1465. **`onChunk`** reacts only to a `RUN_FINISHED` with an interrupt outcome. It commits the accepted resumes, stores the new interrupts, marks the run interrupted, and saves the messages.
1476. **`onFinish`** saves the full transcript first, then marks the run completed.
148
149Usage at the interrupt boundary has two cases. A direct adapter terminal arrives before `onUsage`, so the handler includes its usage and ignores the next `onUsage`. A synthesized tool boundary arrives after the original terminal's `onUsage`, so the handler reuses that total.
150
151Before `onFinish`, the chat engine adds the completed terminal assistant messages to `ctx.messages`:
152
153- Native-combined output keeps the structured result on its terminal assistant message.
154- Separate finalization and event-sourced harness output add a second structured-output message only when that event uses a different message id.
155
156`onError` terminalizes the run record and does not replace the transcript. `onFinish`, `onError`, and a terminal `onAbort` all keep the usage known so far. One exception: on a run that another middleware has declared detachable, a plain disconnect (no cancel recorded in either band) writes nothing. The record stays `'running'` for a later takeover. See [Takeover & Detached Runs](../sandbox/takeover#detach-vs-cancel).
157
158Accepted resumes are committed (interrupts marked resolved or cancelled) only at a successful boundary. If a provider failure or an abort happens between accepting a resume and reaching that boundary, the interrupt stays pending. A retry with the same resume then succeeds.
159
160The AG-UI chunk stream does not change. Persistence does not create a second event stream.
161
162### Reading the stores from your own middleware
163
164Your own middleware often needs the stores that `withPersistence` already holds: an audit step that writes to `metadata`, or a guard that checks pending interrupts. If you pass the persistence object in twice, the two copies can drift apart. Read the stores as capabilities instead. Declare them in `requires`, then read them from the context:
165
166```ts
167import {
168 chat,
169 chatParamsFromRequest,
170 defineChatMiddleware,
171 toServerSentEventsResponse,
172} from '@tanstack/ai'
173import { openaiText } from '@tanstack/ai-openai'
174import {
175 InterruptsCapability,
176 PersistenceCapability,
177 getInterrupts,
178 getPersistence,
179 memoryPersistence,
180 withPersistence,
181} from '@tanstack/ai-persistence'
182import type { ChatMiddlewareContext } from '@tanstack/ai'
183
184const persistence = memoryPersistence()
185
186const auditPending = defineChatMiddleware({
187 name: 'audit-pending',
188 // Fails at setup when no middleware provided the capability.
189 requires: [PersistenceCapability, InterruptsCapability],
190 async setup(ctx: ChatMiddlewareContext) {
191 const stores = getPersistence(ctx).stores
192 const interrupts = getInterrupts(ctx)
193 const pending = await interrupts.listPending(ctx.threadId)
194 await stores.metadata?.set(ctx.threadId, 'pending-count', {
195 count: pending.length,
196 })
197 },
198})
199
200export async function POST(request: Request) {
201 const { messages, threadId, runId } = await chatParamsFromRequest(request)
202 const stream = chat({
203 adapter: openaiText('gpt-6.1-sol'),
204 messages,
205 threadId,
206 runId,
207 // Order matters: the provider comes before the consumer.
208 middleware: [withPersistence(persistence), auditPending],
209 })
210 return toServerSentEventsResponse(stream)
211}
212```
213
214The capabilities that `withPersistence` publishes:
215
216| Capability | Read with | Gives you | Published when |
217| --- | --- | --- | --- |
218| `PersistenceCapability` | `getPersistence(ctx)` | The whole `AIPersistence` object | Always |
219| `InterruptsCapability` | `getInterrupts(ctx)` | The `interrupts` store | The backend has an `interrupts` store |
220| `PersistenceCompletionCapability` | `getPersistenceCompletion(ctx)` | `waitForRunCompletion()` | Always |
221| `MetadataCapability` (from `@tanstack/ai`) | `getMetadata(ctx)` | The `metadata` store | The backend has a `metadata` store |
222
223`providePersistence` and `provideInterrupts` are the write halves. Use them in a middleware of your own that supplies the stores in place of `withPersistence`. Locks are a separate capability from [`@tanstack/ai/locks`](../advanced/locks).
224
225### Generation middleware lifecycle
226
227`withGenerationPersistence(persistence)` records the job at three points:
228
229- `onStart` creates or resumes the run record.
230- `onFinish`, `onError`, and `onAbort` terminalize it.
231- A result transform writes the terminal result metadata (ids and URLs, never media bytes) onto the record.
232
233When `artifacts` and `blobs` are both present, it also stores the generated media. Then it merges the durable refs onto the result and onto the run record.
234
235Generation uses its own `generationRuns` store (`GenerationRunStore`), never the chat `runs` or `messages` stores. A generation has no conversation, so the run is keyed on its own `runId` (`ctx.runId ?? ctx.requestId`). The `threadId` is never the primary identity of the job.
236
237The `threadId` is still **required**. It is the slot that the run is filed under, and `GenerationRunRecord.threadId` is a required field. The middleware resolves it as `opts.threadId ?? ctx.threadId`: normally the `threadId` that the caller passed to the activity, with the option as an override. When neither gives one, the middleware **throws**. It never makes one up from the request id. Nothing can find a run that is filed under an invented scope, so restore returns nothing forever.
238
239### Composition semantics
240
241```ts
242import {
243 composePersistence,
244 memoryPersistence,
245} from '@tanstack/ai-persistence'
246
247const base = memoryPersistence()
248const replacement = base.stores.messages
249
250const result = composePersistence(base, {
251 overrides: {
252 messages: replacement,
253 metadata: undefined,
254 interrupts: false,
255 },
256})
257```
258
259- `messages` is replaced.
260- `metadata` is inherited, because the override is `undefined`.
261- `interrupts` is removed.
262- Every store that you leave out is inherited.
263
264Composition copies the store map. It does not change or dispose of either input. The return type works out which keys are required, optional, replaced, or removed. Unknown store keys fail at compile time and at runtime.
265
266Each entrypoint adds its own runtime check:
267
268| Entrypoint | Rule |
269| --- | --- |
270| `withPersistence` | Requires `messages`. Rejects `interrupts` without `runs`. |
271| `withGenerationPersistence` | Requires `generationRuns`. Requires `artifacts` and `blobs` together. |
272| `reconstructChat` | Requires `messages`. |
273| `reconstructGeneration` | Requires `generationRuns`. |
274
275The runtime checks are necessary because plain JavaScript, loaded configuration, and widened types can get past the static checks.
276
277### Backend ownership
278
279An adapter owns its resources: the connection lifecycle, when migrations run, and how each store record maps to rows. The middleware only calls store methods. It never opens a connection or reads a table. A backend can provide any subset of the stores (for example, no `metadata`), and the return type shows exactly the stores that it has. [Build a chat adapter](./build-your-own-chat-adapter) shows this end to end for SQLite.
280
281`composePersistence` does not add distributed transactions. When related stores use different systems, the adapter author defines the retry, idempotency, and consistency behavior.
282
283Two `RunStore` rules apply to durable runs:
284
285- `update` must round-trip `driverEpoch`. A takeover increments this fencing token, and it is the only way a replaced host learns that it lost the run.
286- `update` must tell an **omitted** patch key (leave the column alone) apart from a key set to `undefined` (clear the column). The takeover path clears `detachedSince` that way.
287
288See [Build your own adapter](./build-your-own-adapter) and [Takeover & Detached Runs](../sandbox/takeover#requirements).