async-bulkhead-llm 1.0.0
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/LICENSE +195 -0
- package/README.md +452 -0
- package/dist/cjs/index.cjs +343 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/esm/index.js +336 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/types/index.d.ts +203 -0
- package/dist/types/index.d.ts.map +1 -0
- package/package.json +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
51
|
+
or written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of discussing and
|
|
55
|
+
improving the Work, but excluding communication that is conspicuously
|
|
56
|
+
marked or otherwise designated in writing by the copyright owner as
|
|
57
|
+
"Not a Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and subsequently
|
|
61
|
+
incorporated within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent claims licensable
|
|
76
|
+
by such Contributor that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
78
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
79
|
+
institute patent litigation against any entity (including a cross-claim
|
|
80
|
+
or counterclaim in a lawsuit) alleging that the Work or a Contribution
|
|
81
|
+
incorporated within the Work constitutes patent or contributory patent
|
|
82
|
+
infringement, then any patent licenses granted to You under this
|
|
83
|
+
License for that Work shall terminate as of the date such litigation
|
|
84
|
+
is filed.
|
|
85
|
+
|
|
86
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
87
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
88
|
+
modifications, and in Source or Object form, provided that You
|
|
89
|
+
meet the following conditions:
|
|
90
|
+
|
|
91
|
+
(a) You must give any other recipients of the Work or Derivative Works
|
|
92
|
+
a copy of this License; and
|
|
93
|
+
|
|
94
|
+
(b) You must cause any modified files to carry prominent notices
|
|
95
|
+
stating that You changed the files; and
|
|
96
|
+
|
|
97
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
98
|
+
that You distribute, all copyright, patent, trademark, and
|
|
99
|
+
attribution notices from the Source form of the Work,
|
|
100
|
+
excluding those notices that do not pertain to any part of
|
|
101
|
+
the Derivative Works; and
|
|
102
|
+
|
|
103
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
104
|
+
distribution, You must include a readable copy of the attribution
|
|
105
|
+
notices contained within such NOTICE file, in at least one of
|
|
106
|
+
the following places: within a NOTICE text file distributed as
|
|
107
|
+
part of the Derivative Works; within the Source form or
|
|
108
|
+
documentation, if provided along with the Derivative Works; or,
|
|
109
|
+
within a display generated by the Derivative Works, if and
|
|
110
|
+
wherever such third-party notices normally appear. The contents
|
|
111
|
+
of the NOTICE file are for informational purposes only and do
|
|
112
|
+
not modify the License. You may add Your own attribution notices
|
|
113
|
+
within Derivative Works that You distribute, alongside or as an
|
|
114
|
+
addendum to the NOTICE text from the Work, provided that such
|
|
115
|
+
additional attribution notices cannot be construed as modifying
|
|
116
|
+
the License.
|
|
117
|
+
|
|
118
|
+
You may add Your own license statement for Your modifications and
|
|
119
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
120
|
+
publish, distribute, sublicense, and/or sell copies of the Work,
|
|
121
|
+
and to permit persons to whom the Work is furnished to do so,
|
|
122
|
+
provided Your conditions do not contradict the terms of this License.
|
|
123
|
+
|
|
124
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
125
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
126
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
127
|
+
this License, without any additional terms or conditions.
|
|
128
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
129
|
+
the terms of any separate license agreement you may have executed
|
|
130
|
+
with Licensor regarding such Contributions.
|
|
131
|
+
|
|
132
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
133
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
134
|
+
except as required for reasonable and customary use in describing the
|
|
135
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
136
|
+
|
|
137
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
138
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
139
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
140
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
141
|
+
implied, including, without limitation, any conditions of title,
|
|
142
|
+
non-infringement, merchantability, or fitness for a particular
|
|
143
|
+
purpose. You are solely responsible for determining the
|
|
144
|
+
appropriateness of using or reproducing the Work and assume any
|
|
145
|
+
risks associated with Your exercise of permissions under this License.
|
|
146
|
+
|
|
147
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
148
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
149
|
+
unless required by applicable law (such as deliberate and grossly
|
|
150
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
151
|
+
liable to You for damages, including any direct, indirect, special,
|
|
152
|
+
incidental, or exemplary damages of any character arising as a
|
|
153
|
+
result of this License or out of the use or inability to use the
|
|
154
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
155
|
+
work stoppage, computer failure or malfunction, or all other
|
|
156
|
+
commercial damages or losses), even if such Contributor has been
|
|
157
|
+
advised of the possibility of such damages.
|
|
158
|
+
|
|
159
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
160
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
161
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
162
|
+
or other liability obligations and/or rights consistent with this
|
|
163
|
+
License. However, in accepting such obligations, You may act only
|
|
164
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
165
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
166
|
+
defend, and hold each Contributor harmless for any liability
|
|
167
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
168
|
+
of your accepting any such warranty or additional liability.
|
|
169
|
+
|
|
170
|
+
END OF TERMS AND CONDITIONS
|
|
171
|
+
|
|
172
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
173
|
+
|
|
174
|
+
To apply the Apache License to your work, attach the following
|
|
175
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
176
|
+
replaced with your own identifying information. (Don't include
|
|
177
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
178
|
+
comment syntax for the file format in question. It is also
|
|
179
|
+
recommended that a file or directory name and a description of
|
|
180
|
+
purpose be included on the same "printed page" as the copyright
|
|
181
|
+
notice for easier identification within third-party archives.
|
|
182
|
+
|
|
183
|
+
Copyright 2026 [Your Name or Organisation]
|
|
184
|
+
|
|
185
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
186
|
+
you may not use this file except in compliance with the License.
|
|
187
|
+
You may obtain a copy of the License at
|
|
188
|
+
|
|
189
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
190
|
+
|
|
191
|
+
Unless required by applicable law or agreed to in writing, software
|
|
192
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
193
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
194
|
+
See the License for the specific language governing permissions and
|
|
195
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
# async-bulkhead-llm
|
|
2
|
+
|
|
3
|
+
Fail-fast **admission control for LLM workloads**, built on [async-bulkhead-ts](https://github.com/your-org/async-bulkhead-ts).
|
|
4
|
+
|
|
5
|
+
Designed for services that need to enforce **cost ceilings, concurrency limits, and backpressure** at the boundary of their LLM calls — before request fan-out, before hitting provider rate limits, before saturation cascades.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- ✅ Hard **max in-flight** concurrency (`maxConcurrent`)
|
|
12
|
+
- ✅ **Token-aware admission** — reserves against estimated input + max output tokens
|
|
13
|
+
- ✅ **Model-aware estimation** — per-model character ratios for known providers
|
|
14
|
+
- ✅ **Fail-fast by default** — shed load early, never silently queue
|
|
15
|
+
- ✅ **Opinionated profiles** — `'interactive'` and `'batch'` presets with escape hatch
|
|
16
|
+
- ✅ **In-flight deduplication** — identical requests share one LLM call
|
|
17
|
+
- ✅ Optional **AbortSignal** and **timeout** cancellation
|
|
18
|
+
- ✅ `bulkhead.run(request, fn)` — acquire + release handled automatically
|
|
19
|
+
- ✅ Zero dependencies beyond `async-bulkhead-ts`
|
|
20
|
+
- ✅ ESM + CJS
|
|
21
|
+
- ✅ Node.js **20+**
|
|
22
|
+
|
|
23
|
+
Non-goals (by design):
|
|
24
|
+
- ❌ No retries
|
|
25
|
+
- ❌ No provider SDK — bring your own client
|
|
26
|
+
- ❌ No distributed coordination
|
|
27
|
+
- ❌ No cost accounting — token estimation is for load-shedding only
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
npm install async-bulkhead-llm
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Quick Start
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { createLLMBulkhead } from 'async-bulkhead-llm';
|
|
43
|
+
|
|
44
|
+
const bulkhead = createLLMBulkhead({
|
|
45
|
+
model: 'claude-sonnet-4',
|
|
46
|
+
maxConcurrent: 10,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const request = {
|
|
50
|
+
messages: [{ role: 'user', content: 'Summarise this document...' }],
|
|
51
|
+
max_tokens: 1024,
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// Acquire + release handled automatically.
|
|
55
|
+
// Throws LLMBulkheadRejectedError on rejection.
|
|
56
|
+
const result = await bulkhead.run(request, async () => {
|
|
57
|
+
return callYourLLMProvider(request);
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## Profiles
|
|
64
|
+
|
|
65
|
+
Two built-in presets cover the common cases. Explicit options always override preset defaults.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// Interactive — fail-fast, no waiting (default)
|
|
69
|
+
const bulkhead = createLLMBulkhead({
|
|
70
|
+
model: 'claude-sonnet-4',
|
|
71
|
+
maxConcurrent: 10,
|
|
72
|
+
profile: 'interactive', // maxQueue: 0
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
// Batch — bounded queue, 30s timeout
|
|
76
|
+
const bulkhead = createLLMBulkhead({
|
|
77
|
+
model: 'claude-sonnet-4',
|
|
78
|
+
maxConcurrent: 4,
|
|
79
|
+
profile: 'batch', // maxQueue: 20, timeoutMs: 30_000
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Escape hatch — plain object, same shape as the options
|
|
83
|
+
const bulkhead = createLLMBulkhead({
|
|
84
|
+
model: 'claude-sonnet-4',
|
|
85
|
+
maxConcurrent: 4,
|
|
86
|
+
profile: { maxQueue: 5, timeoutMs: 5_000 },
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
If no profile is set, the default is fail-fast (`maxQueue: 0`).
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Token Budget
|
|
95
|
+
|
|
96
|
+
Enforce a ceiling on total tokens in-flight simultaneously. Admission is always **fail-fast** when the ceiling is hit, regardless of profile or concurrency headroom.
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
const bulkhead = createLLMBulkhead({
|
|
100
|
+
model: 'claude-sonnet-4',
|
|
101
|
+
maxConcurrent: 10,
|
|
102
|
+
tokenBudget: {
|
|
103
|
+
budget: 200_000, // max tokens in-flight at once
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Token reservations are calculated pre-admission from `input + maxOutput`. Capacity is returned when each request completes.
|
|
109
|
+
|
|
110
|
+
### How estimation works
|
|
111
|
+
|
|
112
|
+
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.
|
|
113
|
+
|
|
114
|
+
Known model families: `claude-3-5-haiku`, `claude-3-5-sonnet`, `claude-3-*`, `claude-sonnet-4`, `claude-opus-4`, `gpt-4o`, `gpt-4-turbo`, `gpt-4`, `gpt-3.5`, `o1`, `o3`, `gemini-1.5`, `gemini-2`.
|
|
115
|
+
|
|
116
|
+
**Accuracy:** ±15% for known models on English prose. Underestimates for code and non-Latin scripts.
|
|
117
|
+
**Suitable for:** load-shedding and cost ceilings.
|
|
118
|
+
**Not suitable for:** cost accounting or billing.
|
|
119
|
+
|
|
120
|
+
### Custom estimator
|
|
121
|
+
|
|
122
|
+
Bring your own for higher accuracy, or to support Azure deployment names and other non-standard model strings:
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { Tiktoken } from 'tiktoken';
|
|
126
|
+
|
|
127
|
+
const enc = new Tiktoken(/* your model encoding */);
|
|
128
|
+
|
|
129
|
+
const bulkhead = createLLMBulkhead({
|
|
130
|
+
model: 'claude-sonnet-4',
|
|
131
|
+
maxConcurrent: 10,
|
|
132
|
+
tokenBudget: {
|
|
133
|
+
budget: 200_000,
|
|
134
|
+
estimator: (request) => ({
|
|
135
|
+
input: enc.encode(request.messages.map(m => m.content).join('')).length,
|
|
136
|
+
maxOutput: request.max_tokens ?? 2_048,
|
|
137
|
+
}),
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### Estimator utilities
|
|
143
|
+
|
|
144
|
+
Both estimators are exported for use outside the bulkhead — in logging, pre-flight checks, or request routing:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
import { naiveTokenEstimator, createModelAwareTokenEstimator } from 'async-bulkhead-llm';
|
|
148
|
+
|
|
149
|
+
// Flat 4.0 ratio, zero configuration
|
|
150
|
+
const est1 = naiveTokenEstimator(request);
|
|
151
|
+
|
|
152
|
+
// Per-model ratios, optional override map
|
|
153
|
+
const estimate = createModelAwareTokenEstimator(
|
|
154
|
+
{ 'my-azure-deployment': 3.7 }, // exact overrides
|
|
155
|
+
{
|
|
156
|
+
defaultModel: 'claude-sonnet-4',
|
|
157
|
+
outputCap: 2_048,
|
|
158
|
+
onUnknownModel: (model) => console.warn(`Unknown model: ${model}`),
|
|
159
|
+
},
|
|
160
|
+
);
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
`onUnknownModel` fires when neither an override nor a built-in prefix matches. Use it to log, alert, or throw in strict environments.
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
## Deduplication
|
|
168
|
+
|
|
169
|
+
When enabled, requests with identical message content that arrive while a matching call is already in-flight share that call — only one LLM request is made.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
const bulkhead = createLLMBulkhead({
|
|
173
|
+
model: 'claude-sonnet-4',
|
|
174
|
+
maxConcurrent: 10,
|
|
175
|
+
deduplication: true,
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
// Both callers get the same result; only one LLM call is made.
|
|
179
|
+
const [r1, r2] = await Promise.all([
|
|
180
|
+
bulkhead.run(request, async () => callLLM(request)),
|
|
181
|
+
bulkhead.run(request, async () => callLLM(request)), // deduped
|
|
182
|
+
]);
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
**v1 key:** `JSON.stringify(request.messages)`. Requests with different `max_tokens` but identical messages are treated as duplicates. Key design is a known limitation in v1.
|
|
186
|
+
|
|
187
|
+
Deduplication stats are tracked:
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
bulkhead.stats().deduplication
|
|
191
|
+
// { active: 2, hits: 5 }
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
## Cancellation
|
|
197
|
+
|
|
198
|
+
Cancel waiting or in-flight requests with an `AbortSignal`:
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
const ac = new AbortController();
|
|
202
|
+
|
|
203
|
+
await bulkhead.run(
|
|
204
|
+
request,
|
|
205
|
+
async (signal) => callLLM(request, { signal }),
|
|
206
|
+
{ signal: ac.signal },
|
|
207
|
+
);
|
|
208
|
+
|
|
209
|
+
// Somewhere else:
|
|
210
|
+
ac.abort(); // cancels if still waiting; signals fn if already in-flight
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The signal is passed through to your function. The bulkhead does not forcibly terminate in-flight work — your function is responsible for observing the signal.
|
|
214
|
+
|
|
215
|
+
Bound waiting time independently with `timeoutMs`:
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
await bulkhead.run(request, async () => callLLM(request), { timeoutMs: 5_000 });
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
`timeoutMs` applies to the waiting period only. It has no effect when `maxQueue` is 0.
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
## Manual Acquire / Release
|
|
226
|
+
|
|
227
|
+
For cases where `run()` doesn't fit your control flow:
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
const r = await bulkhead.acquire(request);
|
|
231
|
+
|
|
232
|
+
if (!r.ok) {
|
|
233
|
+
// r.reason: 'concurrency_limit' | 'queue_limit' | 'budget_limit' | 'timeout' | 'aborted'
|
|
234
|
+
return respond503(r.reason);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
try {
|
|
238
|
+
return await callLLM(request);
|
|
239
|
+
} finally {
|
|
240
|
+
r.token.release();
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
You must call `token.release()` exactly once if acquisition succeeds.
|
|
245
|
+
|
|
246
|
+
> **v1 note:** Token budget reservations are not correctable after admission when using `acquire()` directly — the refund mechanism (adjusting reservations based on actual usage) is deferred to v2. For accurate budget accounting, prefer `run()`.
|
|
247
|
+
|
|
248
|
+
---
|
|
249
|
+
|
|
250
|
+
## Handling Rejections
|
|
251
|
+
|
|
252
|
+
`run()` throws `LLMBulkheadRejectedError` on rejection:
|
|
253
|
+
|
|
254
|
+
```ts
|
|
255
|
+
import { LLMBulkheadRejectedError } from 'async-bulkhead-llm';
|
|
256
|
+
|
|
257
|
+
try {
|
|
258
|
+
await bulkhead.run(request, async () => callLLM(request));
|
|
259
|
+
} catch (err) {
|
|
260
|
+
if (err instanceof LLMBulkheadRejectedError) {
|
|
261
|
+
// err.code === 'LLM_BULKHEAD_REJECTED'
|
|
262
|
+
// err.reason === 'concurrency_limit' | 'queue_limit' | 'budget_limit'
|
|
263
|
+
// | 'timeout' | 'aborted'
|
|
264
|
+
return respond503(`Shed: ${err.reason}`);
|
|
265
|
+
}
|
|
266
|
+
throw err;
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`acquire()` returns a result object instead of throwing — check `r.ok` before using the token.
|
|
271
|
+
|
|
272
|
+
---
|
|
273
|
+
|
|
274
|
+
## Stats
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
const s = bulkhead.stats();
|
|
278
|
+
|
|
279
|
+
s.inFlight // requests currently executing
|
|
280
|
+
s.pending // requests waiting in queue
|
|
281
|
+
s.maxConcurrent // configured limit
|
|
282
|
+
s.maxQueue // configured queue depth
|
|
283
|
+
|
|
284
|
+
// Present only when tokenBudget is configured:
|
|
285
|
+
s.tokenBudget?.budget // total ceiling
|
|
286
|
+
s.tokenBudget?.inFlightTokens // currently reserved
|
|
287
|
+
s.tokenBudget?.available // remaining headroom
|
|
288
|
+
|
|
289
|
+
// Present only when deduplication is enabled:
|
|
290
|
+
s.deduplication?.active // distinct in-flight keys
|
|
291
|
+
s.deduplication?.hits // cumulative dedup hits
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
---
|
|
295
|
+
|
|
296
|
+
## Multi-Model Routing
|
|
297
|
+
|
|
298
|
+
One bulkhead per model is the recommended pattern. Different models have different cost profiles, latency characteristics, and provider rate limits — a unified ceiling can't express those correctly.
|
|
299
|
+
|
|
300
|
+
For fallback routing, A/B testing, or canary deployments, compose multiple bulkheads with a thin routing layer:
|
|
301
|
+
|
|
302
|
+
```ts
|
|
303
|
+
const bulkheads = {
|
|
304
|
+
sonnet: createLLMBulkhead({ model: 'claude-sonnet-4', maxConcurrent: 10 }),
|
|
305
|
+
haiku: createLLMBulkhead({ model: 'claude-haiku-3', maxConcurrent: 40 }),
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
async function callWithFallback(request, isPriority: boolean) {
|
|
309
|
+
const bulkhead = isPriority ? bulkheads.sonnet : bulkheads.haiku;
|
|
310
|
+
try {
|
|
311
|
+
return await bulkhead.run(request, () => callLLM(request));
|
|
312
|
+
} catch (err) {
|
|
313
|
+
if (err instanceof LLMBulkheadRejectedError && !isPriority) {
|
|
314
|
+
// Haiku is saturated — shed rather than escalate to Sonnet.
|
|
315
|
+
throw err;
|
|
316
|
+
}
|
|
317
|
+
throw err;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
---
|
|
323
|
+
|
|
324
|
+
## API Reference
|
|
325
|
+
|
|
326
|
+
### `createLLMBulkhead(options)`
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
type LLMBulkheadOptions = {
|
|
330
|
+
model: string; // required; one bulkhead per model
|
|
331
|
+
maxConcurrent: number; // required
|
|
332
|
+
maxQueue?: number; // default: 0 (fail-fast)
|
|
333
|
+
timeoutMs?: number; // waiting timeout; no effect if maxQueue is 0
|
|
334
|
+
profile?: 'interactive' // maxQueue: 0 (default behaviour)
|
|
335
|
+
| 'batch' // maxQueue: 20, timeoutMs: 30_000
|
|
336
|
+
| LLMBulkheadPreset; // escape hatch: plain options object
|
|
337
|
+
tokenBudget?: {
|
|
338
|
+
budget: number;
|
|
339
|
+
estimator?: TokenEstimator; // default: createModelAwareTokenEstimator
|
|
340
|
+
outputCap?: number; // default: 2048
|
|
341
|
+
};
|
|
342
|
+
deduplication?: boolean; // default: false
|
|
343
|
+
};
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
Explicit options always override profile defaults.
|
|
347
|
+
|
|
348
|
+
### `bulkhead.run(request, fn, options?)`
|
|
349
|
+
|
|
350
|
+
Primary API. Acquires a slot, calls `fn`, releases on completion or error.
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
run<T>(
|
|
354
|
+
request: LLMRequest,
|
|
355
|
+
fn: (signal?: AbortSignal) => Promise<T>,
|
|
356
|
+
options?: { signal?: AbortSignal; timeoutMs?: number },
|
|
357
|
+
): Promise<T>
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
Throws `LLMBulkheadRejectedError` on rejection.
|
|
361
|
+
|
|
362
|
+
### `bulkhead.acquire(request, options?)`
|
|
363
|
+
|
|
364
|
+
Advanced. Returns a result object; you manage the token lifecycle.
|
|
365
|
+
|
|
366
|
+
```ts
|
|
367
|
+
acquire(
|
|
368
|
+
request: LLMRequest,
|
|
369
|
+
options?: { signal?: AbortSignal; timeoutMs?: number },
|
|
370
|
+
): Promise<
|
|
371
|
+
| { ok: true; token: { release(): void } }
|
|
372
|
+
| { ok: false; reason: LLMRejectReason }
|
|
373
|
+
>
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
### `bulkhead.stats()`
|
|
377
|
+
|
|
378
|
+
Returns current runtime state. See [Stats](#stats) above.
|
|
379
|
+
|
|
380
|
+
### `naiveTokenEstimator(request)`
|
|
381
|
+
|
|
382
|
+
Plain function. Flat `4.0` character-per-token ratio. No configuration.
|
|
383
|
+
|
|
384
|
+
### `createModelAwareTokenEstimator(overrides?, options?)`
|
|
385
|
+
|
|
386
|
+
Factory. Per-model ratios, longest-prefix match, exact overrides checked first.
|
|
387
|
+
|
|
388
|
+
```ts
|
|
389
|
+
createModelAwareTokenEstimator(
|
|
390
|
+
overrides?: Record<string, number>, // exact-match; caller values win
|
|
391
|
+
options?: {
|
|
392
|
+
defaultModel?: string;
|
|
393
|
+
outputCap?: number;
|
|
394
|
+
onUnknownModel?: (model: string) => void;
|
|
395
|
+
},
|
|
396
|
+
): TokenEstimator
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
### Types
|
|
400
|
+
|
|
401
|
+
```ts
|
|
402
|
+
type LLMRequest = { messages: LLMMessage[]; max_tokens?: number };
|
|
403
|
+
type LLMMessage = { role: string; content: string };
|
|
404
|
+
type TokenEstimate = { input: number; maxOutput: number };
|
|
405
|
+
type TokenEstimator = (request: LLMRequest) => TokenEstimate;
|
|
406
|
+
|
|
407
|
+
// Forward-looking: not acted on in v1, useful for annotating provider responses.
|
|
408
|
+
type TokenUsage = { input: number; output: number };
|
|
409
|
+
|
|
410
|
+
type LLMRejectReason =
|
|
411
|
+
| 'concurrency_limit'
|
|
412
|
+
| 'queue_limit'
|
|
413
|
+
| 'budget_limit'
|
|
414
|
+
| 'timeout'
|
|
415
|
+
| 'aborted';
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
---
|
|
419
|
+
|
|
420
|
+
## Design Notes
|
|
421
|
+
|
|
422
|
+
This library enforces backpressure at the boundary of your LLM calls. It does not replace higher-level concerns:
|
|
423
|
+
|
|
424
|
+
- **Retries** — compose a retry library around the bulkhead, not inside it
|
|
425
|
+
- **Cost accounting** — use provider response metadata; estimation here is for gating only
|
|
426
|
+
- **Distributed rate limiting** — use a shared token bucket; bulkheads are per-process
|
|
427
|
+
- **Model selection** — route above the bulkhead layer; each bulkhead instance is model-specific
|
|
428
|
+
|
|
429
|
+
Token estimation is deliberately approximate. The estimator's job is to prevent gross over-admission — not to predict your invoice. An estimator that's wrong by 20% still prevents the most common cost explosion: a burst of large-context requests all admitted simultaneously.
|
|
430
|
+
|
|
431
|
+
The refund mechanism (correcting reservations based on actual usage after a call completes) is on the roadmap for v2. In v1, reservations are based on `input + maxOutput` and held until release.
|
|
432
|
+
|
|
433
|
+
---
|
|
434
|
+
|
|
435
|
+
## Multimodal
|
|
436
|
+
|
|
437
|
+
`content` must be a plain string in v1. Multimodal content (images, documents, tool results as structured blocks) is not supported by the built-in estimators — non-string content is ignored, causing underestimation. Treat token budget results as a lower bound for multimodal requests.
|
|
438
|
+
|
|
439
|
+
Full multimodal support is planned for v2.
|
|
440
|
+
|
|
441
|
+
---
|
|
442
|
+
|
|
443
|
+
## Compatibility
|
|
444
|
+
|
|
445
|
+
- Node.js: 20+ (24 LTS recommended)
|
|
446
|
+
- Module formats: ESM and CommonJS
|
|
447
|
+
|
|
448
|
+
---
|
|
449
|
+
|
|
450
|
+
## License
|
|
451
|
+
|
|
452
|
+
Apache License 2.0 © 2026
|