Open History to see the last commit
1---
2title: Locks
3id: locks
4order: 3
5description: "Cross-instance mutual exclusion with LockStore and withLocks — coordination middleware for multi-worker critical sections (e.g. sandbox ensure)."
6keywords:
7 - tanstack ai
8 - locks
9 - withLocks
10 - LockStore
11 - InMemoryLockStore
12 - middleware
13 - multi-instance
14 - durable object
15 - AbortSignal
16 - coordination
17---
18
19Locks answer a different question from persistence:
20
21| Concern | Question | Seam |
22| --- | --- | --- |
23| **State** | What is durable? | Stores + `withPersistence` |
24| **Locks** | Who may run this critical section right now? | `LockStore` + `withLocks` |
25
26They live in **`@tanstack/ai`** as a middleware capability — not in
27`@tanstack/ai-persistence`, and never as a key on `AIPersistence.stores`.
28
29## When you need them
30
31Use locks when **more than one process or isolate** might enter the same critical
32section for the same key:
33
34- **Sandbox resume-or-create** (`withSandbox` / `ensure`) — two concurrent runs
35 for the same thread must not both create a provider sandbox. See
36 [Sandbox Instance Durability](../sandbox/durability).
37- **Your own middleware** — any multi-writer work you want to serialize across
38 workers (e.g. a custom “one active job per thread” gate).
39
40You do **not** need locks for:
41
42- Single-process local dev (optional: `InMemoryLockStore` is fine).
43- Ordinary chat state durability — that is stores, not mutexes.
44- Automatically locking an entire `chat()` turn — `withLocks` only **provides**
45 the capability; consumers call `withLock` when they need exclusion.
46
47## Wire it up
48
49```ts
50import { chat } from '@tanstack/ai'
51import { withLocks, InMemoryLockStore } from '@tanstack/ai/locks'
52import { grokBuildText } from '@tanstack/ai-grok-build'
53import type { ModelMessage } from '@tanstack/ai'
54
55const messages: Array<ModelMessage> = [{ role: 'user', content: 'hi' }]
56
57chat({
58 adapter: grokBuildText('grok-build'),
59 messages,
60 middleware: [
61 // Single process. Multi-instance: pass a distributed LockStore instead.
62 withLocks(new InMemoryLockStore()),
63 // later middleware can getLocks(ctx) / withSandbox will use the same token
64 ],
65})
66```
67
68Capability identity is by **object reference**. `withLocks` provides the shared
69`LocksCapability` from core; any later middleware that reads that token (including
70`@tanstack/ai-sandbox`) sees the same store.
71
72Typical order when composing with sandbox:
73
74```ts
75import { withLocks, InMemoryLockStore } from '@tanstack/ai/locks'
76import { withSandbox } from '@tanstack/ai-sandbox'
77import type { SandboxDefinition } from '@tanstack/ai-sandbox'
78
79declare const sandbox: SandboxDefinition
80
81const middleware = [
82 withLocks(new InMemoryLockStore()),
83 withSandbox(sandbox), // after providers
84]
85```
86
87## The contract
88
89```ts
90import type { LockStore } from '@tanstack/ai/locks'
91
92declare const locks: LockStore
93
94// Mutual exclusion for a key; lease-backed impls abort `signal` on loss.
95await locks.withLock('thread:abc', async (signal) => {
96 // critical section — pass `signal` to cancellable work when using leases
97 void signal
98})
99```
100
101| Piece | Role |
102| --- | --- |
103| `LockStore` | Interface: `withLock(key, fn)` |
104| `withLocks(store)` | Chat middleware that provides `LocksCapability` |
105| `InMemoryLockStore` | Process-local implementation (promise chain per key) |
106| `getLocks` / `provideLocks` | Low-level capability accessors for custom middleware |
107
108`InMemoryLockStore` is correct **within one process only**. It serializes
109callers for the same key, does not poison the chain when a critical section
110throws, and never aborts its signal (ownership cannot be lost in-process).
111
112## Implement a lock
113
114Wrap your own mutual-exclusion primitive with `defineLock`. It types the object
115against the contract inline (autocomplete, no `: LockStore` annotation). Acquire
116the key, run `fn`, and release when `fn` settles (whether it resolves or throws):
117
118```ts
119import { defineLock } from '@tanstack/ai/locks'
120// Your distributed primitive. `acquire` waits until the key is free and returns
121// a `release` (plus, for leases, a `signal` that fires when ownership is lost).
122import { acquire } from './my-lock-backend'
123
124export const locks = defineLock({
125 async withLock(key, fn) {
126 const { release, signal } = await acquire(key)
127 try {
128 return await fn(signal)
129 } finally {
130 release()
131 }
132 },
133})
134```
135
136Wire it as middleware with `withLocks(locks)`. The requirements a production
137store must meet are covered below.
138
139## Distributed locks and leases
140
141Multi-instance deployments need a **distributed** implementation (Durable Object,
142Redis, etc.). A good store:
143
1441. Serializes owners per `key`.
1452. Uses **leases** (or equivalent) so a crashed owner cannot block forever.
1463. Passes an `AbortSignal` into `fn`; when the lease is lost, **abort** so the
147 callback stops starting externally visible work and passes the signal to
148 cancellable dependencies.
149
150Callbacks that ignore `signal` still type-check (`() => Promise<T>` is
151assignable), but lease-backed backends cannot protect you if the critical
152section keeps mutating after abort.
153
154There is no shared lock conformance suite in the chat store testkit — write
155targeted tests for concurrency, release-on-throw, and lease expiry for your
156backend. The Cloudflare Durable Object recipe lives in the
157`ai-persistence/build-cloudflare-adapter` agent skill (app-owned file,
158not a shipped package).
159
160## Consume in custom middleware
161
162```ts
163import { defineChatMiddleware } from '@tanstack/ai'
164import { LocksCapability, getLocks } from '@tanstack/ai/locks'
165
166const serializePerThread = defineChatMiddleware({
167 name: 'serialize-per-thread',
168 requires: [LocksCapability],
169 async onStart(ctx) {
170 const locks = getLocks(ctx)
171 await locks.withLock(`thread:${ctx.threadId}`, async (signal) => {
172 // critical section — honor `signal` under lease-backed locks
173 void signal
174 })
175 },
176})
177```
178
179Or provide without `withLocks` by calling `provideLocks` in your own
180`setup` hook if you already own a custom middleware.
181
182## See also
183
184- [Middleware](./middleware) — capability bus and lifecycle
185- [Sandboxes](../sandbox/overview) — sandbox middleware overview
186- [Sandbox Instance Durability](../sandbox/durability) — primary product consumer (`withSandbox` / `ensure`)
187- [Persistence Controls](../persistence/controls) — compose state stores from different systems
188- [Build Your Own Adapter](../persistence/build-your-own-adapter) — chat store contracts