Open History to see the last commit
1---
2title: Operating
3id: memory-operating
4order: 5
5description: "Run memoryMiddleware in production: log recall and save with onRecall and onSave, watch memory in devtools, save without recall, and know what happens when the memory store fails."
6keywords:
7 - tanstack ai
8 - memory
9 - middleware options
10 - telemetry
11 - devtools
12 - observability
13 - save-only
14---
15
16Log what memory recalls, and keep a slow or failed store from failing the chat.
17
18Add the `onRecall` and `onSave` callbacks for your logs, and use the devtools **Memory** tab while you develop. A memory failure never stops the chat.
19
20## Quick setup
21
22### 1. Log recall and save
23
24```ts
25import { memoryMiddleware } from '@tanstack/ai-memory'
26import { inMemory } from '@tanstack/ai-memory/in-memory'
27
28const middleware = memoryMiddleware({
29 adapter: inMemory(),
30 // ctx.threadId is the conversation id. Add userId from your server session.
31 scope: (ctx) => ({ threadId: ctx.threadId }),
32 onRecall: ({ query, result }) => {
33 console.log('recalled', result.fragments?.length ?? 0, 'hits for', query)
34 },
35 onSave: ({ receipts }) => {
36 console.log('saved', receipts.filter((r) => r.ok).length, 'records')
37 },
38})
39```
40
41Add `middleware` to the `middleware` array of your `chat()` call. Then send your metrics client the counts in place of `console.log`.
42
43### 2. Watch memory in devtools
44
45Open the TanStack AI devtools and select the **Memory** tab. For each turn, it shows:
46
47- The recall query.
48- The number of recalled fragments.
49- The number of characters added to the prompt.
50- The recall duration.
51- The stored records and facts, for adapters that have `inspect` and `listFacts`. `inMemory()` and `redis()` have both.
52
53See the [Memory Inspector](../getting-started/devtools#memory-inspector) for how server-side memory gets to the panel.
54
55Each request now logs what memory recalled and saved, and the Memory tab shows the same data while you develop.
56
57## How it works
58
59- `onRecall` runs after each recall, with the scope, the query, and the result.
60- `onSave` runs after each deferred save, with the scope, the turn, and the write receipts.
61- If `recall` throws, the run continues with no memory in the prompt.
62- If `save` throws, the turn is not saved. The response is not affected, because the save runs after the stream.
63
64The middleware does not catch errors from your `onRecall` and `onSave` callbacks. Catch errors inside them.
65
66## `memoryMiddleware` options
67
68| Option | Type | Default | Purpose |
69| --- | --- | --- | --- |
70| `adapter` | `MemoryAdapter` | (required) | The backend that `recall` reads from and `save` writes to. |
71| `scope` | `MemoryScope \| (ctx) => MemoryScope` | (required) | The isolation scope. Static, or set for each request. The function can be async. |
72| `role` | `'recall+save' \| 'save-only'` | `'recall+save'` | `'save-only'` saves turns but does not recall or add to the prompt. |
73| `onRecall` | `({ scope, query, result }) => void` | none | Telemetry after each `recall`. |
74| `onSave` | `({ scope, turn, receipts }) => void` | none | Telemetry after each deferred `save`. |
75
76## Persist without recalling
77
78Set `role: 'save-only'` to save each turn without reading memory or changing the prompt:
79
80```ts
81import { memoryMiddleware } from '@tanstack/ai-memory'
82import { inMemory } from '@tanstack/ai-memory/in-memory'
83
84const middleware = memoryMiddleware({
85 adapter: inMemory(),
86 scope: (ctx) => ({ threadId: ctx.threadId }),
87 role: 'save-only',
88})
89```
90
91Use it in these cases:
92
93- You want to collect history for a user before you turn on recall.
94- A route must record turns but must not change the current answer.
95
96## Advanced
97
98### When recall and save run
99
100- The recall query is the text of the last user message. If there is no user text, recall does not run.
101- The middleware keeps the resolved scope for the request, so recall and save use the same scope.
102- Save runs only when the turn has both user text and assistant text.
103- If `save` throws, the middleware makes one receipt with `ok: false`, and `onSave` still runs with it.
104
105### Devtools events
106
107The middleware emits these events on `aiEventClient` from `@tanstack/ai-event-client`. The devtools panel reads them, and you can subscribe to them yourself.
108
109| Event | When |
110| --- | --- |
111| `memory:retrieve:started` | Recall starts. |
112| `memory:retrieve:completed` | Recall returns, with the fragment count and whether tools were added. |
113| `memory:persist:started` | A deferred save starts. |
114| `memory:persist:completed` | A save completes, with the receipt count. |
115| `memory:error` | `recall` or `save` threw (`phase: 'recall'` or `'save'`). It has `scope` only when the scope was already resolved. If the scope function failed or did not run, `scope` is not there. |
116
117When the adapter has `inspect`, the middleware also emits `memory:snapshot` with the stored records after each save.
118
119### How server memory gets to the browser panel
120
121Server events do not cross to the browser. The middleware adds one `CUSTOM` chunk named `memory:state` to the stream of each turn. The chunk has the recall metrics. When the adapter has `inspect`, it also has a snapshot of the store from the start of the turn. The client devtools bridge in `@tanstack/ai-client` reads it and emits the `memory:*` events in the browser.
122
123The snapshot is taken at the start of the turn, so the save of the current turn shows in the next turn.