async-bulkhead-llm 3.15.1 → 3.15.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -0
- package/README.md +140 -1768
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -1,1300 +1,135 @@
|
|
|
1
1
|
# async-bulkhead-llm
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Decide whether an LLM call should run — before it runs.**
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/async-bulkhead-llm)
|
|
6
|
+
[](https://github.com/janbalangue/async-bulkhead-llm/actions/workflows/ci.yml)
|
|
7
|
+
[](https://github.com/janbalangue/async-bulkhead-llm/blob/main/LICENSE)
|
|
6
8
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
## Features
|
|
10
|
-
|
|
11
|
-
- ✅ Hard **max in-flight** concurrency (`maxConcurrent`)
|
|
12
|
-
- ✅ **Atomic versioned limit updates** — apply concurrency, queue, token budget, priority reserve, and admission-class floors/ceilings as one revisioned snapshot
|
|
13
|
-
- ✅ **Protected admission-class floors** — reserve per-class concurrency and token capacity before requests borrow from the shared remainder
|
|
14
|
-
- ✅ **Bounded admission classes** — isolate policy classes with hard per-class concurrency and in-flight token ceilings
|
|
15
|
-
- ✅ **Admission-linearized revisions** — every admitted or bypassed lifecycle retains the exact limit revision that made the decision
|
|
16
|
-
- ✅ **Token-aware admission** — reserves against estimated input + max output tokens
|
|
17
|
-
- ✅ **Progressive reconciliation** — release processed input and generated-output reservation during live streams
|
|
18
|
-
- ✅ **Token refund** — reclaim unused budget capacity from actual usage post-completion
|
|
19
|
-
- ✅ **Model-aware estimation** — per-model character ratios for known providers
|
|
20
|
-
- ✅ **Per-request model** — mixed-model routing through a single bulkhead
|
|
21
|
-
- ✅ **Multimodal content** — text blocks counted; opaque blocks ignored by default or charged a configurable per-block reservation (`opaqueBlockTokens`)
|
|
22
|
-
- ✅ **Full-request estimation** — `system` prompts counted natively; `extraInputTokens` carries caller-computed costs (tool schemas, provider-priced media)
|
|
23
|
-
- ✅ **Per-call reservation override** — gateways with their own estimate can bypass the estimator via `reservation` on `acquire()`/`run()`/`wouldAdmit()`
|
|
24
|
-
- ✅ **Fail-fast by default** — shed load early, never silently queue
|
|
25
|
-
- ✅ **Observe/shadow mode** — measure capacity-policy impact while still executing selected would-be-rejected calls
|
|
26
|
-
- ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
|
|
27
|
-
- ✅ **In-flight deduplication** — identical requests share one LLM call; hashed keys, whole-request equality
|
|
28
|
-
- ✅ **Custom dedup key + per-tenant scope** — bring your own equivalence function; `dedupScope` isolates tenants
|
|
29
|
-
- ✅ **Streaming-safe deduplication** — single-consumer results are never silently shared; `shareResult` fan-out hook + per-call `dedup: false` opt-out
|
|
30
|
-
- ✅ **Exact reservation preview** — `estimate()` exposes the reservation admission will use, and its result can be passed back verbatim as the per-call `reservation`
|
|
31
|
-
- ✅ **Adaptive estimation** — `createAdaptiveTokenEstimator()` self-calibrates per-model input estimates from observed usage
|
|
32
|
-
- ✅ **Advisory capacity snapshots** — `wouldAdmit(request, { detail: true })` returns the same capacity numbers rejections carry
|
|
33
|
-
- ✅ **Stable admission IDs** — correlate gateway requests, traces, usage, and release
|
|
34
|
-
- ✅ **Ordered usage events** — sequence-numbered hold changes for external coordinators
|
|
35
|
-
- ✅ **Event hooks** — admitted and bypassed lifecycles have separate telemetry events
|
|
36
|
-
- ✅ **Graceful shutdown** — `close()` + `drain()`, with an optional bounded wait: `drain({ timeoutMs })`
|
|
37
|
-
- ✅ Optional **AbortSignal** and **timeout** cancellation
|
|
38
|
-
- ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
|
|
39
|
-
- ✅ Zero dependencies beyond `async-bulkhead-ts`
|
|
40
|
-
- ✅ ESM + CJS
|
|
41
|
-
- ✅ Node.js **20+**
|
|
42
|
-
|
|
43
|
-
Non-goals (by design):
|
|
44
|
-
|
|
45
|
-
- ❌ No retries
|
|
46
|
-
- ❌ No provider SDK — bring your own client
|
|
47
|
-
- ❌ No distributed coordination
|
|
48
|
-
- ❌ No cost accounting — token estimation is for load-shedding only
|
|
49
|
-
|
|
50
|
-
---
|
|
51
|
-
|
|
52
|
-
## Competitive Matrix (LLM Workloads)
|
|
53
|
-
|
|
54
|
-
| Capability / Library | async-bulkhead-llm | LangChain / LlamaIndex | OpenAI SDK (raw) | p-limit / Bottleneck | cockatiel / polly |
|
|
55
|
-
|---------------------|--------------------|------------------------|------------------|---------------------|-------------------|
|
|
56
|
-
| **Primary goal** | LLM admission control (cost + concurrency) | Orchestration / pipelines | API client | Concurrency / scheduling | Resilience patterns |
|
|
57
|
-
| **Fail-fast by default** | ✅ Yes | ❌ No | ❌ No | ❌ No | ⚠️ Depends |
|
|
58
|
-
| **Token-aware admission** | ✅ Yes (pre-admission budget) | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
59
|
-
| **Token refund (post-call correction)** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
60
|
-
| **Cost ceiling enforcement** | ✅ Yes (`tokenBudget`) | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
61
|
-
| **Concurrency limits** | ✅ Yes | ⚠️ Indirect | ❌ No | ✅ Yes | ⚠️ Indirect |
|
|
62
|
-
| **Bounded queue (optional)** | ✅ Yes | ⚠️ Internal | ❌ No | ✅ Yes | ⚠️ Indirect |
|
|
63
|
-
| **Fail-fast overload handling** | ✅ Core feature | ❌ No | ❌ No | ❌ No | ⚠️ Indirect |
|
|
64
|
-
| **Observe/shadow rollout mode** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
65
|
-
| **In-flight deduplication** | ✅ Yes | ⚠️ Partial caching | ❌ No | ❌ No | ❌ No |
|
|
66
|
-
| **Custom dedup key** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
67
|
-
| **Model-aware estimation** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
68
|
-
| **Per-request model routing** | ✅ Yes | ✅ Yes | ✅ Yes | ❌ No | ❌ No |
|
|
69
|
-
| **Multimodal-aware estimation** | ✅ Yes (text-only counted) | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
70
|
-
| **Abort / timeout (admission)** | ✅ Yes | ⚠️ Partial | ⚠️ SDK-level | ⚠️ Partial | ✅ Yes |
|
|
71
|
-
| **Event hooks (metrics/logging)** | ✅ Yes | ❌ No | ❌ No | ❌ No | ⚠️ Limited |
|
|
72
|
-
| **Graceful shutdown (drain/close)** | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
|
|
73
|
-
| **Retries / fallback** | ❌ No | ⚠️ Yes | ❌ No | ❌ No | ✅ Yes |
|
|
74
|
-
| **LLM orchestration (chains/agents)** | ❌ No | ✅ Yes | ❌ No | ❌ No | ❌ No |
|
|
75
|
-
|
|
76
|
-
---
|
|
77
|
-
|
|
78
|
-
### Quick positioning
|
|
79
|
-
|
|
80
|
-
- **LangChain / LlamaIndex** → *what to run* (orchestration)
|
|
81
|
-
- **OpenAI SDK** → *how to call the provider*
|
|
82
|
-
- **p-limit / Bottleneck** → *how many tasks run*
|
|
83
|
-
- **cockatiel / polly** → *what happens after failure*
|
|
84
|
-
- **async-bulkhead-llm** → **whether a request should run at all**
|
|
85
|
-
|
|
86
|
-
---
|
|
87
|
-
|
|
88
|
-
### Rule of thumb
|
|
89
|
-
|
|
90
|
-
> If you want to **build LLM pipelines**, use LangChain.
|
|
91
|
-
> If you want to **protect your system and budget under load**, use async-bulkhead-llm.
|
|
92
|
-
|
|
93
|
-
---
|
|
94
|
-
|
|
95
|
-
### Key differentiator
|
|
96
|
-
|
|
97
|
-
> **Most LLM tooling optimizes execution.
|
|
98
|
-
> async-bulkhead-llm optimizes survival under load.**
|
|
99
|
-
|
|
100
|
-
It enforces:
|
|
101
|
-
|
|
102
|
-
- **concurrency ceilings**
|
|
103
|
-
- **token budget ceilings**
|
|
104
|
-
- **fail-fast admission**
|
|
105
|
-
|
|
106
|
-
before a request ever reaches your provider.
|
|
107
|
-
|
|
108
|
-
---
|
|
109
|
-
|
|
110
|
-
## Install
|
|
111
|
-
|
|
112
|
-
```bash
|
|
113
|
-
npm install async-bulkhead-llm
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
---
|
|
117
|
-
|
|
118
|
-
## Quick Start
|
|
119
|
-
|
|
120
|
-
```ts
|
|
121
|
-
import { createLLMBulkhead } from 'async-bulkhead-llm';
|
|
122
|
-
|
|
123
|
-
const bulkhead = createLLMBulkhead({
|
|
124
|
-
model: 'claude-sonnet-4',
|
|
125
|
-
maxConcurrent: 10,
|
|
126
|
-
});
|
|
127
|
-
|
|
128
|
-
const request = {
|
|
129
|
-
messages: [{ role: 'user', content: 'Summarise this document...' }],
|
|
130
|
-
max_tokens: 1024,
|
|
131
|
-
};
|
|
132
|
-
|
|
133
|
-
const result = await bulkhead.run(request, async () => {
|
|
134
|
-
return callYourLLMProvider(request);
|
|
135
|
-
});
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
---
|
|
139
|
-
|
|
140
|
-
## What's New in v3.15 — Protected admission-class floors
|
|
141
|
-
|
|
142
|
-
v3.15 lets each statically configured admission class reserve a strict local
|
|
143
|
-
concurrency floor and, when token admission is enabled, a strict in-flight
|
|
144
|
-
token floor. Capacity above all floors forms a shared remainder that any class
|
|
145
|
-
may borrow, subject to its hard class ceilings and the enclosing global limits.
|
|
146
|
-
|
|
147
|
-
```ts
|
|
148
|
-
const bulkhead = createLLMBulkhead({
|
|
149
|
-
model: "gpt-4o",
|
|
150
|
-
maxConcurrent: 12,
|
|
151
|
-
tokenBudget: { budget: 24_000 },
|
|
152
|
-
admissionClasses: {
|
|
153
|
-
defaultClass: "standard",
|
|
154
|
-
classes: {
|
|
155
|
-
premium: {
|
|
156
|
-
protectedConcurrent: 6,
|
|
157
|
-
maxConcurrent: 10,
|
|
158
|
-
protectedInFlightTokens: 12_000,
|
|
159
|
-
maxInFlightTokens: 20_000,
|
|
160
|
-
},
|
|
161
|
-
standard: {
|
|
162
|
-
protectedConcurrent: 2,
|
|
163
|
-
maxConcurrent: 6,
|
|
164
|
-
protectedInFlightTokens: 4_000,
|
|
165
|
-
maxInFlightTokens: 10_000,
|
|
166
|
-
},
|
|
167
|
-
},
|
|
168
|
-
},
|
|
169
|
-
});
|
|
170
|
-
```
|
|
171
|
-
|
|
172
|
-
In this example, eight concurrency slots and 16,000 tokens are protected. The
|
|
173
|
-
remaining four slots and 8,000 tokens are shared. Premium may exceed its floor
|
|
174
|
-
by borrowing from that shared remainder, but it cannot consume the two slots
|
|
175
|
-
or 4,000 tokens protected for standard.
|
|
176
|
-
|
|
177
|
-
Floors are strict reservations, not idle-capacity lending. Unused protected
|
|
178
|
-
capacity remains available only to its owning class. Cross-class lending of an
|
|
179
|
-
idle floor requires a gateway or control plane to install a higher-revision
|
|
180
|
-
snapshot. Increasing a floor never revokes active work: new borrowing pauses
|
|
181
|
-
until completions restore the guarantee by attrition.
|
|
182
|
-
|
|
183
|
-
`stats().admissionClasses` now reports the shared remainder plus each class's
|
|
184
|
-
protected and borrowed usage. Rejections caused by preserving another class's
|
|
185
|
-
floor use `constraint: "admission_class_protection"` and include the shared
|
|
186
|
-
capacity snapshot. Omitting both floor fields preserves v3.14 admission
|
|
187
|
-
behavior.
|
|
188
|
-
|
|
189
|
-
---
|
|
190
|
-
|
|
191
|
-
## What's New in v3.14 — Bounded admission classes
|
|
192
|
-
|
|
193
|
-
v3.14 adds a bounded hierarchical admission layer inside one bulkhead. A
|
|
194
|
-
trusted gateway can map tenant or application identity to a small, static set
|
|
195
|
-
of policy classes, then enforce hard concurrency and in-flight token ceilings
|
|
196
|
-
for each class while retaining the enclosing global limits.
|
|
197
|
-
|
|
198
|
-
```ts
|
|
199
|
-
const bulkhead = createLLMBulkhead({
|
|
200
|
-
model: "gpt-4o",
|
|
201
|
-
maxConcurrent: 12,
|
|
202
|
-
tokenBudget: { budget: 24_000 },
|
|
203
|
-
admissionClasses: {
|
|
204
|
-
defaultClass: "standard",
|
|
205
|
-
classes: {
|
|
206
|
-
premium: { maxConcurrent: 8, maxInFlightTokens: 18_000 },
|
|
207
|
-
standard: { maxConcurrent: 4, maxInFlightTokens: 6_000 },
|
|
208
|
-
},
|
|
209
|
-
},
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
await bulkhead.run(request, callProvider, {
|
|
213
|
-
admissionClass: "premium",
|
|
214
|
-
dedupScope: trustedTenantId,
|
|
215
|
-
});
|
|
216
|
-
```
|
|
217
|
-
|
|
218
|
-
The class table is fixed at construction. Unknown IDs throw instead of creating
|
|
219
|
-
unbounded state or metric cardinality. Class ceilings are fail-fast and are
|
|
220
|
-
checked together with global concurrency, priority-adjusted token budget, and
|
|
221
|
-
shutdown state. `applyLimits()` may update class numbers atomically, but every
|
|
222
|
-
snapshot must contain exactly the construction-time class keys.
|
|
223
|
-
|
|
224
|
-
When in-flight deduplication is enabled, the selected admission class is an
|
|
225
|
-
automatic deduplication partition. Identical requests in `premium` and
|
|
226
|
-
`standard` therefore execute independently rather than sharing the first
|
|
227
|
-
class's admission decision or queue position. `dedupScope` remains necessary
|
|
228
|
-
for tenant-level isolation inside a class.
|
|
229
|
-
|
|
230
|
-
Admission classes are intentionally policy buckets, not raw tenant IDs. The
|
|
231
|
-
library does not authenticate callers, assign identities, implement weighted
|
|
232
|
-
fairness, reserve borrowable floors, or coordinate capacity across processes.
|
|
233
|
-
Those responsibilities remain in the gateway and control plane. When
|
|
234
|
-
in-flight deduplication is enabled, `admissionClass` also does not replace
|
|
235
|
-
`dedupScope`; include trusted tenant identity in `dedupScope` when results must
|
|
236
|
-
not be shared across tenants.
|
|
237
|
-
|
|
238
|
-
Lifecycle results, run contexts, tokens, usage reports, capacity details, and
|
|
239
|
-
telemetry events now carry `admissionClass` when configured. Rejection detail
|
|
240
|
-
also identifies whether the binding constraint was `global` or
|
|
241
|
-
`admission_class`, and `stats().admissionClasses` exposes bounded per-class
|
|
242
|
-
accounting.
|
|
243
|
-
|
|
244
|
-
---
|
|
245
|
-
|
|
246
|
-
## What's New in v3.13 — Progressive reconciliation
|
|
247
|
-
|
|
248
|
-
Gateways that receive cumulative streaming usage may opt into shrinking the
|
|
249
|
-
active hold before request completion:
|
|
250
|
-
|
|
251
|
-
```ts
|
|
252
|
-
const report = ctx!.reportUsage(
|
|
253
|
-
{ input: actualInput, output: cumulativeOutput },
|
|
254
|
-
{
|
|
255
|
-
remainingOutputTokens: Math.max(0, maxOutput - cumulativeOutput),
|
|
256
|
-
safetyMarginTokens: 128,
|
|
257
|
-
},
|
|
258
|
-
);
|
|
259
|
-
```
|
|
260
|
-
|
|
261
|
-
The progressive hold is:
|
|
262
|
-
|
|
263
|
-
```text
|
|
264
|
-
remainingOutputTokens + safetyMarginTokens + output overrun
|
|
265
|
-
```
|
|
266
|
-
|
|
267
|
-
This lets processed input and already-generated output stop occupying the
|
|
268
|
-
in-flight budget. The caller must use the option only after prefill is known to
|
|
269
|
-
be complete and must derive `remainingOutputTokens` from an authoritative
|
|
270
|
-
provider output cap. Omitting the second argument preserves the legacy behavior
|
|
271
|
-
of retaining the full output reservation until release. Final `release()`
|
|
272
|
-
settlement remains authoritative.
|
|
273
|
-
|
|
274
|
-
Progressive updates share the existing sequence-numbered `usage` event. Events
|
|
275
|
-
include `progressive`, `remainingOutputTokens`, and `safetyMarginTokens` when the
|
|
276
|
-
new mode is used.
|
|
277
|
-
|
|
278
|
-
---
|
|
279
|
-
|
|
280
|
-
## What's New in v3.12 — Fail-closed startup
|
|
281
|
-
|
|
282
|
-
v3.12 allows `maxConcurrent: 0` at construction time. A gateway managed by an
|
|
283
|
-
external control plane can now open its listener and health endpoint without
|
|
284
|
-
admitting requests before its first valid grant arrives.
|
|
285
|
-
|
|
286
|
-
```ts
|
|
287
|
-
const bulkhead = createLLMBulkhead({
|
|
288
|
-
model: "gpt-4o",
|
|
289
|
-
maxConcurrent: 0,
|
|
290
|
-
maxQueue: 0,
|
|
291
|
-
initialRevision: 0,
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
// Later, after a validated control-plane grant:
|
|
295
|
-
bulkhead.applyLimits({
|
|
296
|
-
revision: 1,
|
|
297
|
-
maxConcurrent: 8,
|
|
298
|
-
maxQueue: 0,
|
|
299
|
-
});
|
|
300
|
-
```
|
|
301
|
-
|
|
302
|
-
A zero-capacity instance rejects new work with `concurrency_limit`; it does not
|
|
303
|
-
queue work unless `maxQueue` is explicitly greater than zero.
|
|
304
|
-
|
|
305
|
-
---
|
|
306
|
-
|
|
307
|
-
## What's New in v3.11.1 — Security and package integrity patch
|
|
308
|
-
|
|
309
|
-
v3.11.1 is the supported patch release for the v3.11 admission-provenance
|
|
310
|
-
changes. It preserves the v3.11 runtime API and behavior while fixing the
|
|
311
|
-
release artifact and development dependency audit issues.
|
|
312
|
-
|
|
313
|
-
### Highlights
|
|
314
|
-
|
|
315
|
-
- **Security maintenance:** the development lockfile now resolves
|
|
316
|
-
`brace-expansion` 5.0.8 through the ESLint/minimatch toolchain, clearing the
|
|
317
|
-
reported high-severity audit finding. This package is not part of the
|
|
318
|
-
published runtime dependency graph.
|
|
319
|
-
- **Immutable replacement for v3.11.0:** publish and install v3.11.1 instead of
|
|
320
|
-
retrying the conflicting v3.11.0 tarball whose registry metadata and served
|
|
321
|
-
bytes produced an `EINTEGRITY` failure.
|
|
322
|
-
- **Corrected strict snapshot test:** the admit-capacity assertion now includes
|
|
323
|
-
`limitRevision: 0`, matching the additive v3.11 event shape.
|
|
324
|
-
- **No runtime migration:** code already written for v3.11.0 requires no API
|
|
325
|
-
changes. All admission-linearized revision behavior remains the same.
|
|
326
|
-
|
|
327
|
-
```bash
|
|
328
|
-
npm install async-bulkhead-llm@3.11.1
|
|
329
|
-
```
|
|
330
|
-
|
|
331
|
-
---
|
|
332
|
-
|
|
333
|
-
## What's New in v3.11 — Admission-linearized limit revisions
|
|
334
|
-
|
|
335
|
-
v3.11 makes every capacity decision traceable to the exact immutable limit
|
|
336
|
-
revision that produced it. The revision is captured at the admission or
|
|
337
|
-
rejection decision itself, so a concurrent reconfiguration cannot relabel work
|
|
338
|
-
that was evaluated under an earlier snapshot.
|
|
339
|
-
|
|
340
|
-
### Highlights
|
|
341
|
-
|
|
342
|
-
- **Exact admission provenance:** successful `acquire()` results, `LLMToken`,
|
|
343
|
-
and `LLMRunContext` expose `limitRevision`.
|
|
344
|
-
- **Lifecycle consistency:** `admit`, `usage`, `release`, `bypass`,
|
|
345
|
-
`bypassUsage`, and `bypassRelease` events retain that same revision for the
|
|
346
|
-
full lifetime of the execution.
|
|
347
|
-
- **Revisioned rejection snapshots:** `LLMRejectDetail.limitRevision` records
|
|
348
|
-
the snapshot used for a capacity rejection, while every `reject` event also
|
|
349
|
-
includes a top-level `limitRevision`.
|
|
350
|
-
- **Race-safe reporting:** gateways no longer need to call `limits()` after
|
|
351
|
-
admission, which could observe a newer revision than the one that actually
|
|
352
|
-
authorized the request.
|
|
353
|
-
- **Additive API change:** existing call sites continue to work. Tests or
|
|
354
|
-
consumers that assert exact event or detail object shapes must include the
|
|
355
|
-
new `limitRevision` field.
|
|
356
|
-
|
|
357
|
-
```ts
|
|
358
|
-
const acquired = await bulkhead.acquire(request);
|
|
359
|
-
|
|
360
|
-
if (acquired.ok) {
|
|
361
|
-
console.log(acquired.admissionId);
|
|
362
|
-
console.log(acquired.limitRevision);
|
|
363
|
-
console.log(acquired.token.limitRevision); // same immutable revision
|
|
364
|
-
acquired.token.release();
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
await bulkhead.run(request, async (_signal, ctx) => {
|
|
368
|
-
auditLog({
|
|
369
|
-
admissionId: ctx?.admissionId,
|
|
370
|
-
limitRevision: ctx?.limitRevision,
|
|
371
|
-
});
|
|
372
|
-
|
|
373
|
-
return callYourLLMProvider(request);
|
|
374
|
-
});
|
|
375
|
-
|
|
376
|
-
bulkhead.on('reject', ({ reason, limitRevision, detail }) => {
|
|
377
|
-
auditLog({ reason, limitRevision, capacity: detail });
|
|
378
|
-
});
|
|
379
|
-
```
|
|
380
|
-
|
|
381
|
-
The revision identifies the library limit snapshot, not an external control
|
|
382
|
-
plane grant by itself. A gateway can associate that revision with its own
|
|
383
|
-
immutable grant metadata to provide end-to-end admission provenance.
|
|
384
|
-
|
|
385
|
-
---
|
|
386
|
-
|
|
387
|
-
## What's New in v3.10 — Atomic, versioned admission limits
|
|
388
|
-
|
|
389
|
-
v3.10 makes `async-bulkhead-llm` safer to operate from gateways and distributed
|
|
390
|
-
control-plane agents. All mutable admission limits can now be replaced in one
|
|
391
|
-
validated, revisioned snapshot instead of being updated independently.
|
|
392
|
-
|
|
393
|
-
### Highlights
|
|
394
|
-
|
|
395
|
-
- **Atomic updates:** `maxConcurrent`, `maxQueue`, token budget, and
|
|
396
|
-
high-priority reserve change together or not at all.
|
|
397
|
-
- **Stale-update protection:** every snapshot carries a strictly increasing
|
|
398
|
-
`revision`; equal or older revisions are rejected without mutating state.
|
|
399
|
-
- **Shrink by attrition:** lowering limits never cancels in-flight work or
|
|
400
|
-
already accepted queue waiters. New work is admitted only as capacity returns.
|
|
401
|
-
- **Immediate scale-up:** raising concurrency starts eligible queued work as soon
|
|
402
|
-
as the new snapshot is applied.
|
|
403
|
-
- **Runtime kill switch:** setting `maxConcurrent` to `0` stops new admissions
|
|
404
|
-
while existing work drains normally.
|
|
405
|
-
- **Observable state:** `limits()`, `stats().limits`, and the `reconfigure` event
|
|
406
|
-
expose the active revision and previous/current snapshots.
|
|
407
|
-
|
|
408
|
-
```ts
|
|
409
|
-
const result = bulkhead.applyLimits({
|
|
410
|
-
revision: 42,
|
|
411
|
-
maxConcurrent: 12,
|
|
412
|
-
maxQueue: 0,
|
|
413
|
-
tokenBudget: {
|
|
414
|
-
budget: 120_000,
|
|
415
|
-
highPriorityReserve: 20_000,
|
|
416
|
-
},
|
|
417
|
-
});
|
|
418
|
-
|
|
419
|
-
if (!result.applied) {
|
|
420
|
-
// Equal and lower revisions are ignored without mutation.
|
|
421
|
-
console.log(result.reason); // "stale_revision"
|
|
422
|
-
}
|
|
423
|
-
```
|
|
424
|
-
|
|
425
|
-
Use `initialRevision` when restoring persisted control-plane state. A configured
|
|
426
|
-
token budget must remain configured in every later snapshot; estimator and
|
|
427
|
-
output-cap policy remain construction-time settings. `setBudget()` is still
|
|
428
|
-
supported for local use, but distributed integrations should use
|
|
429
|
-
`applyLimits()` exclusively so a single authority owns the revision sequence.
|
|
430
|
-
|
|
431
|
-
---
|
|
432
|
-
|
|
433
|
-
## What's New in v3.9 — First-class observe mode
|
|
434
|
-
|
|
435
|
-
v3.9 adds an explicit rollout mode for measuring admission policy before fully
|
|
436
|
-
enforcing it. `run()` still attempts normal admission first. When a configured
|
|
437
|
-
capacity-related rejection occurs, observe mode executes the callback without
|
|
438
|
-
holding a concurrency slot or token reservation and records the bypass on a
|
|
439
|
-
separate telemetry surface.
|
|
440
|
-
|
|
441
|
-
```ts
|
|
442
|
-
const result = await bulkhead.run(
|
|
443
|
-
request,
|
|
444
|
-
async (signal, ctx) => {
|
|
445
|
-
logger.info({
|
|
446
|
-
admissionId: ctx?.admissionId,
|
|
447
|
-
admission: ctx?.admission, // "admitted" | "bypassed"
|
|
448
|
-
bypassReason: ctx?.bypassReason, // set only for bypassed work
|
|
449
|
-
bypassDetail: ctx?.bypassDetail, // capacity snapshot, when available
|
|
450
|
-
});
|
|
451
|
-
|
|
452
|
-
return callYourLLMProvider(request, {
|
|
453
|
-
signal,
|
|
454
|
-
onUsage: (usage) => ctx?.reportUsage(usage),
|
|
455
|
-
});
|
|
456
|
-
},
|
|
457
|
-
{ mode: "observe" },
|
|
458
|
-
);
|
|
459
|
-
```
|
|
460
|
-
|
|
461
|
-
By default, observe mode may bypass these capacity outcomes:
|
|
462
|
-
|
|
463
|
-
```ts
|
|
464
|
-
"budget_limit" | "concurrency_limit" | "queue_limit" | "timeout"
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
Shutdown, caller cancellation, and unsafe deduplication fan-out remain hard
|
|
468
|
-
failures. Observe mode is therefore not a global "ignore every rejection"
|
|
469
|
-
switch.
|
|
470
|
-
|
|
471
|
-
### Restrict which outcomes may be bypassed
|
|
472
|
-
|
|
473
|
-
Use `shadowReasons` to roll out one policy at a time:
|
|
474
|
-
|
|
475
|
-
```ts
|
|
476
|
-
await bulkhead.run(request, fn, {
|
|
477
|
-
mode: "observe",
|
|
478
|
-
shadowReasons: ["budget_limit"],
|
|
479
|
-
});
|
|
480
|
-
```
|
|
481
|
-
|
|
482
|
-
An empty `shadowReasons` array keeps normal enforcement while still exposing
|
|
483
|
-
`ctx.admission === "admitted"` to callbacks.
|
|
484
|
-
|
|
485
|
-
### Admitted and bypassed callback context
|
|
486
|
-
|
|
487
|
-
Normally admitted calls receive the same context with:
|
|
488
|
-
|
|
489
|
-
```ts
|
|
490
|
-
ctx.admission === "admitted"
|
|
491
|
-
ctx.bypassReason === undefined
|
|
492
|
-
```
|
|
493
|
-
|
|
494
|
-
Bypassed calls receive a `shadow-`-prefixed `admissionId`, the exact evaluated
|
|
495
|
-
reservation, the bypass reason, and the associated capacity detail. Their
|
|
496
|
-
`reportUsage()` snapshots always report `held: 0`, because observed work does
|
|
497
|
-
not consume bulkhead accounting capacity.
|
|
498
|
-
|
|
499
|
-
### Separate observe telemetry
|
|
500
|
-
|
|
501
|
-
Bypassed work does not increment normal `admit`/`release` counters. It is
|
|
502
|
-
reported through:
|
|
503
|
-
|
|
504
|
-
```ts
|
|
505
|
-
bulkhead.on("bypass", listener);
|
|
506
|
-
bulkhead.on("bypassUsage", listener);
|
|
507
|
-
bulkhead.on("bypassRelease", listener);
|
|
508
|
-
|
|
509
|
-
const observe = bulkhead.stats().observe;
|
|
510
|
-
// {
|
|
511
|
-
// bypassed,
|
|
512
|
-
// raceBypassed,
|
|
513
|
-
// bypassedByReason,
|
|
514
|
-
// usageReported,
|
|
515
|
-
// totalInputTokens,
|
|
516
|
-
// totalOutputTokens,
|
|
517
|
-
// }
|
|
518
|
-
```
|
|
519
|
-
|
|
520
|
-
`raceBypassed` counts calls whose advisory check passed but whose authoritative
|
|
521
|
-
acquisition later rejected—for example, a queued request that timed out while
|
|
522
|
-
capacity changed. This makes preview-to-admission races visible instead of
|
|
523
|
-
silently merging them into ordinary bypasses.
|
|
524
|
-
|
|
525
|
-
> Observe mode intentionally allows work to proceed without capacity
|
|
526
|
-
> protection. Use it for policy calibration, migration, and audit periods—not
|
|
527
|
-
> as the steady-state overload posture of a saturated service.
|
|
528
|
-
|
|
529
|
-
---
|
|
530
|
-
|
|
531
|
-
## What's New in v3.8 — Feedback and shutdown ergonomics
|
|
532
|
-
|
|
533
|
-
### Bounded drain
|
|
534
|
-
|
|
535
|
-
`drain()` without arguments is unchanged (`Promise<void>`). With a deadline,
|
|
536
|
-
it always *resolves* — never rejects — with what happened:
|
|
537
|
-
|
|
538
|
-
```ts
|
|
539
|
-
bulkhead.close();
|
|
540
|
-
const result = await bulkhead.drain({ timeoutMs: 10_000 });
|
|
541
|
-
if (!result.drained) {
|
|
542
|
-
log.warn("abandoning shutdown wait", {
|
|
543
|
-
inFlight: result.inFlight,
|
|
544
|
-
pending: result.pending,
|
|
545
|
-
});
|
|
546
|
-
}
|
|
547
|
-
```
|
|
548
|
-
|
|
549
|
-
The deadline never cancels or interrupts in-flight work and leaves the
|
|
550
|
-
bulkhead's accounting untouched — work that finishes later still releases
|
|
551
|
-
normally. It exists so a shutdown path can log what it is abandoning and
|
|
552
|
-
proceed, instead of parking forever behind one stuck upstream stream.
|
|
553
|
-
`timeoutMs: 0` is an immediate "is it drained right now?" snapshot.
|
|
554
|
-
|
|
555
|
-
### Capacity detail from `wouldAdmit()`
|
|
556
|
-
|
|
557
|
-
Routing layers choosing between pools want the numbers, not just the boolean:
|
|
558
|
-
|
|
559
|
-
```ts
|
|
560
|
-
const { admit, reason, detail } = bulkhead.wouldAdmit(request, {
|
|
561
|
-
detail: true,
|
|
562
|
-
});
|
|
563
|
-
// detail is the same LLMRejectDetail snapshot real rejections carry,
|
|
564
|
-
// present on admit: true as well (detail.tokenBudget.requested is the
|
|
565
|
-
// reservation this request needs).
|
|
566
|
-
```
|
|
567
|
-
|
|
568
|
-
Omitted by default, so existing callers see the exact v3.7 result shape.
|
|
569
|
-
|
|
570
|
-
### `estimate()` round-trips as the reservation override
|
|
571
|
-
|
|
572
|
-
The frozen object returned by `estimate()` can now be passed straight back:
|
|
573
|
-
|
|
574
|
-
```ts
|
|
575
|
-
const preview = bulkhead.estimate(request);
|
|
576
|
-
await bulkhead.run(request, fn, {
|
|
577
|
-
...(preview !== null ? { reservation: preview } : {}),
|
|
578
|
-
});
|
|
579
|
-
```
|
|
580
|
-
|
|
581
|
-
When the override carries a `reserved` field it is validated as a
|
|
582
|
-
consistency check (`reserved === input + maxOutput`), catching hand-built
|
|
583
|
-
overrides whose cached total drifted from edited parts. Plain
|
|
584
|
-
`{ input, maxOutput }` overrides are unchanged.
|
|
585
|
-
|
|
586
|
-
### Adaptive estimation
|
|
587
|
-
|
|
588
|
-
Character-ratio estimation is ±15% at best and drifts with content mix and
|
|
589
|
-
tokenizer changes. `createAdaptiveTokenEstimator()` closes the loop:
|
|
590
|
-
|
|
591
|
-
```ts
|
|
592
|
-
import {
|
|
593
|
-
createAdaptiveTokenEstimator,
|
|
594
|
-
createLLMBulkhead,
|
|
595
|
-
} from "async-bulkhead-llm";
|
|
596
|
-
|
|
597
|
-
const adaptive = createAdaptiveTokenEstimator({
|
|
598
|
-
defaultModel: "claude-sonnet-4-5",
|
|
599
|
-
opaqueBlockTokens: 2_048,
|
|
600
|
-
// smoothing: 0.2, minSamples: 5,
|
|
601
|
-
// minCorrection: 0.5, maxCorrection: 2, maxModels: 64,
|
|
602
|
-
});
|
|
603
|
-
|
|
604
|
-
const bulkhead = createLLMBulkhead({
|
|
605
|
-
model: "claude-sonnet-4-5",
|
|
606
|
-
maxConcurrent: 8,
|
|
607
|
-
tokenBudget: { budget: 200_000, estimator: adaptive.estimator },
|
|
608
|
-
});
|
|
609
|
-
|
|
610
|
-
// Close the loop from actual usage:
|
|
611
|
-
bulkhead.on("release", (e) => {
|
|
612
|
-
if (e.usage) adaptive.observe(e.request, e.usage);
|
|
613
|
-
});
|
|
614
|
-
|
|
615
|
-
adaptive.corrections(); // per-model { samples, factor, applied } for /stats
|
|
616
|
-
```
|
|
617
|
-
|
|
618
|
-
It maintains a per-model EWMA of `actual input / estimated input` and
|
|
619
|
-
multiplies future *input* estimates by that factor — clamped, and only
|
|
620
|
-
after `minSamples` observations. Output reservations are never corrected
|
|
621
|
-
(`max_tokens` is a ceiling, not an estimate). Observations always measure
|
|
622
|
-
against the *uncorrected* base estimate, so the loop cannot compound
|
|
623
|
-
through its own corrections. Calibration is in-memory, per-instance, and
|
|
624
|
-
bounded to `maxModels` tracked models.
|
|
625
|
-
|
|
626
|
-
---
|
|
627
|
-
|
|
628
|
-
## What's New in v3.6 — Gateway coordination seams
|
|
629
|
-
|
|
630
|
-
### Exact reservation preview
|
|
631
|
-
|
|
632
|
-
`estimate()` runs the same estimator and validation path as admission without
|
|
633
|
-
reserving capacity. This is useful when a gateway must acquire an external
|
|
634
|
-
lease before entering the local bulkhead:
|
|
635
|
-
|
|
636
|
-
```ts
|
|
637
|
-
const reservation = bulkhead.estimate(request);
|
|
638
|
-
const lease = reservation
|
|
639
|
-
? await redisLease.reserve(requestId, reservation.reserved)
|
|
640
|
-
: undefined;
|
|
641
|
-
|
|
642
|
-
const result = await bulkhead.acquire(request);
|
|
643
|
-
if (!result.ok) {
|
|
644
|
-
await lease?.release();
|
|
645
|
-
return reject(result.reason);
|
|
646
|
-
}
|
|
647
|
-
```
|
|
648
|
-
|
|
649
|
-
The preview is advisory until admission occurs: do not mutate the request
|
|
650
|
-
between calls, and keep custom estimators deterministic. `null` means token
|
|
651
|
-
budgeting is disabled and the local bulkhead will reserve no tokens.
|
|
652
|
-
|
|
653
|
-
### Stable admission identity
|
|
654
|
-
|
|
655
|
-
Every successful admission receives a UUID available on the acquire result,
|
|
656
|
-
token, run context, and lifecycle events:
|
|
657
|
-
|
|
658
|
-
```ts
|
|
659
|
-
const result = await bulkhead.acquire(request);
|
|
660
|
-
if (result.ok) {
|
|
661
|
-
console.log(result.admissionId);
|
|
662
|
-
console.log(result.token.admissionId);
|
|
663
|
-
result.token.release();
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
await bulkhead.run(request, async (_signal, ctx) => {
|
|
667
|
-
trace.setAttribute('llm.admission_id', ctx!.admissionId);
|
|
668
|
-
return callYourLLMProvider(request);
|
|
669
|
-
});
|
|
670
|
-
```
|
|
671
|
-
|
|
672
|
-
### Ordered usage-change events
|
|
673
|
-
|
|
674
|
-
Effective cumulative `reportUsage()` updates emit a sequence-numbered event.
|
|
675
|
-
Stale or duplicate reports are clamped as before and do not emit:
|
|
676
|
-
|
|
677
|
-
```ts
|
|
678
|
-
bulkhead.on('usage', (event) => {
|
|
679
|
-
// External stores can ignore an update whose sequence is not newer.
|
|
680
|
-
distributedLedger.adjust({
|
|
681
|
-
admissionId: event.admissionId,
|
|
682
|
-
sequence: event.sequence,
|
|
683
|
-
heldTokens: event.heldTokens,
|
|
684
|
-
});
|
|
685
|
-
});
|
|
686
|
-
```
|
|
687
|
-
|
|
688
|
-
The event includes previous/current hold, delta, cumulative usage, priority,
|
|
689
|
-
output-cap state, and over-reservation status. Listeners remain synchronous;
|
|
690
|
-
enqueue network or storage work rather than blocking inside the callback.
|
|
691
|
-
For admission-critical distributed enforcement, use the returned report and
|
|
692
|
-
await the external update in the gateway's stream loop:
|
|
693
|
-
|
|
694
|
-
```ts
|
|
695
|
-
const report = ctx!.reportUsage(cumulativeUsage);
|
|
696
|
-
await distributedLedger.setHold({
|
|
697
|
-
admissionId: report.admissionId,
|
|
698
|
-
sequence: report.sequence,
|
|
699
|
-
heldTokens: report.held,
|
|
700
|
-
});
|
|
701
|
-
```
|
|
702
|
-
|
|
703
|
-
---
|
|
704
|
-
|
|
705
|
-
## What's New in v3.2 — Gateway readiness
|
|
706
|
-
|
|
707
|
-
v3.2 adds the admission-control primitives an AI gateway needs, all additive:
|
|
708
|
-
|
|
709
|
-
### Streaming budget enforcement (`reportUsage`)
|
|
710
|
-
|
|
711
|
-
Report *cumulative* usage as stream events arrive. Input over-estimates are
|
|
712
|
-
refunded to the budget immediately; output overruns expand the hold (blocking
|
|
713
|
-
new admissions until the runaway stream releases). The returned snapshot lets
|
|
714
|
-
a gateway decide to abort a stream:
|
|
715
|
-
|
|
716
|
-
```ts
|
|
717
|
-
await bulkhead.run(request, async (signal, ctx) => {
|
|
718
|
-
for await (const event of providerStream(request, signal)) {
|
|
719
|
-
const snap = ctx!.reportUsage({
|
|
720
|
-
input: event.usage.input_tokens,
|
|
721
|
-
output: event.usage.output_tokens, // cumulative
|
|
722
|
-
});
|
|
723
|
-
if (snap.outputRemaining === 0) {
|
|
724
|
-
// stream has consumed its entire output reservation — abort policy here
|
|
725
|
-
}
|
|
726
|
-
}
|
|
727
|
-
return final;
|
|
728
|
-
});
|
|
729
|
-
```
|
|
730
|
-
|
|
731
|
-
If `release()` is called without usage, the last reported usage drives the
|
|
732
|
-
final refund. Reports are clamped monotonically non-decreasing per field.
|
|
733
|
-
|
|
734
|
-
### Priority admission (`highPriorityReserve`)
|
|
735
|
-
|
|
736
|
-
Reserve budget headroom that only `priority: "high"` requests may use, so
|
|
737
|
-
interactive traffic keeps admitting when batch traffic saturates the pool:
|
|
738
|
-
|
|
739
|
-
```ts
|
|
740
|
-
const bulkhead = createLLMBulkhead({
|
|
741
|
-
model: "claude-sonnet-4",
|
|
742
|
-
maxConcurrent: 50,
|
|
743
|
-
tokenBudget: { budget: 200_000, highPriorityReserve: 40_000 },
|
|
744
|
-
});
|
|
745
|
-
|
|
746
|
-
await bulkhead.run(request, callLLM, { priority: "high" });
|
|
747
|
-
```
|
|
748
|
-
|
|
749
|
-
### Rejection detail
|
|
750
|
-
|
|
751
|
-
Failed acquisitions, `reject` events, and `LLMBulkheadRejectedError` now carry
|
|
752
|
-
a capacity snapshot (`detail`) — slots, queue, and priority-adjusted budget
|
|
753
|
-
numbers — so gateways can emit informative 429/503 responses. No fabricated
|
|
754
|
-
`Retry-After` is provided: a fail-fast bulkhead has no honest ETA.
|
|
755
|
-
|
|
756
|
-
### `wouldAdmit(request, { priority })`
|
|
757
|
-
|
|
758
|
-
Advisory dry-run for routing decisions ("try another model pool"). It reserves
|
|
759
|
-
nothing and is inherently racy — never treat `true` as a guarantee.
|
|
760
|
-
|
|
761
|
-
### Scope note
|
|
762
|
-
|
|
763
|
-
This library remains single-process by design. Distributed budget
|
|
764
|
-
coordination across gateway replicas requires shared state and an async
|
|
765
|
-
admission path; it is out of scope here. For multi-replica deployments,
|
|
766
|
-
partition the budget per replica or coordinate above this layer.
|
|
767
|
-
|
|
768
|
-
---
|
|
769
|
-
|
|
770
|
-
## What's New in v3
|
|
771
|
-
|
|
772
|
-
### Stats are now namespaced
|
|
773
|
-
|
|
774
|
-
`bulkhead.stats()` now separates:
|
|
775
|
-
|
|
776
|
-
- underlying bulkhead stats → stats().bulkhead
|
|
777
|
-
- LLM-layer request stats → stats().llm
|
|
778
|
-
|
|
779
|
-
This avoids conflating base bulkhead slot lifecycle with higher-level LLM request outcomes
|
|
780
|
-
such as 'budget_limit'.
|
|
781
|
-
|
|
782
|
-
---
|
|
783
|
-
|
|
784
|
-
## What's New in v2
|
|
785
|
-
|
|
786
|
-
### Token Refund
|
|
787
|
-
|
|
788
|
-
v1 reserved `input + maxOutput` tokens and held that full reservation until release. Most calls use far fewer output tokens than `max_tokens`. v2 reclaims the difference:
|
|
789
|
-
|
|
790
|
-
```ts
|
|
791
|
-
// Via run() — extract usage from your provider's response
|
|
792
|
-
const result = await bulkhead.run(
|
|
793
|
-
request,
|
|
794
|
-
async () => callLLM(request),
|
|
795
|
-
{
|
|
796
|
-
getUsage: (response) => ({
|
|
797
|
-
input: response.usage.input_tokens,
|
|
798
|
-
output: response.usage.output_tokens,
|
|
799
|
-
}),
|
|
800
|
-
},
|
|
801
|
-
);
|
|
802
|
-
|
|
803
|
-
// Via acquire() — pass usage at release time
|
|
804
|
-
const r = await bulkhead.acquire(request);
|
|
805
|
-
if (r.ok) {
|
|
806
|
-
try {
|
|
807
|
-
const response = await callLLM(request);
|
|
808
|
-
return response;
|
|
809
|
-
} finally {
|
|
810
|
-
r.token.release({
|
|
811
|
-
input: response.usage.input_tokens,
|
|
812
|
-
output: response.usage.output_tokens,
|
|
813
|
-
});
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
```
|
|
817
|
-
|
|
818
|
-
When usage is reported, the refund is `reserved - (actual input + actual output)`. Budget capacity is returned immediately. Without usage, behavior is identical to v1.
|
|
819
|
-
|
|
820
|
-
### Multimodal Content
|
|
821
|
-
|
|
822
|
-
`content` may now be a plain string or an array of content blocks:
|
|
823
|
-
|
|
824
|
-
```ts
|
|
825
|
-
const request = {
|
|
826
|
-
messages: [{
|
|
827
|
-
role: 'user',
|
|
828
|
-
content: [
|
|
829
|
-
{ type: 'text', text: 'Describe this image...' },
|
|
830
|
-
{ type: 'image', source: { type: 'base64', data: '...' } },
|
|
831
|
-
],
|
|
832
|
-
}],
|
|
833
|
-
max_tokens: 1024,
|
|
834
|
-
};
|
|
835
|
-
```
|
|
836
|
-
|
|
837
|
-
Built-in estimators extract text from text blocks and ignore non-text blocks. Token estimates for multimodal requests are a lower bound. Provide a custom `estimator` for accurate multimodal estimation.
|
|
838
|
-
|
|
839
|
-
### Per-Request Model
|
|
840
|
-
|
|
841
|
-
Route multiple models through a single bulkhead with accurate per-model estimation:
|
|
842
|
-
|
|
843
|
-
```ts
|
|
844
|
-
const bulkhead = createLLMBulkhead({
|
|
845
|
-
model: 'claude-sonnet-4', // default for estimation
|
|
846
|
-
maxConcurrent: 20,
|
|
847
|
-
tokenBudget: { budget: 500_000 },
|
|
848
|
-
});
|
|
849
|
-
|
|
850
|
-
// Estimator uses request.model when present
|
|
851
|
-
await bulkhead.run(
|
|
852
|
-
{ model: 'claude-haiku-4-5', messages, max_tokens: 512 },
|
|
853
|
-
async () => callLLM(request),
|
|
854
|
-
);
|
|
855
|
-
```
|
|
856
|
-
|
|
857
|
-
### Custom Dedup Key
|
|
858
|
-
|
|
859
|
-
```ts
|
|
860
|
-
const bulkhead = createLLMBulkhead({
|
|
861
|
-
model: 'claude-sonnet-4',
|
|
862
|
-
maxConcurrent: 10,
|
|
863
|
-
deduplication: {
|
|
864
|
-
keyFn: (request) => {
|
|
865
|
-
// Your own equivalence logic
|
|
866
|
-
return hash(request.messages);
|
|
867
|
-
},
|
|
868
|
-
},
|
|
869
|
-
});
|
|
870
|
-
```
|
|
871
|
-
|
|
872
|
-
The default key covers the entire request object with stable key ordering.
|
|
873
|
-
Return an empty string to opt a specific request out.
|
|
874
|
-
|
|
875
|
-
### Event Hooks
|
|
876
|
-
|
|
877
|
-
```ts
|
|
878
|
-
const off = bulkhead.on('release', ({ reservedTokens, refundedTokens, usage }) => {
|
|
879
|
-
metrics.histogram('llm.tokens.reserved', reservedTokens);
|
|
880
|
-
metrics.histogram('llm.tokens.refunded', refundedTokens);
|
|
881
|
-
});
|
|
882
|
-
|
|
883
|
-
// Later:
|
|
884
|
-
off(); // unsubscribe
|
|
885
|
-
```
|
|
886
|
-
|
|
887
|
-
Events: `'admit'`, `'reject'`, `'usage'`, `'release'`, `'reconfigure'`, `'dedup'`.
|
|
888
|
-
|
|
889
|
-
### Graceful Shutdown
|
|
890
|
-
|
|
891
|
-
```ts
|
|
892
|
-
// In your SIGTERM handler:
|
|
893
|
-
bulkhead.close(); // reject all pending; block future admission
|
|
894
|
-
await bulkhead.drain(); // wait for in-flight work to complete
|
|
895
|
-
```
|
|
896
|
-
|
|
897
|
-
---
|
|
898
|
-
|
|
899
|
-
## Profiles
|
|
900
|
-
|
|
901
|
-
Two built-in presets cover the common cases. Explicit options always override preset defaults.
|
|
902
|
-
|
|
903
|
-
```ts
|
|
904
|
-
// Interactive — fail-fast, no waiting (default)
|
|
905
|
-
const bulkhead = createLLMBulkhead({
|
|
906
|
-
model: 'claude-sonnet-4',
|
|
907
|
-
maxConcurrent: 10,
|
|
908
|
-
profile: 'interactive',
|
|
909
|
-
});
|
|
910
|
-
|
|
911
|
-
// Batch — bounded queue, 30s timeout
|
|
912
|
-
const bulkhead = createLLMBulkhead({
|
|
913
|
-
model: 'claude-sonnet-4',
|
|
914
|
-
maxConcurrent: 4,
|
|
915
|
-
profile: 'batch',
|
|
916
|
-
});
|
|
917
|
-
|
|
918
|
-
// Escape hatch — plain object
|
|
919
|
-
const bulkhead = createLLMBulkhead({
|
|
920
|
-
model: 'claude-sonnet-4',
|
|
921
|
-
maxConcurrent: 4,
|
|
922
|
-
profile: { maxQueue: 5, timeoutMs: 5_000 },
|
|
923
|
-
});
|
|
924
|
-
```
|
|
9
|
+
📖 **[Full documentation →](https://janbalangue.github.io/async-bulkhead-llm/)**
|
|
925
10
|
|
|
926
11
|
---
|
|
927
12
|
|
|
928
|
-
##
|
|
13
|
+
## What it does
|
|
929
14
|
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
15
|
+
You wrap your LLM calls in a bulkhead. Before each call runs, the bulkhead
|
|
16
|
+
decides whether it *should* run — based on how many calls are already in
|
|
17
|
+
flight and how many tokens are already committed. If the answer is no, you get
|
|
18
|
+
a fast, typed rejection instead of a request that piles onto an already
|
|
19
|
+
saturated provider.
|
|
934
20
|
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
model: 'gpt-4o',
|
|
938
|
-
maxConcurrent: 20,
|
|
939
|
-
tokenBudget: { budget: 50_000 },
|
|
940
|
-
admissionClasses: {
|
|
941
|
-
defaultClass: 'standard',
|
|
942
|
-
classes: {
|
|
943
|
-
latencySensitive: {
|
|
944
|
-
protectedConcurrent: 8,
|
|
945
|
-
maxConcurrent: 14,
|
|
946
|
-
protectedInFlightTokens: 20_000,
|
|
947
|
-
maxInFlightTokens: 36_000,
|
|
948
|
-
},
|
|
949
|
-
standard: {
|
|
950
|
-
protectedConcurrent: 3,
|
|
951
|
-
maxConcurrent: 8,
|
|
952
|
-
protectedInFlightTokens: 8_000,
|
|
953
|
-
maxInFlightTokens: 20_000,
|
|
954
|
-
},
|
|
955
|
-
background: {
|
|
956
|
-
maxConcurrent: 4,
|
|
957
|
-
maxInFlightTokens: 10_000,
|
|
958
|
-
},
|
|
959
|
-
},
|
|
960
|
-
},
|
|
961
|
-
});
|
|
21
|
+
That's it. It's one decision, made in-process, in microseconds, before any
|
|
22
|
+
bytes leave your service.
|
|
962
23
|
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
24
|
+
```ts
|
|
25
|
+
await bulkhead.run(request, () => callYourProvider(request));
|
|
26
|
+
// ^ throws LLMBulkheadRejectedError instead of making things worse
|
|
966
27
|
```
|
|
967
28
|
|
|
968
|
-
|
|
969
|
-
owning class. The sum of concurrency floors must not exceed
|
|
970
|
-
`maxConcurrent`; the sum of token floors must not exceed
|
|
971
|
-
`tokenBudget.budget`. A floor may not exceed the same class's hard ceiling.
|
|
972
|
-
Invalid construction or reconfiguration snapshots throw before any limit is
|
|
973
|
-
installed.
|
|
974
|
-
|
|
975
|
-
After all floors are subtracted, the remaining capacity is shared. A class
|
|
976
|
-
uses its protected capacity first, then borrows from the shared remainder.
|
|
977
|
-
Borrowing remains subject to `maxConcurrent`, `maxInFlightTokens`, the global
|
|
978
|
-
limits, and the priority-adjusted token budget. A rejection required to keep
|
|
979
|
-
another class's floor available reports
|
|
980
|
-
`constraint: 'admission_class_protection'`.
|
|
981
|
-
|
|
982
|
-
Floors are deliberately strict: an idle class's protected capacity is not
|
|
983
|
-
automatically lent to another class. A gateway or control plane may implement
|
|
984
|
-
demand-aware lending by atomically applying a newer snapshot with adjusted
|
|
985
|
-
floors. Raising a floor does not cancel work that is already active. Existing
|
|
986
|
-
borrowers drain normally, while new shared-capacity admissions pause until the
|
|
987
|
-
new floor is restored by attrition.
|
|
988
|
-
|
|
989
|
-
Omitting a floor is equivalent to zero. Omitting a hard ceiling means that
|
|
990
|
-
dimension is governed only by the global bulkhead. Zero is valid for either a
|
|
991
|
-
floor or ceiling. Class checks remain fail-fast; `maxQueue` is still one global
|
|
992
|
-
queue and does not create per-class waiter queues.
|
|
993
|
-
|
|
994
|
-
The class table is fixed at construction, which bounds runtime state and metric
|
|
995
|
-
cardinality. Map authenticated tenants or applications to these trusted policy
|
|
996
|
-
buckets instead of using arbitrary identity values as class IDs. Identity
|
|
997
|
-
verification and distributed coordination remain outside this single-process
|
|
998
|
-
library. Admission classes partition deduplication automatically, but use
|
|
999
|
-
`dedupScope` when tenants inside the same class must not share results.
|
|
29
|
+
## Should you use it?
|
|
1000
30
|
|
|
1001
|
-
|
|
31
|
+
**Probably yes if:** you call an LLM provider from a service that takes
|
|
32
|
+
concurrent traffic, and you've either already watched a burst turn into a 429
|
|
33
|
+
storm or a saturation cascade — or you'd rather not.
|
|
1002
34
|
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
- Cumulative admissions whose concurrency came from shared capacity.
|
|
1006
|
-
- Cumulative reservation tokens placed in shared capacity at admission.
|
|
1007
|
-
- Rejection details showing protected, borrowed, and available shared capacity.
|
|
35
|
+
**Probably not if:** you're building a CLI, a notebook, or anything where one
|
|
36
|
+
request happens at a time. There's nothing to protect.
|
|
1008
37
|
|
|
1009
|
-
|
|
38
|
+
**Not a replacement for:** LangChain (orchestration), your provider SDK (the
|
|
39
|
+
actual calls), or a retry library (what happens after a failure). This sits
|
|
40
|
+
underneath all of them and answers a different question. See
|
|
41
|
+
[How it compares](guides/comparison.md).
|
|
1010
42
|
|
|
1011
|
-
##
|
|
43
|
+
## Install
|
|
1012
44
|
|
|
1013
|
-
```
|
|
1014
|
-
|
|
1015
|
-
model: 'claude-sonnet-4',
|
|
1016
|
-
maxConcurrent: 10,
|
|
1017
|
-
tokenBudget: {
|
|
1018
|
-
budget: 200_000,
|
|
1019
|
-
},
|
|
1020
|
-
});
|
|
45
|
+
```bash
|
|
46
|
+
npm install async-bulkhead-llm
|
|
1021
47
|
```
|
|
1022
48
|
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
### How Estimation Works
|
|
1026
|
-
|
|
1027
|
-
The default estimator is `createModelAwareTokenEstimator` seeded with the bulkhead's `model`. It uses per-model character-to-token ratios for known model families, falling back to a flat `4.0` ratio for unknown models.
|
|
1028
|
-
|
|
1029
|
-
v2 checks `request.model` first (when present), then falls back to the bulkhead-level `defaultModel`.
|
|
49
|
+
Node.js 20+. ESM and CommonJS. TypeScript types included. One dependency
|
|
50
|
+
([`async-bulkhead-ts`](https://github.com/janbalangue/async-bulkhead-ts)).
|
|
1030
51
|
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
### Custom Estimator
|
|
52
|
+
## Quick start
|
|
1034
53
|
|
|
1035
54
|
```ts
|
|
1036
|
-
import {
|
|
1037
|
-
|
|
1038
|
-
const enc = new Tiktoken(/* your model encoding */);
|
|
55
|
+
import { createLLMBulkhead, LLMBulkheadRejectedError } from 'async-bulkhead-llm';
|
|
1039
56
|
|
|
1040
57
|
const bulkhead = createLLMBulkhead({
|
|
1041
58
|
model: 'claude-sonnet-4',
|
|
1042
59
|
maxConcurrent: 10,
|
|
1043
|
-
tokenBudget: {
|
|
1044
|
-
budget: 200_000,
|
|
1045
|
-
estimator: (request) => ({
|
|
1046
|
-
input: enc.encode(request.messages.map(m =>
|
|
1047
|
-
typeof m.content === 'string'
|
|
1048
|
-
? m.content
|
|
1049
|
-
: m.content.filter(b => b.type === 'text').map(b => b.text).join('')
|
|
1050
|
-
).join('')).length,
|
|
1051
|
-
maxOutput: request.max_tokens ?? 2_048,
|
|
1052
|
-
}),
|
|
1053
|
-
},
|
|
1054
|
-
});
|
|
1055
|
-
```
|
|
1056
|
-
|
|
1057
|
-
### Estimator Utilities
|
|
1058
|
-
|
|
1059
|
-
```ts
|
|
1060
|
-
import {
|
|
1061
|
-
naiveTokenEstimator,
|
|
1062
|
-
createModelAwareTokenEstimator,
|
|
1063
|
-
createAdaptiveTokenEstimator,
|
|
1064
|
-
extractTextLength,
|
|
1065
|
-
} from 'async-bulkhead-llm';
|
|
1066
|
-
|
|
1067
|
-
// Flat 4.0 ratio, multimodal-safe
|
|
1068
|
-
const est1 = naiveTokenEstimator(request);
|
|
1069
|
-
|
|
1070
|
-
// Per-model ratios
|
|
1071
|
-
const estimate = createModelAwareTokenEstimator(
|
|
1072
|
-
{ 'my-azure-deployment': 3.7 },
|
|
1073
|
-
{
|
|
1074
|
-
defaultModel: 'claude-sonnet-4',
|
|
1075
|
-
outputCap: 2_048,
|
|
1076
|
-
onUnknownModel: (model) => console.warn(`Unknown model: ${model}`),
|
|
1077
|
-
},
|
|
1078
|
-
);
|
|
1079
|
-
|
|
1080
|
-
// Utility for multimodal content
|
|
1081
|
-
const charCount = extractTextLength(message.content);
|
|
1082
|
-
|
|
1083
|
-
// Self-calibrating wrapper (v3.8) — see "What's New in v3.8"
|
|
1084
|
-
const adaptive = createAdaptiveTokenEstimator({ defaultModel: 'gpt-4o' });
|
|
1085
|
-
adaptive.estimator; // pass as tokenBudget.estimator
|
|
1086
|
-
adaptive.observe(request, usage); // feed actual usage (release event)
|
|
1087
|
-
adaptive.corrections(); // per-model calibration snapshot
|
|
1088
|
-
adaptive.reset(); // clear calibration
|
|
1089
|
-
```
|
|
1090
|
-
|
|
1091
|
-
### Atomic Runtime Reconfiguration
|
|
1092
|
-
|
|
1093
|
-
`applyLimits(snapshot)` is the preferred runtime control surface for gateways
|
|
1094
|
-
and distributed control-plane agents. The snapshot is complete rather than
|
|
1095
|
-
partial, so concurrency, queue, budget, and reserve values cannot drift across
|
|
1096
|
-
separate setter calls.
|
|
1097
|
-
|
|
1098
|
-
```ts
|
|
1099
|
-
const bulkhead = createLLMBulkhead({
|
|
1100
|
-
model: 'claude-sonnet-4',
|
|
1101
|
-
maxConcurrent: 10,
|
|
1102
|
-
maxQueue: 0,
|
|
1103
|
-
initialRevision: 100,
|
|
1104
|
-
tokenBudget: {
|
|
1105
|
-
budget: 200_000,
|
|
1106
|
-
highPriorityReserve: 25_000,
|
|
1107
|
-
},
|
|
1108
|
-
admissionClasses: {
|
|
1109
|
-
defaultClass: 'standard',
|
|
1110
|
-
classes: {
|
|
1111
|
-
premium: { maxConcurrent: 7, maxInFlightTokens: 140_000 },
|
|
1112
|
-
standard: { maxConcurrent: 3, maxInFlightTokens: 60_000 },
|
|
1113
|
-
},
|
|
1114
|
-
},
|
|
1115
|
-
});
|
|
1116
|
-
|
|
1117
|
-
const update = bulkhead.applyLimits({
|
|
1118
|
-
revision: 101,
|
|
1119
|
-
maxConcurrent: 6,
|
|
1120
|
-
maxQueue: 20,
|
|
1121
|
-
tokenBudget: {
|
|
1122
|
-
budget: 90_000,
|
|
1123
|
-
highPriorityReserve: 15_000,
|
|
1124
|
-
},
|
|
1125
60
|
});
|
|
1126
|
-
```
|
|
1127
|
-
|
|
1128
|
-
Semantics:
|
|
1129
61
|
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
* **Shrink by attrition.** In-flight work and accepted queue waiters are never
|
|
1135
|
-
revoked. New admissions obey the lower ceilings immediately.
|
|
1136
|
-
* **Immediate expansion.** Raising `maxConcurrent` pumps accepted waiters in
|
|
1137
|
-
the same synchronous update, after the complete LLM-layer snapshot is active.
|
|
1138
|
-
* **Zero-concurrency kill switch.** `maxConcurrent: 0` rejects new callers with
|
|
1139
|
-
`"concurrency_limit"` instead of queueing them.
|
|
1140
|
-
* **Budget reserve may exceed a shrunken budget.** The normal-priority ceiling
|
|
1141
|
-
is clamped to 0 while high-priority traffic is checked against the full
|
|
1142
|
-
budget, preserving the existing degraded-priority behavior.
|
|
1143
|
-
* **Feature shapes are fixed at construction.** A bulkhead created with
|
|
1144
|
-
`tokenBudget` requires `tokenBudget` in every update. A bulkhead created
|
|
1145
|
-
without it must omit that field; estimator policy is not hot-swapped. The
|
|
1146
|
-
same rule applies to `admissionClasses`, whose complete fixed key set must be
|
|
1147
|
-
present in every update.
|
|
1148
|
-
* **Admission provenance is immutable.** `acquire()` results, tokens,
|
|
1149
|
-
`LLMRunContext`, usage reports, and lifecycle events retain the revision
|
|
1150
|
-
captured when the slot and token reservation were successfully acquired.
|
|
1151
|
-
A later `applyLimits()` call cannot relabel already admitted work.
|
|
1152
|
-
|
|
1153
|
-
```ts
|
|
1154
|
-
const current = bulkhead.limits();
|
|
1155
|
-
// { revision, maxConcurrent, maxQueue, tokenBudget?, admissionClasses? }
|
|
62
|
+
const request = {
|
|
63
|
+
messages: [{ role: 'user', content: 'Summarise this document...' }],
|
|
64
|
+
max_tokens: 1024,
|
|
65
|
+
};
|
|
1156
66
|
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
67
|
+
try {
|
|
68
|
+
const result = await bulkhead.run(request, async () => {
|
|
69
|
+
return callYourLLMProvider(request);
|
|
70
|
+
});
|
|
71
|
+
} catch (err) {
|
|
72
|
+
if (err instanceof LLMBulkheadRejectedError) {
|
|
73
|
+
// Shed on purpose. err.reason tells you which limit was hit.
|
|
74
|
+
return respond503(err.reason);
|
|
75
|
+
}
|
|
76
|
+
throw err;
|
|
77
|
+
}
|
|
1160
78
|
```
|
|
1161
79
|
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
complete budget-only update at `currentRevision + 1`. Do not mix it with an
|
|
1166
|
-
external revision authority; distributed integrations should use
|
|
1167
|
-
`applyLimits()` exclusively.
|
|
80
|
+
Ten calls run at once. The eleventh is rejected immediately with
|
|
81
|
+
`reason: 'concurrency_limit'` — it does not wait, and it does not reach your
|
|
82
|
+
provider. That is the whole idea: **fail fast beats fail slow.**
|
|
1168
83
|
|
|
84
|
+
If you'd rather queue than shed, add `maxQueue: 20`. If you want queued
|
|
85
|
+
callers to give up after a while, add `timeoutMs: 5_000`. Both are off by
|
|
86
|
+
default, deliberately.
|
|
1169
87
|
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
## Deduplication
|
|
88
|
+
## Limit tokens, not just requests
|
|
1173
89
|
|
|
90
|
+
`maxConcurrent` counts requests. It cannot tell a 500-token request from a
|
|
91
|
+
100,000-token one — ten of each look identical to it. `tokenBudget` adds the
|
|
92
|
+
second dimension:
|
|
1174
93
|
|
|
1175
94
|
```ts
|
|
1176
95
|
const bulkhead = createLLMBulkhead({
|
|
1177
96
|
model: 'claude-sonnet-4',
|
|
1178
97
|
maxConcurrent: 10,
|
|
1179
|
-
|
|
98
|
+
tokenBudget: { budget: 200_000 },
|
|
1180
99
|
});
|
|
1181
|
-
|
|
1182
|
-
const [r1, r2] = await Promise.all([
|
|
1183
|
-
bulkhead.run(request, async () => callLLM(request)),
|
|
1184
|
-
bulkhead.run(request, async () => callLLM(request)), // deduped
|
|
1185
|
-
]);
|
|
1186
|
-
```
|
|
1187
|
-
|
|
1188
|
-
Deduplication applies to `run()` only — `acquire()` never deduplicates.
|
|
1189
|
-
|
|
1190
|
-
**Default key (v3.4):** a key-order-stable serialization of the **entire
|
|
1191
|
-
request object**, SHA-256 hashed before storage (the in-flight map never
|
|
1192
|
-
retains prompt text). Any own enumerable property difference —
|
|
1193
|
-
`temperature`, `tools`, `system`, not just `messages` / `max_tokens` /
|
|
1194
|
-
`model` — prevents conflation. The tradeoff: volatile per-request fields
|
|
1195
|
-
(request IDs, timestamps) also defeat deduplication; supply a `keyFn`
|
|
1196
|
-
that omits them if your requests carry such fields.
|
|
1197
|
-
|
|
1198
|
-
Custom key:
|
|
1199
|
-
|
|
1200
|
-
```ts
|
|
1201
|
-
deduplication: {
|
|
1202
|
-
keyFn: (request) => myStableKey(request.messages),
|
|
1203
|
-
}
|
|
1204
|
-
```
|
|
1205
|
-
|
|
1206
|
-
Return `""` from `keyFn` to opt a specific request out.
|
|
1207
|
-
|
|
1208
|
-
**Multi-tenant callers:** the default key has no tenant dimension — two
|
|
1209
|
-
tenants sending byte-identical requests would share one response. Pass a
|
|
1210
|
-
per-call `dedupScope` to isolate them; requests deduplicate only within
|
|
1211
|
-
the same scope:
|
|
1212
|
-
|
|
1213
|
-
```ts
|
|
1214
|
-
bulkhead.run(request, callLLM, { dedupScope: apiKeyId });
|
|
1215
|
-
```
|
|
1216
|
-
|
|
1217
|
-
When a request joins an existing in-flight call through deduplication, the
|
|
1218
|
-
underlying LLM call is shared and is not cancelled by later callers. Each
|
|
1219
|
-
deduped caller still gets its own `AbortSignal`, and an *explicitly
|
|
1220
|
-
passed* per-call `timeoutMs` caps its wait on the shared call: aborting
|
|
1221
|
-
or timing out that caller rejects only that caller's `run()` promise while
|
|
1222
|
-
the shared work continues for the original caller and any other waiters.
|
|
1223
|
-
The bulkhead-level `timeoutMs` default does **not** apply to this wait —
|
|
1224
|
-
it is a queue-wait timeout, and a follower is waiting on a call that is
|
|
1225
|
-
already running, not queued.
|
|
1226
|
-
|
|
1227
|
-
### Streaming results (v3.5)
|
|
1228
|
-
|
|
1229
|
-
Dedup shares the leader's resolved value with every follower **by
|
|
1230
|
-
reference**. For plain JSON results that is correct. For streaming
|
|
1231
|
-
results it is not: a `ReadableStream`, Node `Readable`, async iterable,
|
|
1232
|
-
or `Response` body can only be consumed once — whichever caller reads
|
|
1233
|
-
first wins, and the rest get a locked or drained stream.
|
|
1234
|
-
|
|
1235
|
-
The bulkhead now refuses to do that silently. When a follower's shared
|
|
1236
|
-
result is detected as single-consumer, that follower rejects with
|
|
1237
|
-
`LLMBulkheadRejectedError("unshareable_result")`. The **leader always
|
|
1238
|
-
receives its original result unaffected**. Detection is shallow — only
|
|
1239
|
-
the result value itself is inspected, so a stream nested inside a
|
|
1240
|
-
wrapper object is still shared by reference.
|
|
1241
|
-
|
|
1242
|
-
You have two ways to make streaming and dedup coexist:
|
|
1243
|
-
|
|
1244
|
-
**1. `shareResult` — make sharing work.** A fan-out hook called once per
|
|
1245
|
-
follower with the leader's result; its return value is what that
|
|
1246
|
-
follower receives. It runs for *every* follower delivery (safe results
|
|
1247
|
-
included) and bypasses the single-consumer detection — the hook owns
|
|
1248
|
-
fan-out policy. A throwing hook rejects that follower with the thrown
|
|
1249
|
-
error; leader and other followers are unaffected.
|
|
1250
|
-
|
|
1251
|
-
```ts
|
|
1252
|
-
// fetch Response: each follower gets an independent clone.
|
|
1253
|
-
// clone() is called at resolution time, before any body is consumed.
|
|
1254
|
-
deduplication: {
|
|
1255
|
-
shareResult: (r) => (r as Response).clone(),
|
|
1256
|
-
}
|
|
1257
100
|
```
|
|
1258
101
|
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
**2. `dedup: false` — skip dedup for streaming calls.** A per-call
|
|
1263
|
-
opt-out on `run()` options: the call neither joins an existing in-flight
|
|
1264
|
-
call nor registers as joinable. Use it on streaming routes of a bulkhead
|
|
1265
|
-
where dedup is otherwise useful, instead of encoding the exemption in a
|
|
1266
|
-
bulkhead-wide `keyFn`. (`dedup: true` cannot enable deduplication when
|
|
1267
|
-
it is disabled at the bulkhead level.)
|
|
1268
|
-
|
|
1269
|
-
```ts
|
|
1270
|
-
bulkhead.run(request, streamFromProvider, { dedup: false });
|
|
1271
|
-
```
|
|
102
|
+
Each request now also reserves `estimated input + max_tokens` before it runs.
|
|
103
|
+
When the budget is committed, further requests are rejected with
|
|
104
|
+
`budget_limit`.
|
|
1272
105
|
|
|
1273
|
-
|
|
106
|
+
**This is an in-flight ceiling, not a spend cap.** The budget limits how many
|
|
107
|
+
tokens may be reserved *at the same time*; every reservation is returned when
|
|
108
|
+
its request completes. A 200,000-token budget does not mean you will spend
|
|
109
|
+
200,000 tokens — it means no more than that much work is ever committed at
|
|
110
|
+
once. It is a load-shedding control, not a billing control.
|
|
1274
111
|
|
|
1275
|
-
|
|
112
|
+
Reservations are estimates, so give the budget back when you know the truth:
|
|
1276
113
|
|
|
1277
114
|
```ts
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
);
|
|
1285
|
-
|
|
1286
|
-
ac.abort();
|
|
115
|
+
await bulkhead.run(request, () => callLLM(request), {
|
|
116
|
+
getUsage: (response) => ({
|
|
117
|
+
input: response.usage.input_tokens,
|
|
118
|
+
output: response.usage.output_tokens,
|
|
119
|
+
}),
|
|
120
|
+
});
|
|
1287
121
|
```
|
|
1288
122
|
|
|
1289
|
-
|
|
123
|
+
The unused portion returns to the in-flight budget immediately. Most calls use
|
|
124
|
+
far fewer output tokens than `max_tokens`, so this frees real admission
|
|
125
|
+
capacity.
|
|
1290
126
|
|
|
1291
|
-
|
|
1292
|
-
await bulkhead.run(request, async () => callLLM(request), { timeoutMs: 5_000 });
|
|
1293
|
-
```
|
|
127
|
+
→ [Token budget and estimation](guides/token-budget.md)
|
|
1294
128
|
|
|
1295
|
-
|
|
129
|
+
## Handling rejections
|
|
1296
130
|
|
|
1297
|
-
|
|
131
|
+
Every rejection is typed and carries a capacity snapshot, so you can return
|
|
132
|
+
something useful instead of a generic 500:
|
|
1298
133
|
|
|
1299
134
|
```ts
|
|
1300
135
|
const r = await bulkhead.acquire(request);
|
|
@@ -1302,552 +137,89 @@ const r = await bulkhead.acquire(request);
|
|
|
1302
137
|
if (!r.ok) {
|
|
1303
138
|
// r.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit'
|
|
1304
139
|
// | 'timeout' | 'aborted' | 'shutdown'
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
console.log(`Admission: ${r.admissionId}`);
|
|
1309
|
-
|
|
1310
|
-
try {
|
|
1311
|
-
const response = await callLLM(request);
|
|
1312
|
-
return response;
|
|
1313
|
-
} finally {
|
|
1314
|
-
// v2: pass usage for refund
|
|
1315
|
-
r.token.release({
|
|
1316
|
-
input: response.usage.input_tokens,
|
|
1317
|
-
output: response.usage.output_tokens,
|
|
1318
|
-
});
|
|
1319
|
-
}
|
|
1320
|
-
```
|
|
1321
|
-
|
|
1322
|
-
---
|
|
1323
|
-
|
|
1324
|
-
## Handling Rejections
|
|
1325
|
-
|
|
1326
|
-
```ts
|
|
1327
|
-
import { LLMBulkheadRejectedError } from 'async-bulkhead-llm';
|
|
1328
|
-
|
|
1329
|
-
try {
|
|
1330
|
-
await bulkhead.run(request, async () => callLLM(request));
|
|
1331
|
-
} catch (err) {
|
|
1332
|
-
if (err instanceof LLMBulkheadRejectedError) {
|
|
1333
|
-
// err.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit'
|
|
1334
|
-
// | 'timeout' | 'aborted' | 'shutdown'
|
|
1335
|
-
return respond503(`Shed: ${err.reason}`);
|
|
1336
|
-
}
|
|
1337
|
-
throw err;
|
|
140
|
+
// r.detail: slots, queue depth, priority-adjusted budget numbers
|
|
141
|
+
return respond429(r.reason, r.detail);
|
|
1338
142
|
}
|
|
1339
143
|
```
|
|
1340
144
|
|
|
1341
|
-
|
|
145
|
+
No `Retry-After` is fabricated — a fail-fast bulkhead has no honest ETA. If
|
|
146
|
+
you need one, your gateway knows more than the bulkhead does.
|
|
1342
147
|
|
|
1343
|
-
##
|
|
148
|
+
## Watching it work
|
|
1344
149
|
|
|
1345
150
|
```ts
|
|
1346
151
|
const s = bulkhead.stats();
|
|
152
|
+
s.bulkhead.inFlight; // slots in use
|
|
153
|
+
s.llm.rejectedByReason; // why you're shedding
|
|
154
|
+
s.tokenBudget?.available; // budget headroom
|
|
1347
155
|
|
|
1348
|
-
|
|
1349
|
-
s.limits.maxConcurrent
|
|
1350
|
-
s.limits.maxQueue
|
|
1351
|
-
s.limits.tokenBudget?.budget
|
|
1352
|
-
s.limits.tokenBudget?.highPriorityReserve
|
|
1353
|
-
s.limits.admissionClasses?.premium?.maxConcurrent
|
|
1354
|
-
|
|
1355
|
-
s.bulkhead.inFlight
|
|
1356
|
-
s.bulkhead.pending
|
|
1357
|
-
s.bulkhead.maxConcurrent
|
|
1358
|
-
s.bulkhead.maxQueue
|
|
1359
|
-
s.bulkhead.closed // true after close()
|
|
1360
|
-
|
|
1361
|
-
s.llm.admitted
|
|
1362
|
-
s.llm.released
|
|
1363
|
-
s.llm.rejected
|
|
1364
|
-
s.llm.rejectedByReason?.budget_limit
|
|
1365
|
-
|
|
1366
|
-
s.observe?.bypassed // v3.9: callbacks run without capacity
|
|
1367
|
-
s.observe?.raceBypassed // advisory admit raced with rejection
|
|
1368
|
-
s.observe?.bypassedByReason
|
|
1369
|
-
s.observe?.usageReported
|
|
1370
|
-
s.observe?.totalInputTokens
|
|
1371
|
-
s.observe?.totalOutputTokens
|
|
1372
|
-
|
|
1373
|
-
s.tokenBudget?.budget
|
|
1374
|
-
s.tokenBudget?.inFlightTokens
|
|
1375
|
-
s.tokenBudget?.available
|
|
1376
|
-
s.tokenBudget?.totalReserved // v3.1: cumulative tokens reserved at admission
|
|
1377
|
-
s.tokenBudget?.totalConsumed // v3.1: cumulative actual tokens consumed (usage required)
|
|
1378
|
-
s.tokenBudget?.totalRefunded // v2: cumulative refunded tokens
|
|
1379
|
-
|
|
1380
|
-
s.admissionClasses?.defaultClass
|
|
1381
|
-
s.admissionClasses?.classes.premium?.inFlight
|
|
1382
|
-
s.admissionClasses?.classes.premium?.inFlightTokens
|
|
1383
|
-
s.admissionClasses?.classes.premium?.rejectedByReason
|
|
1384
|
-
|
|
1385
|
-
s.deduplication?.active
|
|
1386
|
-
s.deduplication?.hits
|
|
1387
|
-
```
|
|
1388
|
-
|
|
1389
|
-
```ts
|
|
1390
|
-
type LLMStats = {
|
|
1391
|
-
limits: LLMAdmissionLimits;
|
|
1392
|
-
bulkhead: Stats;
|
|
1393
|
-
llm: {
|
|
1394
|
-
admitted: number;
|
|
1395
|
-
released: number;
|
|
1396
|
-
rejected: number;
|
|
1397
|
-
rejectedByReason: Partial<Record<LLMRejectReason, number>>;
|
|
1398
|
-
};
|
|
1399
|
-
tokenBudget?: {
|
|
1400
|
-
budget: number;
|
|
1401
|
-
inFlightTokens: number;
|
|
1402
|
-
available: number;
|
|
1403
|
-
totalReserved: number;
|
|
1404
|
-
totalConsumed: number;
|
|
1405
|
-
totalRefunded: number;
|
|
1406
|
-
};
|
|
1407
|
-
observe?: {
|
|
1408
|
-
bypassed: number;
|
|
1409
|
-
raceBypassed: number;
|
|
1410
|
-
bypassedByReason: Partial<Record<
|
|
1411
|
-
'budget_limit' | 'concurrency_limit' | 'queue_limit' | 'timeout',
|
|
1412
|
-
number
|
|
1413
|
-
>>;
|
|
1414
|
-
usageReported: number;
|
|
1415
|
-
totalInputTokens: number;
|
|
1416
|
-
totalOutputTokens: number;
|
|
1417
|
-
};
|
|
1418
|
-
admissionClasses?: {
|
|
1419
|
-
defaultClass: string;
|
|
1420
|
-
shared: {
|
|
1421
|
-
maxConcurrent: number;
|
|
1422
|
-
inFlight: number;
|
|
1423
|
-
availableConcurrent: number;
|
|
1424
|
-
tokenBudget?: {
|
|
1425
|
-
budget: number;
|
|
1426
|
-
inFlightTokens: number;
|
|
1427
|
-
available: number;
|
|
1428
|
-
};
|
|
1429
|
-
};
|
|
1430
|
-
classes: Record<string, LLMAdmissionClassStats>;
|
|
1431
|
-
};
|
|
1432
|
-
deduplication?: {
|
|
1433
|
-
active: number;
|
|
1434
|
-
hits: number;
|
|
1435
|
-
};
|
|
1436
|
-
};
|
|
1437
|
-
```
|
|
1438
|
-
|
|
1439
|
-
---
|
|
1440
|
-
|
|
1441
|
-
## Event Hooks
|
|
1442
|
-
|
|
1443
|
-
```ts
|
|
1444
|
-
// Subscribe
|
|
1445
|
-
const off = bulkhead.on('admit', ({ admissionId, reservedTokens }) => {
|
|
1446
|
-
console.log(`${admissionId}: ${reservedTokens} tokens reserved`);
|
|
1447
|
-
});
|
|
1448
|
-
|
|
1449
|
-
// Unsubscribe
|
|
1450
|
-
off();
|
|
1451
|
-
```
|
|
1452
|
-
|
|
1453
|
-
| Event | Payload |
|
|
1454
|
-
|-----------|---------|
|
|
1455
|
-
| `admit` | `{ request, admissionId, limitRevision, priority, admissionClass?, reservedTokens }` |
|
|
1456
|
-
| `reject` | `{ request, reason, limitRevision, admissionClass?, detail? }` |
|
|
1457
|
-
| `usage` | `{ request, admissionId, limitRevision, priority, admissionClass?, sequence, reservedTokens, previousHeldTokens, heldTokens, deltaTokens, usage, outputCap, outputRemaining, overReservation }` |
|
|
1458
|
-
| `release` | `{ request, admissionId, limitRevision, priority, admissionClass?, reservedTokens, heldTokens, refundedTokens, usageSequence, usage? }` |
|
|
1459
|
-
| `bypass` | `{ request, admissionId, limitRevision, priority, admissionClass?, reason, detail?, reservation, raced }` |
|
|
1460
|
-
| `bypassUsage` | `{ request, admissionId, limitRevision, priority, admissionClass?, reason, sequence, reservation, usage, outputCap, outputRemaining, overReservation }` |
|
|
1461
|
-
| `bypassRelease` | `{ request, admissionId, limitRevision, priority, admissionClass?, reason, reservation, usageSequence, usage? }` |
|
|
1462
|
-
| `reconfigure` | `{ previous, current }` |
|
|
1463
|
-
| `dedup` | `{ request }` |
|
|
1464
|
-
|
|
1465
|
-
Listeners are synchronous and fire-and-forget. Exceptions are silently caught.
|
|
1466
|
-
Do not perform blocking network I/O in a listener; enqueue telemetry or lease
|
|
1467
|
-
updates for asynchronous delivery.
|
|
1468
|
-
|
|
1469
|
-
---
|
|
1470
|
-
|
|
1471
|
-
## Graceful Shutdown
|
|
1472
|
-
|
|
1473
|
-
```ts
|
|
1474
|
-
bulkhead.close(); // stop admission, reject pending waiters
|
|
1475
|
-
await bulkhead.drain(); // wait for in-flight work to finish
|
|
1476
|
-
```
|
|
1477
|
-
|
|
1478
|
-
`close()` is synchronous, idempotent, and irreversible. `drain()` resolves when `inFlight` and `pending` both reach zero.
|
|
1479
|
-
|
|
1480
|
-
---
|
|
1481
|
-
|
|
1482
|
-
## API Reference
|
|
1483
|
-
|
|
1484
|
-
### `createLLMBulkhead(options)`
|
|
1485
|
-
|
|
1486
|
-
```ts
|
|
1487
|
-
type LLMBulkheadOptions = {
|
|
1488
|
-
model: string;
|
|
1489
|
-
maxConcurrent: number;
|
|
1490
|
-
initialRevision?: number; // non-negative safe integer; default 0
|
|
1491
|
-
maxQueue?: number;
|
|
1492
|
-
timeoutMs?: number; // integer >= 0
|
|
1493
|
-
profile?: 'interactive' | 'batch' | LLMBulkheadPreset;
|
|
1494
|
-
tokenBudget?: {
|
|
1495
|
-
budget: number; // non-negative integer; 0 rejects all budget-gated admissions
|
|
1496
|
-
estimator?: TokenEstimator;
|
|
1497
|
-
outputCap?: number; // integer >= 0
|
|
1498
|
-
highPriorityReserve?: number; // integer >= 0 and <= initial budget
|
|
1499
|
-
};
|
|
1500
|
-
admissionClasses?: {
|
|
1501
|
-
defaultClass: string;
|
|
1502
|
-
classes: Record<string, {
|
|
1503
|
-
protectedConcurrent?: number;
|
|
1504
|
-
maxConcurrent?: number;
|
|
1505
|
-
protectedInFlightTokens?: number; // requires tokenBudget
|
|
1506
|
-
maxInFlightTokens?: number; // requires tokenBudget
|
|
1507
|
-
}>;
|
|
1508
|
-
};
|
|
1509
|
-
deduplication?: boolean | DeduplicationOptions;
|
|
1510
|
-
};
|
|
1511
|
-
|
|
1512
|
-
type DeduplicationOptions = {
|
|
1513
|
-
keyFn?: (request: LLMRequest) => string;
|
|
1514
|
-
shareResult?: (result: unknown) => unknown; // per-follower fan-out (v3.5)
|
|
1515
|
-
};
|
|
1516
|
-
```
|
|
1517
|
-
|
|
1518
|
-
### `bulkhead.run(request, fn, options?)`
|
|
1519
|
-
|
|
1520
|
-
```ts
|
|
1521
|
-
run<T>(
|
|
1522
|
-
request: LLMRequest,
|
|
1523
|
-
fn: (signal?: AbortSignal, ctx?: LLMRunContext) => Promise<T>,
|
|
1524
|
-
options?: {
|
|
1525
|
-
signal?: AbortSignal;
|
|
1526
|
-
timeoutMs?: number; // integer >= 0
|
|
1527
|
-
priority?: 'normal' | 'high';
|
|
1528
|
-
admissionClass?: string; // fixed configured policy-class ID
|
|
1529
|
-
getUsage?: (result: T) => TokenUsage | undefined;
|
|
1530
|
-
mode?: 'enforce' | 'observe'; // default: 'enforce' (v3.9)
|
|
1531
|
-
shadowReasons?: readonly (
|
|
1532
|
-
| 'budget_limit'
|
|
1533
|
-
| 'concurrency_limit'
|
|
1534
|
-
| 'queue_limit'
|
|
1535
|
-
| 'timeout'
|
|
1536
|
-
)[];
|
|
1537
|
-
dedupScope?: string; // dedup isolation scope (e.g. tenant / API key)
|
|
1538
|
-
dedup?: boolean; // false = opt this call out of dedup (v3.5)
|
|
1539
|
-
},
|
|
1540
|
-
): Promise<T>
|
|
1541
|
-
```
|
|
1542
|
-
|
|
1543
|
-
`ctx.admissionId` is the stable execution identifier and
|
|
1544
|
-
`ctx.limitRevision` is the immutable revision associated with the admission
|
|
1545
|
-
or bypass decision, and `ctx.admissionClass` identifies the selected bounded
|
|
1546
|
-
policy class when configured. In observe-mode
|
|
1547
|
-
bypasses it uses a `shadow-` prefix. `ctx.reservation` is the exact evaluated
|
|
1548
|
-
reservation (or `null` when token budgeting is disabled),
|
|
1549
|
-
`ctx.admission` distinguishes `"admitted"` from `"bypassed"`, and
|
|
1550
|
-
`ctx.bypassReason` / `ctx.bypassDetail` describe a bypass.
|
|
1551
|
-
`ctx.reportUsage()` reports cumulative streaming usage; bypassed usage is
|
|
1552
|
-
recorded for telemetry but never changes bulkhead capacity accounting.
|
|
1553
|
-
|
|
1554
|
-
### `bulkhead.estimate(request)`
|
|
1555
|
-
|
|
1556
|
-
```ts
|
|
1557
|
-
estimate(request: LLMRequest): LLMReservationEstimate | null
|
|
1558
|
-
|
|
1559
|
-
type LLMReservationEstimate = {
|
|
1560
|
-
readonly input: number;
|
|
1561
|
-
readonly maxOutput: number;
|
|
1562
|
-
readonly reserved: number;
|
|
1563
|
-
};
|
|
1564
|
-
```
|
|
1565
|
-
|
|
1566
|
-
Runs the same estimator and validation path as admission but does not reserve
|
|
1567
|
-
capacity. Returns `null` when `tokenBudget` is not configured.
|
|
1568
|
-
|
|
1569
|
-
### `bulkhead.acquire(request, options?)`
|
|
1570
|
-
|
|
1571
|
-
```ts
|
|
1572
|
-
acquire(
|
|
1573
|
-
request: LLMRequest,
|
|
1574
|
-
options?: {
|
|
1575
|
-
signal?: AbortSignal;
|
|
1576
|
-
timeoutMs?: number; // integer >= 0
|
|
1577
|
-
priority?: 'normal' | 'high';
|
|
1578
|
-
admissionClass?: string;
|
|
1579
|
-
},
|
|
1580
|
-
): Promise<LLMAcquireResult>
|
|
1581
|
-
|
|
1582
|
-
type LLMAcquireResult =
|
|
1583
|
-
| {
|
|
1584
|
-
ok: true;
|
|
1585
|
-
admissionId: string;
|
|
1586
|
-
limitRevision: number;
|
|
1587
|
-
admissionClass?: string;
|
|
1588
|
-
reservation: LLMReservationEstimate | null;
|
|
1589
|
-
token: LLMToken;
|
|
1590
|
-
}
|
|
1591
|
-
| { ok: false; reason: LLMRejectReason; detail?: LLMRejectDetail };
|
|
1592
|
-
|
|
1593
|
-
type LLMToken = {
|
|
1594
|
-
readonly admissionId: string;
|
|
1595
|
-
readonly limitRevision: number;
|
|
1596
|
-
readonly admissionClass?: string;
|
|
1597
|
-
readonly reservation: LLMReservationEstimate | null;
|
|
1598
|
-
reportUsage(
|
|
1599
|
-
usage: TokenUsage,
|
|
1600
|
-
reconciliation?: {
|
|
1601
|
-
remainingOutputTokens: number;
|
|
1602
|
-
safetyMarginTokens?: number;
|
|
1603
|
-
},
|
|
1604
|
-
): UsageReport;
|
|
1605
|
-
release(usage?: TokenUsage): void;
|
|
1606
|
-
};
|
|
1607
|
-
```
|
|
1608
|
-
|
|
1609
|
-
### `bulkhead.stats()`
|
|
1610
|
-
|
|
1611
|
-
### `bulkhead.limits()`
|
|
1612
|
-
|
|
1613
|
-
```ts
|
|
1614
|
-
limits(): LLMAdmissionLimits
|
|
1615
|
-
```
|
|
1616
|
-
|
|
1617
|
-
Returns a frozen copy of the currently applied complete snapshot.
|
|
1618
|
-
|
|
1619
|
-
### `bulkhead.applyLimits(snapshot)`
|
|
1620
|
-
|
|
1621
|
-
```ts
|
|
1622
|
-
applyLimits(snapshot: LLMAdmissionLimits): LLMApplyLimitsResult
|
|
1623
|
-
|
|
1624
|
-
type LLMAdmissionLimits = {
|
|
1625
|
-
readonly revision: number;
|
|
1626
|
-
readonly maxConcurrent: number; // runtime 0 = fail-fast kill switch
|
|
1627
|
-
readonly maxQueue: number;
|
|
1628
|
-
readonly tokenBudget?: {
|
|
1629
|
-
readonly budget: number;
|
|
1630
|
-
readonly highPriorityReserve: number;
|
|
1631
|
-
};
|
|
1632
|
-
readonly admissionClasses?: Readonly<Record<string, {
|
|
1633
|
-
readonly protectedConcurrent?: number;
|
|
1634
|
-
readonly maxConcurrent?: number;
|
|
1635
|
-
readonly protectedInFlightTokens?: number;
|
|
1636
|
-
readonly maxInFlightTokens?: number;
|
|
1637
|
-
}>>;
|
|
1638
|
-
};
|
|
1639
|
-
```
|
|
1640
|
-
|
|
1641
|
-
Applies only strictly higher revisions. See
|
|
1642
|
-
[Atomic Runtime Reconfiguration](#atomic-runtime-reconfiguration).
|
|
1643
|
-
|
|
1644
|
-
### `bulkhead.setBudget(tokens)`
|
|
1645
|
-
|
|
1646
|
-
```ts
|
|
1647
|
-
setBudget(tokens: number): void
|
|
1648
|
-
```
|
|
1649
|
-
|
|
1650
|
-
Applies a complete budget-only update and advances the local revision by one.
|
|
1651
|
-
Throws if `tokenBudget` was not configured at construction or if `tokens` is
|
|
1652
|
-
not a non-negative integer. Externally managed callers should use
|
|
1653
|
-
`applyLimits()` instead.
|
|
1654
|
-
|
|
1655
|
-
### `bulkhead.close()`
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
### `bulkhead.drain(opts?)`
|
|
1659
|
-
|
|
1660
|
-
```ts
|
|
1661
|
-
drain(): Promise<void>;
|
|
1662
|
-
drain(opts: { timeoutMs: number }): Promise<LLMDrainResult>;
|
|
1663
|
-
|
|
1664
|
-
type LLMDrainResult = {
|
|
1665
|
-
drained: boolean; // true: everything completed within the deadline
|
|
1666
|
-
inFlight: number; // outstanding at the deadline (0 when drained)
|
|
1667
|
-
pending: number; // queued waiters at the deadline (0 when drained)
|
|
1668
|
-
};
|
|
1669
|
-
```
|
|
1670
|
-
|
|
1671
|
-
Resolves when all in-flight work and pending waiters have completed. With
|
|
1672
|
-
`timeoutMs`, always resolves (never rejects) by the deadline with an
|
|
1673
|
-
`LLMDrainResult`; the deadline does not cancel in-flight work.
|
|
1674
|
-
|
|
1675
|
-
### `bulkhead.on(event, listener)`
|
|
1676
|
-
|
|
1677
|
-
```ts
|
|
1678
|
-
on<K extends keyof LLMEventMap>(
|
|
1679
|
-
event: K,
|
|
1680
|
-
listener: (payload: LLMEventMap[K]) => void,
|
|
1681
|
-
): () => void // returns unsubscribe
|
|
1682
|
-
```
|
|
1683
|
-
|
|
1684
|
-
### Types
|
|
1685
|
-
|
|
1686
|
-
```ts
|
|
1687
|
-
type LLMRequest = { model?: string; messages: LLMMessage[]; max_tokens?: number };
|
|
1688
|
-
type LLMMessage = { role: string; content: string | ContentBlock[] };
|
|
1689
|
-
type ContentBlock = TextContentBlock | OpaqueContentBlock;
|
|
1690
|
-
type TextContentBlock = { type: 'text'; text: string };
|
|
1691
|
-
type OpaqueContentBlock = { type: string; [key: string]: unknown };
|
|
1692
|
-
|
|
1693
|
-
type TokenEstimate = { input: number; maxOutput: number };
|
|
1694
|
-
type LLMReservationEstimate = TokenEstimate & { reserved: number };
|
|
1695
|
-
type TokenEstimator = (request: LLMRequest) => TokenEstimate;
|
|
1696
|
-
type TokenUsage = { input: number; output: number };
|
|
1697
|
-
type UsageReport = {
|
|
1698
|
-
admissionId: string;
|
|
1699
|
-
limitRevision: number;
|
|
1700
|
-
admissionClass?: string;
|
|
1701
|
-
sequence: number;
|
|
1702
|
-
reserved: number;
|
|
1703
|
-
held: number;
|
|
1704
|
-
consumed: number;
|
|
1705
|
-
outputCap: number | null;
|
|
1706
|
-
outputRemaining: number | null;
|
|
1707
|
-
overReservation: boolean;
|
|
1708
|
-
};
|
|
1709
|
-
|
|
1710
|
-
type LLMRejectReason =
|
|
1711
|
-
| 'concurrency_limit'
|
|
1712
|
-
| 'queue_limit'
|
|
1713
|
-
| 'budget_limit'
|
|
1714
|
-
| 'timeout'
|
|
1715
|
-
| 'aborted'
|
|
1716
|
-
| 'shutdown'
|
|
1717
|
-
| 'unshareable_result';
|
|
156
|
+
bulkhead.on('reject', ({ reason, detail }) => metrics.increment(reason));
|
|
1718
157
|
```
|
|
1719
158
|
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
## Migration
|
|
1723
|
-
|
|
1724
|
-
### v3.14 → v3.15
|
|
1725
|
-
|
|
1726
|
-
No admission call-site changes are required. Configure
|
|
1727
|
-
`protectedConcurrent` and/or `protectedInFlightTokens` only when a class needs
|
|
1728
|
-
a strict local guarantee. The sum of floors must fit inside the corresponding
|
|
1729
|
-
global limit. Floors are not automatically lent while idle; a control plane
|
|
1730
|
-
must adjust them with `applyLimits()` to implement demand-aware lending.
|
|
1731
|
-
|
|
1732
|
-
`stats().admissionClasses` gains `shared`, protected/borrowed usage fields, and
|
|
1733
|
-
cumulative borrowing counters. Rejection capacity details may now use
|
|
1734
|
-
`constraint: 'admission_class_protection'` and include `sharedCapacity`. Code
|
|
1735
|
-
that exhaustively asserts these additive object or union shapes must be
|
|
1736
|
-
updated. Omitting both floor fields preserves v3.14 admission behavior.
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
### v3.13 → v3.14
|
|
159
|
+
→ [Stats and events](guides/telemetry.md)
|
|
1740
160
|
|
|
1741
|
-
|
|
1742
|
-
all new lifecycle fields are optional when the feature is disabled. Code that
|
|
1743
|
-
exhaustively asserts event, stats, limit-snapshot, token, run-context, usage,
|
|
1744
|
-
or rejection-detail shapes should account for the additive class fields.
|
|
1745
|
-
Gateways should pass only trusted, bounded policy-class IDs. Admission class
|
|
1746
|
-
automatically partitions in-flight deduplication, while `dedupScope` remains
|
|
1747
|
-
required for tenant-level isolation inside a shared class.
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
### v3.11.0 → v3.11.1
|
|
1751
|
-
|
|
1752
|
-
No code changes are required. Update the dependency to v3.11.1 and regenerate
|
|
1753
|
-
your lockfile. The patch keeps the v3.11 API unchanged, replaces the conflicting
|
|
1754
|
-
v3.11.0 package artifact, updates the development dependency lockfile, and
|
|
1755
|
-
corrects the strict capacity-snapshot test expectation.
|
|
1756
|
-
|
|
1757
|
-
### v3.10 → v3.11
|
|
1758
|
-
|
|
1759
|
-
No admission call-site changes are required. Successful acquire results,
|
|
1760
|
-
admission tokens, run contexts, usage reports, lifecycle events, and rejection
|
|
1761
|
-
capacity details gain `limitRevision`. Code that uses exact deep equality on
|
|
1762
|
-
these objects must add the field. Gateways should read the captured revision
|
|
1763
|
-
from the result, token, context, event, or rejection detail instead of calling
|
|
1764
|
-
`limits()` after the decision.
|
|
1765
|
-
|
|
1766
|
-
### v3.9 → v3.10
|
|
1767
|
-
|
|
1768
|
-
Existing admission calls require no changes. `stats()` gains a `limits` block,
|
|
1769
|
-
`LLMEventType` gains `"reconfigure"`, and `setBudget()` now advances the local
|
|
1770
|
-
revision. Code that exhaustively enumerates event types should add the new
|
|
1771
|
-
case. Control-plane integrations should move from `setBudget()` to complete
|
|
1772
|
-
`applyLimits()` snapshots.
|
|
1773
|
-
|
|
1774
|
-
### v3.5 → v3.6
|
|
1775
|
-
|
|
1776
|
-
No call-site changes are required. `admit` and `release` event payloads gained
|
|
1777
|
-
additional fields, and `usage` is a new event type. Code that exhaustively
|
|
1778
|
-
enumerates `LLMEventType` should add the new `usage` case.
|
|
1779
|
-
|
|
1780
|
-
### v2 → v3
|
|
1781
|
-
|
|
1782
|
-
Update stats access from top-level fields to the `bulkhead` block:
|
|
1783
|
-
|
|
1784
|
-
```ts
|
|
1785
|
-
const s = bulkhead.stats();
|
|
1786
|
-
|
|
1787
|
-
// v2
|
|
1788
|
-
s.inFlight;
|
|
1789
|
-
s.pending;
|
|
1790
|
-
|
|
1791
|
-
// v3
|
|
1792
|
-
s.bulkhead.inFlight;
|
|
1793
|
-
s.bulkhead.pending;
|
|
1794
|
-
```
|
|
1795
|
-
|
|
1796
|
-
LLM-layer counters are now available separately:
|
|
161
|
+
## Shutting down cleanly
|
|
1797
162
|
|
|
1798
163
|
```ts
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
s.llm.rejectedByReason?.budget_limit;
|
|
164
|
+
// In your SIGTERM handler:
|
|
165
|
+
bulkhead.close(); // stop admitting
|
|
166
|
+
await bulkhead.drain({ timeoutMs: 10_000 }); // wait, but not forever
|
|
1803
167
|
```
|
|
1804
168
|
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
See [CHANGELOG](./CHANGELOG.md) for the v2 migration guide.
|
|
169
|
+
`drain()` with a deadline always resolves and tells you what it abandoned, so
|
|
170
|
+
one stuck upstream stream can't hold your deploy hostage.
|
|
1808
171
|
|
|
1809
172
|
---
|
|
1810
173
|
|
|
1811
|
-
##
|
|
1812
|
-
|
|
1813
|
-
The implementation is split into focused modules under `src/`; the package
|
|
1814
|
-
entry point (`src/index.ts`) is a barrel that re-exports the public API.
|
|
1815
|
-
Deep-importing the internal modules is not supported — the package
|
|
1816
|
-
`exports` map exposes only the entry point.
|
|
174
|
+
## Documentation
|
|
1817
175
|
|
|
1818
|
-
|
|
|
176
|
+
| Guide | What's in it |
|
|
1819
177
|
|---|---|
|
|
1820
|
-
|
|
|
1821
|
-
|
|
|
1822
|
-
|
|
|
1823
|
-
|
|
|
1824
|
-
|
|
|
1825
|
-
|
|
|
1826
|
-
|
|
|
1827
|
-
|
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
178
|
+
| [How admission works](guides/concepts.md) | The decision path, `run()` vs `acquire()`, profiles, cancellation, shutdown |
|
|
179
|
+
| [Token budget and estimation](guides/token-budget.md) | Reservations, refunds, estimators, adaptive calibration, priority reserve |
|
|
180
|
+
| [Streaming and reconciliation](guides/streaming.md) | `reportUsage()`, progressive holds, ordered usage events |
|
|
181
|
+
| [Admission classes](guides/admission-classes.md) | Per-class floors and ceilings, shared capacity, borrowing |
|
|
182
|
+
| [Runtime limits and reconfiguration](guides/runtime-limits.md) | `applyLimits()`, revisions, fail-closed startup, kill switch |
|
|
183
|
+
| [Observe mode](guides/observe-mode.md) | Measure a policy before you enforce it |
|
|
184
|
+
| [Deduplication](guides/deduplication.md) | In-flight dedup, tenant scoping, streaming results |
|
|
185
|
+
| [Gateway integration](guides/gateway-integration.md) | `wouldAdmit()`, admission IDs, external leases, control planes |
|
|
186
|
+
| [Stats and events](guides/telemetry.md) | Every counter and every event payload |
|
|
187
|
+
| [How it compares](guides/comparison.md) | Against LangChain, p-limit, cockatiel, and raw SDKs |
|
|
188
|
+
| [Migration](guides/migration.md) | Upgrade notes for every release since v2 |
|
|
189
|
+
|
|
190
|
+
The **[full API reference](https://janbalangue.github.io/async-bulkhead-llm/)**
|
|
191
|
+
is generated from the source types on every push to `main`, so it is never out
|
|
192
|
+
of date with the code. Release-by-release detail lives in the
|
|
193
|
+
[changelog](./CHANGELOG.md).
|
|
194
|
+
|
|
195
|
+
## What it deliberately doesn't do
|
|
196
|
+
|
|
197
|
+
- **No retries.** Compose a retry library *around* the bulkhead, not inside it.
|
|
198
|
+
- **No provider SDK.** Bring your own client.
|
|
199
|
+
- **No distributed coordination.** Bulkheads are per-process. Partition the
|
|
200
|
+
budget per replica, or coordinate above this layer.
|
|
201
|
+
- **No cost accounting or spend caps.** Token estimation is for load-shedding,
|
|
202
|
+
not billing. Nothing here tracks cumulative spend or stops you reaching a
|
|
203
|
+
dollar figure.
|
|
204
|
+
|
|
205
|
+
Each of those is a deliberate boundary, not a missing feature. A bulkhead that
|
|
206
|
+
also retried would defeat its own purpose.
|
|
1843
207
|
|
|
1844
208
|
## Compatibility
|
|
1845
209
|
|
|
1846
|
-
- Node.js
|
|
1847
|
-
- Module formats
|
|
210
|
+
- **Node.js:** 20+
|
|
211
|
+
- **Module formats:** ESM and CommonJS
|
|
212
|
+
- **Types:** shipped, generated from source
|
|
213
|
+
- **Public API:** only the package entry point. Deep imports into `src/`
|
|
214
|
+
internals are not supported.
|
|
1848
215
|
|
|
1849
|
-
|
|
216
|
+
## Contributing and security
|
|
217
|
+
|
|
218
|
+
Issues and pull requests are welcome at
|
|
219
|
+
[github.com/janbalangue/async-bulkhead-llm](https://github.com/janbalangue/async-bulkhead-llm/issues).
|
|
220
|
+
For security reports, see the
|
|
221
|
+
[security policy](https://github.com/janbalangue/async-bulkhead-llm/security/policy).
|
|
1850
222
|
|
|
1851
223
|
## License
|
|
1852
224
|
|
|
1853
|
-
Apache License 2.0 © 2026
|
|
225
|
+
Apache License 2.0 © 2026
|