Open History to see the last commit
1---
2title: How Persistence Works (Advanced)
3id: internals
4description: "The two durability layers and how they differ, thread and run identity, who owns history when both sides persist, what a reload restores, and the middleware lifecycle behind every backend."
5keywords:
6 - persistence internals
7 - delivery durability vs state persistence
8 - threadId runId
9 - server authoritative
10 - middleware lifecycle
11---
12
13Read this when something surprised you, or before you write a backend. To simply set
14persistence up, [the overview](./overview) is three snippets.
15
16## Two layers, not one
17
18| Layer | Answers | Lives | Docs |
19| --- | --- | --- | --- |
20| **Delivery durability** | "how do I reconnect to a stream that is still running?" | a per-run log, keyed by `runId` | [Resumable Streams](../resumable-streams/overview) |
21| **State persistence** | "what is the conversation, and is it still there later?" | a durable store (client and/or server) | this section |
22
23They share no code. Delivery durability replays a live byte stream so a dropped
24connection resumes exactly where it stopped. State persistence stores the
25conversation itself, so it survives a reload or exists on another device. A replayable
26stream is not a saved conversation, and a saved conversation is not a live stream.
27Most real apps want both.
28
29## Identity: threads and runs
30
31A **thread** (`threadId`) is the conversation: stable, survives reloads, exists on
32every device. A **run** (`runId`) is one execution inside it, minted fresh for each
33streamed answer. A thread accumulates many runs; delivery durability logs one run,
34state persistence stores the whole thread.
35
36```mermaid
37flowchart TB
38 subgraph thread ["One thread, threadId (stable, the conversation)"]
39 direction LR
40 run1["run r1
41completed"] --> run2["run r2
42completed"] --> run3["run r3
43running"]
44 end
45
46 subgraph delivery ["Delivery durability, one byte log per run"]
47 log["log for r3
48replays the live stream to a reconnecting client"]
49 end
50
51 subgraph state ["State persistence, durable store per thread"]
52 store["transcript, run records, interrupts"]
53 end
54
55 run3 -. "a dropped connection tails" .-> log
56 thread -- "saved on finish, loaded on mount" --> store
57```
58
59Run ids are too ephemeral to reconnect by, since a reloading client may not know the
60current one. Reconnection resolves from the stable `threadId` instead: the store
61answers "does this thread have a live run?" (`findActiveRun`), and only then does the
62client tail that run's log. [Id map](./id-map) is the short version of both ids.
63
64### Isolation is yours to enforce
65
66Store APIs take a bare `threadId` string, which keeps adapters simple and makes
67multi-user isolation your job:
68
69- Derive `Scope.userId` / `Scope.tenantId` **server-side** from session state.
70- Authorize before `loadThread` / `saveThread` / `reconstructChat`, with
71 `reconstructChat({ authorize })`.
72- Never treat a client-supplied thread id as ownership. Thread ids are guessable.
73
74`Scope` is re-exported from `@tanstack/ai-persistence`, so the identity type sits next
75to the store contracts.
76
77## Who owns history when both sides persist
78
79`withPersistence` merges incoming `messages` into the stored thread by id:
80
81- **Empty `messages`**: continue from the stored transcript. The server loads
82 its copy and runs from there.
83- **Non-empty `messages`**: merge by id. The last incoming id that already
84 exists in stored is a cutoff. Stored messages after it are dropped. Incoming
85 wins on the same id. New ids are appended.
86
87`saveThread` replaces the stored thread with that merged list.
88
89Two postures:
90
91- **Client-authoritative**, closest to a pure SPA. The client sends its
92 in-memory list. Merge keeps stored extras the client omitted, unless a
93 shared id cuts the stored tail (reload).
94- **Server-authoritative**: the same thread opens on another device. With
95 `history: { pageSize }`, the client posts only the new turn. Reload posts
96 the last user. Resume posts from that user through the painted assistant.
97 Merge keeps stored extras that sit before the cutoff.
98
99## What a reload restores
100
101With a client store adapter, `useChat` reads the client record on load and acts on
102what it finds:
103
1041. **The run had finished.** The record has the transcript and no resume pointer. The
105 conversation paints instantly from storage, with no network.
1062. **The run was paused on an interrupt.** The resume pointer carries the pending
107 interrupts, so the transcript paints and the approval UI comes back as it was.
1083. **The run was still streaming.** The transcript paints from storage, then the
109 client rejoins the live run through the durability log and the reply finishes in
110 place. This is the one case that needs both layers.
111
112A dropped connection while the page is still open is simpler: delivery durability
113reconnects on its own. Persistence matters once the page itself is gone.
114
115Server-authoritative mode paints from a server read instead of `localStorage`.
116A GET with `limit` returns the newest window and `page`. An older window uses
117`before`. The delivery log cannot supply that history, because it holds one
118run, not the thread.
119
120Both layers assume the work itself is over by the time the client comes back:
121replaying a log and reading a transcript are both reads of something already
122produced. A long-running **sandboxed agent** is the case where neither is enough,
123because the run is still going and its producer was the host that disappeared. That
124needs a third thing, a later request that adopts the run and keeps driving it. See
125[Takeover & Detached Runs](../sandbox/takeover).
126
127## Why server-authoritative is the recommended default
128
129- **One source of truth.** History lives on the server, so no two copies can drift.
130 The same conversation opens on any device and survives a restart.
131- **A cheap client.** The browser never parses or stores a long transcript, so there
132 is no storage quota or startup-parse cost, even for huge threads.
133- **Reload durability anyway.** The mount `GET` re-paints the transcript and reports
134 any `activeRun`, so the client rejoins it and restores pending interrupts.
135- **No wasted work.** That `GET` shares the route with the durable-stream resume, and
136 `loadThread` returns ready-made messages instead of replaying a stream to rebuild
137 them.
138
139```mermaid
140sequenceDiagram
141 participant Hook as useChat (persistence: true)
142 participant Route as GET /api/chat
143 participant Store as Durable store
144 participant Log as Delivery log
145
146 Note over Hook: page reloads while a run is streaming
147 Hook->>Route: ?threadId=support-chat
148 Route->>Store: reconstructChat, loadThread + findActiveRun
149 Store-->>Route: messages + activeRun (runId)
150 Route-->>Hook: transcript + activeRun cursor
151 Note over Hook: transcript paints
152 Hook->>Route: ?runId=…&offset=-1
153 Route->>Log: resumeServerSentEventsResponse
154 Log-->>Hook: replay + live tail of the run
155 Note over Hook: reply finishes in place
156```
157
158## Separate boundaries
159
160Server state persistence is one of three boundaries that intentionally share no
161code:
162
163- **Server state** (this page): `AIPersistence` stores driven by the middleware
164 lifecycle, the authoritative record.
165- **Client hydration**: the browser restores a rendered conversation, a separate
166 concern covered in [Client persistence](./client-persistence).
167- **Stream delivery**: replaying an in-flight SSE response,
168 [Resumable Streams](../resumable-streams/overview).
169
170State middleware never mutates chunks to add delivery offsets, and it stores
171server event state, not the client's rendered messages.
172
173## Chat middleware lifecycle
174
175`withPersistence(persistence)` derives a plan from store presence:
176
1771. `setup` provides persistence, interrupt, and lock capabilities when their
178 stores exist.
1792. `onConfig` creates or resumes the run, seeds usage from the existing run
180 record, loads pending interrupts, and validates the request's resume batch
181 against them, then merges stored messages into the request by id. An empty
182 list loads the stored thread.
1833. `onUsage` accumulates each provider terminal.
1844. `onChunk` reacts only to a `RUN_FINISHED` interrupt outcome. A direct adapter
185 terminal arrives before `onUsage`, so the handler includes its usage and
186 ignores the following `onUsage`. A synthesized tool boundary arrives after
187 the original terminal's `onUsage`, so the handler reuses that aggregate. It
188 then commits accepted resumes, stores the new interrupts, marks the run
189 interrupted, and saves messages.
1905. Before `onFinish`, the chat engine appends the completed terminal assistant
191 messages to `ctx.messages`. Native-combined output keeps the structured
192 result on its terminal assistant message. Separate finalization and
193 event-sourced harness output append a second structured-output message only
194 when that event uses a different message id.
1956. `onFinish` saves that canonical transcript before marking the run completed.
196 `onError` terminalizes the run record without replacing the transcript. Both
197 retain known usage. So does terminal `onAbort`, with one exception: on a run
198 another middleware has declared detachable, a plain disconnect (no cancel
199 recorded in either band) writes nothing and leaves the record `'running'`
200 for a later takeover. See
201 [Takeover & Detached Runs](../sandbox/takeover#detach-vs-cancel).
202
203Accepted resumes are committed (interrupts marked resolved/cancelled) only once
204the run reaches a successful boundary, so a provider failure or abort between
205accepting a resume and reaching that boundary leaves the interrupt pending and a
206retry with the same resume succeeds. The canonical AG-UI chunk stream remains
207unchanged; persistence does not create a second event stream.
208
209`withPersistence` merges incoming `messages` into the stored thread by id.
210If `messages` is empty, the stored transcript is loaded and used.
211If `messages` is not empty, stored extras stay, new ids append, and the same
212id uses the incoming message. `saveThread` replaces the stored thread with
213that merged list.
214
215## Reading the stores from your own middleware
216
217Your own middleware often needs the same stores `withPersistence` is already
218holding: an audit step that writes to `metadata`, a guard that checks pending
219interrupts. Passing the persistence object in twice works but drifts, because
220the middleware and your code can end up with different instances.
221
222`withPersistence` publishes what it holds as capabilities instead. Declare what
223you need in `requires`, then read it off the context:
224
225```ts
226import { chat, defineChatMiddleware, toServerSentEventsResponse } from '@tanstack/ai'
227import { openaiText } from '@tanstack/ai-openai'
228import {
229 InterruptsCapability,
230 PersistenceCapability,
231 getInterrupts,
232 getPersistence,
233 memoryPersistence,
234 withPersistence,
235} from '@tanstack/ai-persistence'
236import type { ChatMiddlewareContext } from '@tanstack/ai'
237
238const persistence = memoryPersistence()
239
240const auditPending = defineChatMiddleware({
241 name: 'audit-pending',
242 // Fails fast at setup when the capability was never provided.
243 requires: [PersistenceCapability, InterruptsCapability],
244 async setup(ctx: ChatMiddlewareContext) {
245 const stores = getPersistence(ctx).stores
246 const interrupts = getInterrupts(ctx)
247 const pending = await interrupts.listPending(ctx.threadId)
248 await stores.metadata?.set(ctx.threadId, 'pending-count', {
249 count: pending.length,
250 })
251 },
252})
253
254export async function POST(request: Request) {
255 const { messages, threadId } = await request.json()
256 const stream = chat({
257 adapter: openaiText('gpt-5.5'),
258 messages,
259 threadId,
260 // Order matters: the provider runs before the consumer.
261 middleware: [withPersistence(persistence), auditPending],
262 })
263 return toServerSentEventsResponse(stream)
264}
265```
266
267Two capabilities are published:
268
269- `PersistenceCapability`, read with `getPersistence(ctx)`: the whole
270 `AIPersistence` object, so any store it exposes is reachable.
271- `InterruptsCapability`, read with `getInterrupts(ctx)`: the `interrupts` store
272 alone, published only when persistence actually has one.
273
274`providePersistence` and `provideInterrupts` are the write halves, for a
275middleware of your own that supplies the stores instead of `withPersistence`.
276Locks are not part of this: they are a separate capability from
277[`@tanstack/ai/locks`](../advanced/locks).
278
279## Generation middleware lifecycle
280
281`withGenerationPersistence(persistence)` records the job across
282three points:
283
284- `onStart` creates or resumes the run record.
285- `onFinish` / `onError` / `onAbort` terminalize it.
286- A result transform captures the terminal result metadata (ids, urls, never
287 media bytes) onto the record.
288
289When `artifacts` and `blobs` are both provided it also persists the generated
290media and merges the durable refs onto both the result and the run record.
291
292Generation uses its own `generationRuns` store (`GenerationRunStore`), never chat's
293`runs` / `messages`. A generation has no conversation, so the run is keyed on
294its own `runId` (`ctx.runId ?? ctx.requestId`), and `threadId` never becomes the
295job's primary identity.
296
297`threadId` is nonetheless **required**: it is the slot the run is filed under,
298and `GenerationRunRecord.threadId` is a required field. The middleware resolves
299it as `opts.threadId ?? ctx.threadId` (normally the `threadId` the caller
300passed the activity, with the option as an override) and **throws** when
301neither supplies one. It is never faked from the request id: a run filed under
302an invented scope can never be hydrated by one, so restoring would silently
303return nothing forever.
304
305## Composition semantics
306
307```ts
308import {
309 composePersistence,
310 memoryPersistence,
311} from '@tanstack/ai-persistence'
312
313const base = memoryPersistence()
314const replacement = base.stores.messages
315
316const result = composePersistence(base, {
317 overrides: {
318 messages: replacement,
319 metadata: undefined,
320 interrupts: false,
321 },
322})
323```
324
325- `messages` is replaced.
326- `metadata` is inherited because the override is `undefined`.
327- `interrupts` is removed.
328- every omitted store is inherited.
329
330Composition copies the store map and does not mutate or dispose either input.
331The return type calculates which keys are required, optional, replaced, or
332removed. Unknown store keys are rejected statically and by runtime validation.
333
334Middleware adds entrypoint validation:
335
336- chat requires `messages`; rejects `interrupts` without `runs`.
337- generation requires `generationRuns`.
338- `reconstructChat` requires `messages`.
339- `reconstructGeneration` requires `generationRuns`.
340
341The runtime checks are required because JavaScript, configuration loading, and
342explicitly widened types can bypass static guarantees.
343
344## Backend ownership
345
346An adapter owns its own resources: connection lifecycle, when migrations run, and
347how each store record maps to rows. The middleware only calls the store methods;
348it never opens a connection or inspects a table. A backend may provide any subset
349of the stores (for example, no `metadata`), and the return type reflects exactly the
350stores it exposes. [Build a chat adapter](./build-your-own-chat-adapter) shows
351this end to end for SQLite.
352
353`composePersistence` does not add distributed transactions. When related
354stores use different systems, adapter authors must define retry,
355idempotency, and consistency behavior.
356
357Two `RunStore` details bind an adapter author beyond the obvious mapping, and
358both exist for durable runs. `update` must round-trip `driverEpoch` (the fencing
359token a takeover bumps, and the only way a superseded host can discover it lost
360the run), and it must distinguish an **omitted** patch key (leave the column
361alone) from a key carrying `undefined` (clear the column). The takeover path
362clears `detachedSince` exactly that way. See
363[Build your own adapter](./build-your-own-adapter) and
364[Takeover & Detached Runs](../sandbox/takeover#requirements).