Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

locks.md

196 lines7.2 KB

1---
2title: Locks
3id: locks
4order: 3
5description: "Let only one run at a time enter a critical section for a key, across workers. Use LockStore and withLocks, for example around sandbox create."
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​
19A lock makes one worker create the sandbox for a thread. A second run for that thread waits, then uses the same sandbox.
20​
21Only one caller at a time runs the critical section for a key.
22​
23## Quick setup
24​
25### 1. Provide a lock store
26​
27Add `withLocks` to the `middleware` array. Put it before the middleware that uses the lock:
28​
29```ts
30// api/chat.ts
31import {
32 chat,
33 chatParamsFromRequest,
34 toServerSentEventsResponse,
35} from '@tanstack/ai'
36import { withLocks, InMemoryLockStore } from '@tanstack/ai/locks'
37import { openaiText } from '@tanstack/ai-openai'
38import { onePrepPerThread } from './one-prep-per-thread'
39​
40// Create the store once, so all requests share it.
41// For more than one process, pass a distributed LockStore.
42const locks = new InMemoryLockStore()
43​
44export async function POST(request: Request) {
45 const { messages, threadId, runId } = await chatParamsFromRequest(request)
46​
47 const stream = chat({
48 adapter: openaiText('gpt-6.1-sol'),
49 messages,
50 threadId,
51 runId,
52 middleware: [withLocks(locks), onePrepPerThread],
53 })
54​
55 return toServerSentEventsResponse(stream)
57```
58​
59### 2. Use the lock in your middleware
60​
61Read the store with `getLocks(ctx)`. Then wrap the critical section in `withLock`:
62​
63```ts
64// one-prep-per-thread.ts
65import { defineChatMiddleware } from '@tanstack/ai'
66import { LocksCapability, getLocks } from '@tanstack/ai/locks'
67​
68export const onePrepPerThread = defineChatMiddleware({
69 name: 'one-prep-per-thread',
70 requires: [LocksCapability],
71 async onStart(ctx) {
72 const locks = getLocks(ctx)
73 await locks.withLock(`thread:${ctx.threadId}`, async (signal) => {
74 // Only one run for this thread is in here at a time.
75 // Pass `signal` to cancellable work when you use a lease-backed store.
76 console.log(`start ${ctx.threadId}`)
77 await new Promise((resolve) => setTimeout(resolve, 1000))
78 console.log(`end ${ctx.threadId}, lost lock: ${signal.aborted}`)
79 })
80 },
81})
82```
83​
84When two runs for the same thread start at the same time, the server console shows `start`, `end`, `start`, `end`. The two critical sections never overlap.
85​
86## How it works
87​
88- `withLocks(store)` is a middleware. It provides the `LocksCapability` in its `setup` hook. See [Capabilities](./middleware-advanced#capabilities).
89- `withLocks` does not lock a whole `chat()` turn. It only gives the store to later middleware. A consumer calls `withLock` when it needs the lock.
90- The capability is the same object everywhere. So each later middleware that reads `LocksCapability` sees the same store, including `@tanstack/ai-sandbox`.
91​
92When you use a sandbox, put `withLocks` before `withSandbox`:
93​
94```ts
95import { withLocks, InMemoryLockStore } from '@tanstack/ai/locks'
96import { withSandbox } from '@tanstack/ai-sandbox'
97import type { SandboxDefinition } from '@tanstack/ai-sandbox'
98​
99declare const sandbox: SandboxDefinition
100​
101const middleware = [
102 withLocks(new InMemoryLockStore()),
103 withSandbox(sandbox), // after the providers
105```
106​
107## When you need a lock
108​
109Use a lock when **more than one process or isolate** can enter the same critical section for the same key:
110​
111- **Sandbox resume-or-create** (`withSandbox` / `ensure`). Two runs for the same thread must not both create a provider sandbox. See [Sandbox Instance Durability](../sandbox/durability).
112- **Your own middleware.** Any work with more than one writer that you want to run one at a time across workers. For example, "one active job per thread".
113​
114You do not need a lock for:
115​
116- Local development with one process. `InMemoryLockStore` is enough there.
117- Saving chat state. Stores and `withPersistence` do that. See [Persistence Controls](../persistence/controls).
118​
119## Advanced
120​
121### The contract
122​
123```ts
124import type { LockStore } from '@tanstack/ai/locks'
125​
126declare const locks: LockStore
127​
128// Mutual exclusion for a key. Lease-backed stores abort `signal` on loss.
129await locks.withLock('thread:abc', async (signal) => {
130 // Critical section. Pass `signal` to cancellable work when you use leases.
131 void signal
132})
133```
134​
135| Piece | Role |
136| --- | --- |
137| `LockStore` | Interface: `withLock(key, fn)` |
138| `withLocks(store)` | Chat middleware that provides `LocksCapability` |
139| `InMemoryLockStore` | Implementation for one process (a promise chain per key) |
140| `defineLock(lock)` | Types your own `LockStore` inline |
141| `getLocks` / `provideLocks` | Low-level capability accessors for custom middleware |
142​
143`InMemoryLockStore` is correct **in one process only**:
144​
145- It runs callers for the same key one at a time.
146- When a critical section throws, the next caller still runs.
147- It never aborts its signal, because a process cannot lose its own lock.
148​
149### Implement a lock
150​
151Wrap your own mutual-exclusion primitive with `defineLock`. It checks the object against the contract inline, so you get autocomplete and need no `: LockStore` annotation.
152​
1531. Acquire the key.
1542. Run `fn`.
1553. Release the key when `fn` settles, also when it throws.
156​
157```ts
158import { defineLock } from '@tanstack/ai/locks'
159// Your distributed primitive. `acquire` waits until the key is free and returns
160// a `release` (plus, for leases, a `signal` that fires when ownership is lost).
161import { acquire } from './my-lock-backend'
162​
163export const locks = defineLock({
164 async withLock(key, fn) {
165 const { release, signal } = await acquire(key)
166 try {
167 return await fn(signal)
168 } finally {
169 release()
170 }
171 },
172})
173```
174​
175Wire it as middleware with `withLocks(locks)`. A production store must meet the rules in the next section.
176​
177### Distributed locks and leases
178​
179A deployment with more than one instance needs a **distributed** store, for example a Durable Object or Redis. A good store:
180​
1811. Lets one owner at a time hold each `key`.
1822. Uses **leases** (or something like them), so an owner that crashes cannot block the key forever.
1833. Passes an `AbortSignal` into `fn`. When the lease is lost, it **aborts** the signal. The callback then stops starting work that others can see, and passes the signal to cancellable dependencies.
184​
185A callback that ignores `signal` still type-checks, because `() => Promise<T>` is assignable. But a lease-backed store cannot protect you if the critical section keeps changing data after the abort.
186​
187To test your store:
188​
189- The chat store testkit has no lock conformance suite. Write your own tests for concurrency, release on throw, and lease expiry.
190- The Cloudflare Durable Object recipe is in the `ai-persistence/build-cloudflare-adapter` agent skill. It is a file that your app owns, not a published package.
191​
192On Redis, `upstashLocks()` from `@upstash/agentkit-tanstack-ai` is a published third-party `LockStore` on Upstash Redis. It renews its lease while `fn` runs, and it aborts `signal` if a renewal fails. See [Upstash](../community-adapters/upstash#locks).
193​
194### Provide a store without `withLocks`
195​
196If you already own a custom middleware, call `provideLocks(ctx, store)` in its `setup` hook, and list `LocksCapability` in its `provides`. Later middleware then reads the store with `getLocks(ctx)`.