@backendkit-labs/retry 0.1.1
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/README.md +801 -0
- package/dist/chunk-HOW7IDKS.cjs +752 -0
- package/dist/chunk-HOW7IDKS.cjs.map +1 -0
- package/dist/chunk-ZWXN4OXT.js +734 -0
- package/dist/chunk-ZWXN4OXT.js.map +1 -0
- package/dist/index.cjs +98 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +207 -0
- package/dist/index.d.ts +207 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/nestjs/index.cjs +108 -0
- package/dist/nestjs/index.cjs.map +1 -0
- package/dist/nestjs/index.d.cts +43 -0
- package/dist/nestjs/index.d.ts +43 -0
- package/dist/nestjs/index.js +104 -0
- package/dist/nestjs/index.js.map +1 -0
- package/dist/retry.engine-DSm8xWKJ.d.cts +202 -0
- package/dist/retry.engine-DSm8xWKJ.d.ts +202 -0
- package/package.json +100 -0
package/README.md
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
1
|
+
# @backendkit-labs/retry
|
|
2
|
+
|
|
3
|
+
Enterprise-grade retry library for Node.js — exponential backoff, sliding-window budget, error classification, circuit-breaker and bulkhead integration, and optional NestJS support. Returns `Result<T, RetryError>`, never throws.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@backendkit-labs/retry)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
[](package.json)
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Minimal Example
|
|
12
|
+
|
|
13
|
+
Self-contained runnable example — no NestJS, one file, realistic scenario.
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
git clone https://github.com/BackendKit-labs/backendkit-monorepo.git
|
|
17
|
+
cd backendkit-monorepo/examples/minimal-retry
|
|
18
|
+
npm install && npm start
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Shows a payment gateway that fails 60% of the time retried with exponential backoff + jitter. Lifecycle hooks log each attempt in real time. → [full source](https://github.com/BackendKit-labs/backendkit-monorepo/tree/master/examples/minimal-retry)
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Table of Contents
|
|
26
|
+
|
|
27
|
+
- [Installation](#installation)
|
|
28
|
+
- [Quick Start](#quick-start)
|
|
29
|
+
- [RetryEngine — full control](#RetryEngine--full-control)
|
|
30
|
+
- [Configuration Reference](#configuration-reference)
|
|
31
|
+
- [maxAttempts](#maxattempts)
|
|
32
|
+
- [backoff](#backoff)
|
|
33
|
+
- [retryIf / abortIf](#retryif--abortif)
|
|
34
|
+
- [timeout](#timeout)
|
|
35
|
+
- [budget](#budget)
|
|
36
|
+
- [hooks](#hooks)
|
|
37
|
+
- [fallback](#fallback)
|
|
38
|
+
- [dynamicDelay](#dynamicdelay)
|
|
39
|
+
- [classifiers](#classifiers)
|
|
40
|
+
- [Backoff Strategies](#backoff-strategies)
|
|
41
|
+
- [Error Types](#error-types)
|
|
42
|
+
- [BackendKit Integrations](#backendkit-integrations)
|
|
43
|
+
- [circuit-breaker](#backendkit-labscircuit-breaker)
|
|
44
|
+
- [bulkhead](#backendkit-labsbulkhead)
|
|
45
|
+
- [result](#backendkit-labsresult)
|
|
46
|
+
- [observability](#backendkit-labsobservability)
|
|
47
|
+
- [All three layers together](#all-three-layers-together)
|
|
48
|
+
- [NestJS Integration](#nestjs-integration)
|
|
49
|
+
- [RetryRegistry](#RetryRegistry)
|
|
50
|
+
- [API Reference](#api-reference)
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npm install @backendkit-labs/retry @backendkit-labs/result
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
NestJS peer dependencies (optional — only if using `RetryModule`):
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
npm install @nestjs/common @nestjs/core rxjs
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Quick Start
|
|
69
|
+
|
|
70
|
+
`Retry()` is a standalone function backed by a global registry. It covers 90% of use cases in two lines:
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import { Retry } from '@backendkit-labs/retry';
|
|
74
|
+
|
|
75
|
+
const result = await retry(() => fetchUser(userId), {
|
|
76
|
+
maxAttempts: 3,
|
|
77
|
+
backoff: { type: 'exponential', baseDelay: 200 },
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
result.match(
|
|
81
|
+
(user) => res.json(user),
|
|
82
|
+
(error) => res.status(502).json({ error: error.message }),
|
|
83
|
+
);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`Retry()` returns `Result<T, RetryError>` — it **never throws**. Use `.match()`, `.ok`, or `.error` to handle both paths.
|
|
87
|
+
|
|
88
|
+
### Minimal retry with default config
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
// 3 attempts, fixed 200ms delay
|
|
92
|
+
const result = await retry(() => callExternalApi());
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Handle specific error types
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
const result = await retry(() => chargePayment(order), {
|
|
99
|
+
maxAttempts: 4,
|
|
100
|
+
backoff: { type: 'exponential', baseDelay: 300, maxDelay: 5_000 },
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
if (!result.ok) {
|
|
104
|
+
const { type, status, metadata } = result.error;
|
|
105
|
+
if (type === 'http' && status === 429) {
|
|
106
|
+
// rate-limited — already retried, still failed
|
|
107
|
+
}
|
|
108
|
+
console.log(`Failed after ${metadata.attempts} attempt(s)`);
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## RetryEngine — full control
|
|
115
|
+
|
|
116
|
+
`RetryEngine` is the stateful core. Use it when you need shared configuration, per-engine metrics, or external integrations (circuit breaker, bulkhead, observability).
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
import { RetryEngine } from '@backendkit-labs/retry';
|
|
120
|
+
import { circuitBreaker } from '@backendkit-labs/circuit-breaker';
|
|
121
|
+
import { bulkhead } from '@backendkit-labs/bulkhead';
|
|
122
|
+
|
|
123
|
+
const engine = new RetryEngine({
|
|
124
|
+
name: 'payment-gateway',
|
|
125
|
+
defaultConfig: {
|
|
126
|
+
maxAttempts: 3,
|
|
127
|
+
backoff: { type: 'exponential', baseDelay: 200, maxDelay: 8_000, jitter: 'full' },
|
|
128
|
+
timeout: { attemptTimeoutMs: 5_000, globalTimeoutMs: 20_000 },
|
|
129
|
+
},
|
|
130
|
+
integrations: {
|
|
131
|
+
circuitBreaker: circuitBreaker({ failureThreshold: 5, cooldownMs: 10_000 }),
|
|
132
|
+
bulkhead: bulkhead({ maxConcurrent: 10, maxQueue: 20 }),
|
|
133
|
+
observability: {
|
|
134
|
+
logger: myLogger,
|
|
135
|
+
metrics: myMetricsEmitter,
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const result = await engine.execute(() => chargePayment(order));
|
|
141
|
+
|
|
142
|
+
// Per-execution overrides
|
|
143
|
+
const result2 = await engine.execute(
|
|
144
|
+
() => refundPayment(order),
|
|
145
|
+
{ maxAttempts: 5 },
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
// With correlationId for distributed tracing
|
|
149
|
+
const result3 = await engine.executeWithContext(
|
|
150
|
+
() => fetchInventory(productId),
|
|
151
|
+
{ correlationId: req.headers['x-request-id'] },
|
|
152
|
+
);
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
---
|
|
156
|
+
|
|
157
|
+
## Configuration Reference
|
|
158
|
+
|
|
159
|
+
All options are in `RetryConfig`. Every field except `maxAttempts` and `backoff` is optional.
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
interface RetryConfig {
|
|
163
|
+
maxAttempts: number;
|
|
164
|
+
backoff: BackoffConfig | BackoffStrategy;
|
|
165
|
+
retryIf?: RetryCondition | RetryConditionFn;
|
|
166
|
+
abortIf?: AbortCondition | AbortConditionFn;
|
|
167
|
+
timeout?: Partial<TimeoutConfig>;
|
|
168
|
+
budget?: Partial<RetryBudgetConfig>;
|
|
169
|
+
idempotency?: Partial<IdempotencyConfig>;
|
|
170
|
+
classifiers?: ClassifierRule[];
|
|
171
|
+
dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number;
|
|
172
|
+
hooks?: RetryHooks;
|
|
173
|
+
fallback?: (error: RetryErrorPayload) => unknown | Promise<unknown>;
|
|
174
|
+
correlationId?: string;
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
### maxAttempts
|
|
179
|
+
|
|
180
|
+
Total number of attempts including the first one. `maxAttempts: 3` means one initial call plus two retries.
|
|
181
|
+
|
|
182
|
+
```typescript
|
|
183
|
+
await retry(task, { maxAttempts: 5 });
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### backoff
|
|
187
|
+
|
|
188
|
+
Controls the delay between retries. Accepts a config object (shorthand) or a `BackoffStrategy` instance (composable). See [Backoff Strategies](#backoff-strategies) for all options.
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
// Shorthand (most common)
|
|
192
|
+
{ backoff: { type: 'exponential', baseDelay: 200, maxDelay: 10_000, jitter: 'full' } }
|
|
193
|
+
|
|
194
|
+
// Strategy instance (composable)
|
|
195
|
+
import { ExponentialBackoff, JitterDecorator } from '@backendkit-labs/retry';
|
|
196
|
+
const strategy = new JitterDecorator(new ExponentialBackoff({ baseDelay: 200 }), 'full');
|
|
197
|
+
{ backoff: strategy }
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### retryIf / abortIf
|
|
201
|
+
|
|
202
|
+
Fine-grained control over which errors trigger a retry and which abort immediately.
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
await retry(task, {
|
|
206
|
+
// Only retry on network errors and 5xx responses
|
|
207
|
+
retryIf: (error) => error.type === 'network' || (error.type === 'http' && (error.status ?? 0) >= 500),
|
|
208
|
+
|
|
209
|
+
// Abort immediately on 401/403 — retrying is pointless
|
|
210
|
+
abortIf: (error) => error.type === 'http' && [401, 403].includes(error.status ?? 0),
|
|
211
|
+
});
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
Both accept a plain function `(error: RetryErrorPayload) => boolean | Promise<boolean>` or an object implementing `RetryCondition` / `AbortCondition`. Default behavior: retry on 5xx, network, and timeout errors; abort on 4xx (except 429).
|
|
215
|
+
|
|
216
|
+
### timeout
|
|
217
|
+
|
|
218
|
+
Per-attempt and global timeouts are independent:
|
|
219
|
+
|
|
220
|
+
```typescript
|
|
221
|
+
await retry(task, {
|
|
222
|
+
timeout: {
|
|
223
|
+
attemptTimeoutMs: 5_000, // each individual call is capped at 5s
|
|
224
|
+
globalTimeoutMs: 30_000, // entire retry operation (including delays) capped at 30s
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
- `attemptTimeoutMs` expiration → error classified as `type: 'timeout'` → triggers retry (if retryable)
|
|
230
|
+
- `globalTimeoutMs` expiration → operation aborted immediately regardless of attempt count
|
|
231
|
+
- `0` means unlimited (default)
|
|
232
|
+
|
|
233
|
+
### budget
|
|
234
|
+
|
|
235
|
+
Sliding-window budget prevents retry storms. If the ratio of retries to total calls exceeds `maxRetryRatio` in the last `windowMs` milliseconds, further retries are rejected.
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
await retry(task, {
|
|
239
|
+
budget: {
|
|
240
|
+
windowMs: 60_000, // 1-minute sliding window
|
|
241
|
+
maxRetryRatio: 0.1, // max 10% of calls may be retries
|
|
242
|
+
minRequestCount: 20, // budget not enforced until at least 20 calls
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Budget exhaustion produces `type: 'unknown'` with `metadata.budgetExhausted: true`. Share a budget across calls by reusing the same `RetryEngine` instance.
|
|
248
|
+
|
|
249
|
+
### hooks
|
|
250
|
+
|
|
251
|
+
Lifecycle hooks for observability, logging, and debugging. Hook errors are swallowed and never affect retry state.
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
await retry(task, {
|
|
255
|
+
hooks: {
|
|
256
|
+
beforeRetry: ({ attempt, delayMs, error }) => {
|
|
257
|
+
logger.warn(`Retry #${attempt} in ${delayMs}ms — ${error.message}`);
|
|
258
|
+
},
|
|
259
|
+
afterRetry: ({ attempt, error }) => {
|
|
260
|
+
logger.debug(`Attempt ${attempt} finished with error: ${error.type}`);
|
|
261
|
+
},
|
|
262
|
+
onRetrySuccess: ({ attempt, totalAttempts, totalElapsedMs }) => {
|
|
263
|
+
logger.info(`Succeeded on attempt ${attempt}/${totalAttempts} (${totalElapsedMs}ms total)`);
|
|
264
|
+
},
|
|
265
|
+
onExhausted: ({ lastError, totalAttempts, totalElapsedMs }) => {
|
|
266
|
+
logger.error(`All ${totalAttempts} attempts failed in ${totalElapsedMs}ms`, lastError);
|
|
267
|
+
},
|
|
268
|
+
onBudgetExhausted: () => {
|
|
269
|
+
logger.warn('Retry budget exhausted — skipping retry');
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
### fallback
|
|
276
|
+
|
|
277
|
+
Return a default value when all retries are exhausted instead of returning `err(...)`:
|
|
278
|
+
|
|
279
|
+
```typescript
|
|
280
|
+
const result = await retry(() => fetchConfig(), {
|
|
281
|
+
maxAttempts: 3,
|
|
282
|
+
fallback: () => DEFAULT_CONFIG,
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// result.ok === true, result.value === DEFAULT_CONFIG
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
### dynamicDelay
|
|
289
|
+
|
|
290
|
+
Override backoff with a delay computed from the error — useful for respecting `Retry-After` headers:
|
|
291
|
+
|
|
292
|
+
```typescript
|
|
293
|
+
await retry(task, {
|
|
294
|
+
dynamicDelay: (error, attempt) => {
|
|
295
|
+
if (error.type === 'http' && error.status === 429) {
|
|
296
|
+
// Use Retry-After header value if available in cause
|
|
297
|
+
const retryAfterMs = (error.cause as any)?.retryAfterMs ?? 5_000;
|
|
298
|
+
return retryAfterMs;
|
|
299
|
+
}
|
|
300
|
+
return 0; // 0 = fall back to backoff strategy
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
### classifiers
|
|
306
|
+
|
|
307
|
+
Add custom rules that classify errors as `'transient'` (retryable) or `'permanent'` (abort):
|
|
308
|
+
|
|
309
|
+
```typescript
|
|
310
|
+
await retry(task, {
|
|
311
|
+
classifiers: [
|
|
312
|
+
{
|
|
313
|
+
name: 'business-validation',
|
|
314
|
+
priority: 1, // evaluated before built-in rules
|
|
315
|
+
match: (error) => error.type === 'http' && error.status === 422,
|
|
316
|
+
classification: 'permanent',
|
|
317
|
+
},
|
|
318
|
+
{
|
|
319
|
+
name: 'gateway-timeout',
|
|
320
|
+
priority: 50,
|
|
321
|
+
match: (error) => error.type === 'http' && error.status === 504,
|
|
322
|
+
classification: 'transient',
|
|
323
|
+
},
|
|
324
|
+
],
|
|
325
|
+
});
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
Built-in rules (lower priority number = evaluated first):
|
|
329
|
+
|
|
330
|
+
| Status / Type | Classification |
|
|
331
|
+
|---|---|
|
|
332
|
+
| 400, 401, 403, 404, 413, 422 | permanent |
|
|
333
|
+
| 429, 500–599 | transient |
|
|
334
|
+
| `network`, `timeout` | transient |
|
|
335
|
+
| `circuit-open`, `bulkhead-rejected` | transient |
|
|
336
|
+
| everything else | permanent |
|
|
337
|
+
|
|
338
|
+
---
|
|
339
|
+
|
|
340
|
+
## Backoff Strategies
|
|
341
|
+
|
|
342
|
+
Three built-in strategies, all composable with `JitterDecorator`:
|
|
343
|
+
|
|
344
|
+
### Fixed
|
|
345
|
+
|
|
346
|
+
Same delay every time:
|
|
347
|
+
|
|
348
|
+
```typescript
|
|
349
|
+
import { FixedBackoff } from '@backendkit-labs/retry';
|
|
350
|
+
|
|
351
|
+
new FixedBackoff({ baseDelay: 500 });
|
|
352
|
+
// attempt 1→2: 500ms, 2→3: 500ms, ...
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
Shorthand: `{ type: 'fixed', baseDelay: 500 }`
|
|
356
|
+
|
|
357
|
+
### Linear
|
|
358
|
+
|
|
359
|
+
Delay grows linearly:
|
|
360
|
+
|
|
361
|
+
```typescript
|
|
362
|
+
import { LinearBackoff } from '@backendkit-labs/retry';
|
|
363
|
+
|
|
364
|
+
new LinearBackoff({ baseDelay: 200, multiplier: 1.5, maxDelay: 5_000 });
|
|
365
|
+
// attempt 1→2: 200ms, 2→3: 300ms, 3→4: 450ms, ...
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
Shorthand: `{ type: 'linear', baseDelay: 200, multiplier: 1.5, maxDelay: 5_000 }`
|
|
369
|
+
|
|
370
|
+
### Exponential
|
|
371
|
+
|
|
372
|
+
Delay doubles (or scales by `multiplier`) each attempt:
|
|
373
|
+
|
|
374
|
+
```typescript
|
|
375
|
+
import { ExponentialBackoff } from '@backendkit-labs/retry';
|
|
376
|
+
|
|
377
|
+
new ExponentialBackoff({ baseDelay: 200, multiplier: 2, maxDelay: 30_000, jitter: 'full' });
|
|
378
|
+
// attempt 1→2: ~200ms, 2→3: ~400ms, 3→4: ~800ms, ...
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
Shorthand: `{ type: 'exponential', baseDelay: 200, maxDelay: 30_000, jitter: 'full' }`
|
|
382
|
+
|
|
383
|
+
Jitter types: `'full'` (uniform random in [0, delay]), `'equal'` (delay/2 + random in [0, delay/2]), `'decorrelated'` (delay based on previous delay × random).
|
|
384
|
+
|
|
385
|
+
### JitterDecorator
|
|
386
|
+
|
|
387
|
+
Wrap any strategy with jitter:
|
|
388
|
+
|
|
389
|
+
```typescript
|
|
390
|
+
import { LinearBackoff, JitterDecorator } from '@backendkit-labs/retry';
|
|
391
|
+
|
|
392
|
+
const strategy = new JitterDecorator(
|
|
393
|
+
new LinearBackoff({ baseDelay: 300 }),
|
|
394
|
+
'full',
|
|
395
|
+
);
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
---
|
|
399
|
+
|
|
400
|
+
## Error Types
|
|
401
|
+
|
|
402
|
+
`RetryError` is the union of `RetryErrorPayload` and `RetryMetadata`:
|
|
403
|
+
|
|
404
|
+
```typescript
|
|
405
|
+
type RetryError = RetryErrorPayload & { metadata: RetryMetadata };
|
|
406
|
+
|
|
407
|
+
interface RetryErrorPayload {
|
|
408
|
+
type: ErrorType; // 'http' | 'network' | 'timeout' | 'circuit-open' | 'bulkhead-rejected' | 'business' | 'unknown'
|
|
409
|
+
message: string;
|
|
410
|
+
status?: number; // HTTP status code (only when type === 'http')
|
|
411
|
+
cause?: unknown; // original thrown error
|
|
412
|
+
attempt: number; // attempt number when this error occurred
|
|
413
|
+
elapsedMs: number; // elapsed ms at this point
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
interface RetryMetadata {
|
|
417
|
+
attempts: number; // total attempts made
|
|
418
|
+
totalElapsedMs: number; // total operation duration
|
|
419
|
+
lastError?: RetryErrorPayload;
|
|
420
|
+
budgetExhausted?: boolean; // true if stopped by budget
|
|
421
|
+
circuitOpen?: boolean; // true if stopped by circuit breaker
|
|
422
|
+
}
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
Handling different error types:
|
|
426
|
+
|
|
427
|
+
```typescript
|
|
428
|
+
const result = await retry(() => callApi());
|
|
429
|
+
|
|
430
|
+
if (!result.ok) {
|
|
431
|
+
const error = result.error;
|
|
432
|
+
|
|
433
|
+
switch (error.type) {
|
|
434
|
+
case 'http':
|
|
435
|
+
console.log(`HTTP ${error.status} after ${error.metadata.attempts} attempts`);
|
|
436
|
+
break;
|
|
437
|
+
case 'timeout':
|
|
438
|
+
console.log(`Timed out after ${error.metadata.totalElapsedMs}ms`);
|
|
439
|
+
break;
|
|
440
|
+
case 'circuit-open':
|
|
441
|
+
console.log('Circuit breaker is OPEN — fast-failed without retrying');
|
|
442
|
+
break;
|
|
443
|
+
case 'network':
|
|
444
|
+
console.log('Network error:', error.cause);
|
|
445
|
+
break;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
---
|
|
451
|
+
|
|
452
|
+
## BackendKit Integrations
|
|
453
|
+
|
|
454
|
+
All integrations are **duck-typed** — `Retry` never imports any other BackendKit library at compile time. You connect them by passing the instance directly to `RetryEngine`. Any object that satisfies the minimal interface works, including mocks in tests.
|
|
455
|
+
|
|
456
|
+
---
|
|
457
|
+
|
|
458
|
+
### `@backendkit-labs/circuit-breaker`
|
|
459
|
+
|
|
460
|
+
The circuit breaker controls whether to attempt a call. `Retry` checks it before each attempt:
|
|
461
|
+
|
|
462
|
+
```typescript
|
|
463
|
+
import { CircuitBreaker } from '@backendkit-labs/circuit-breaker';
|
|
464
|
+
import { RetryEngine } from '@backendkit-labs/retry';
|
|
465
|
+
|
|
466
|
+
const cb = new CircuitBreaker({ name: 'payments', threshold: 5 });
|
|
467
|
+
|
|
468
|
+
const engine = new RetryEngine({
|
|
469
|
+
name: 'payments',
|
|
470
|
+
integrations: {
|
|
471
|
+
circuitBreaker: cb, // duck-typed: canAttempt() / onSuccess() / onError()
|
|
472
|
+
},
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
const result = await engine.execute(() => chargePayment(order));
|
|
476
|
+
|
|
477
|
+
if (!result.ok && result.error.type === 'circuit-open') {
|
|
478
|
+
// Breaker was OPEN — Retry returned immediately without calling the task
|
|
479
|
+
}
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
**Execution flow:**
|
|
483
|
+
1. `Retry` calls `cb.canAttempt()` before every attempt. If `false` → returns `{ type: 'circuit-open' }` immediately.
|
|
484
|
+
2. On success → `cb.onSuccess(durationMs)` — registers the healthy call.
|
|
485
|
+
3. On transient failure → `cb.onError(err)` — updates the breaker's failure counter.
|
|
486
|
+
4. On permanent/business failure (e.g. 422) → CB is **not** notified — this is not an infrastructure problem.
|
|
487
|
+
|
|
488
|
+
**The real value:** the circuit breaker stops calls when the service is known to be down. `Retry` acts as the gradual recovery mechanism — it waits with backoff and retries when the breaker transitions to half-open.
|
|
489
|
+
|
|
490
|
+
---
|
|
491
|
+
|
|
492
|
+
### `@backendkit-labs/bulkhead`
|
|
493
|
+
|
|
494
|
+
Limits the concurrency of attempts. Every attempt — including retries — passes through the bulkhead:
|
|
495
|
+
|
|
496
|
+
```typescript
|
|
497
|
+
import { Bulkhead } from '@backendkit-labs/bulkhead';
|
|
498
|
+
import { RetryEngine } from '@backendkit-labs/retry';
|
|
499
|
+
|
|
500
|
+
const bulkhead = new Bulkhead({ maxConcurrent: 10, maxQueue: 20 });
|
|
501
|
+
|
|
502
|
+
const engine = new RetryEngine({
|
|
503
|
+
name: 'orders',
|
|
504
|
+
integrations: {
|
|
505
|
+
bulkhead, // duck-typed: execute(fn) / isFull()
|
|
506
|
+
},
|
|
507
|
+
});
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
**Execution flow:**
|
|
511
|
+
- Each attempt (including retries) is wrapped in `bulkhead.execute(fn)`.
|
|
512
|
+
- If the bulkhead is full → it rejects → `Retry` classifies as `type: 'bulkhead-rejected'` (transient by default) → waits with backoff and re-queues.
|
|
513
|
+
|
|
514
|
+
---
|
|
515
|
+
|
|
516
|
+
### `@backendkit-labs/result`
|
|
517
|
+
|
|
518
|
+
`Retry()` already returns `Result<T, RetryError>` — direct integration, no adapter needed:
|
|
519
|
+
|
|
520
|
+
```typescript
|
|
521
|
+
import { Retry } from '@backendkit-labs/retry';
|
|
522
|
+
|
|
523
|
+
const result = await retry(() => fetchOrder(id), {
|
|
524
|
+
maxAttempts: 3,
|
|
525
|
+
backoff: { type: 'exponential', baseDelay: 200 },
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
result.match(
|
|
529
|
+
(order) => res.json(order),
|
|
530
|
+
(err) => res.status(502).json({ message: err.message, attempts: err.metadata.attempts }),
|
|
531
|
+
);
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
When combining with `@backendkit-labs/http-client` (which also returns `Result`), unwrap between layers so `Retry` sees a thrown error instead of a nested `Result`:
|
|
535
|
+
|
|
536
|
+
```typescript
|
|
537
|
+
const result = await retry(
|
|
538
|
+
async () => {
|
|
539
|
+
const r = await httpClient.get<Order>('/orders/1');
|
|
540
|
+
if (!r.ok) throw Object.assign(new Error(r.error.message), { status: r.error.status });
|
|
541
|
+
return r.value;
|
|
542
|
+
},
|
|
543
|
+
{ maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 100 } },
|
|
544
|
+
);
|
|
545
|
+
```
|
|
546
|
+
|
|
547
|
+
The thrown error with a `.status` property is detected as `type: 'http'` and classified correctly by the built-in rules.
|
|
548
|
+
|
|
549
|
+
---
|
|
550
|
+
|
|
551
|
+
### `@backendkit-labs/observability`
|
|
552
|
+
|
|
553
|
+
Plug in any logger and metrics emitter that satisfy the minimal duck-typed interfaces:
|
|
554
|
+
|
|
555
|
+
```typescript
|
|
556
|
+
import { Logger } from '@backendkit-labs/observability';
|
|
557
|
+
|
|
558
|
+
const logger = new Logger({ service: 'payments' });
|
|
559
|
+
|
|
560
|
+
const engine = new RetryEngine({
|
|
561
|
+
name: 'payments',
|
|
562
|
+
integrations: {
|
|
563
|
+
observability: {
|
|
564
|
+
logger, // info / warn / error
|
|
565
|
+
metrics: metricsRegistry, // emit(event)
|
|
566
|
+
},
|
|
567
|
+
},
|
|
568
|
+
});
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
**Logs emitted automatically:**
|
|
572
|
+
|
|
573
|
+
```
|
|
574
|
+
WARN "Retry: attempt failed" { attempt: 2, type: 'http', classification: 'transient' }
|
|
575
|
+
ERROR "Retry: exhausted" { attempts: 3, type: 'http', totalElapsedMs: 1842 }
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
**Metrics emitted automatically:**
|
|
579
|
+
|
|
580
|
+
| Metric | When | Tags |
|
|
581
|
+
|---|---|---|
|
|
582
|
+
| `Retry.attempt_failed` | After each failed attempt | `attempt`, `type`, `classification` |
|
|
583
|
+
| `Retry.success` | On eventual success | `attempt` (attempt number that succeeded) |
|
|
584
|
+
| `Retry.exhausted` | All retries exhausted | `type` |
|
|
585
|
+
| `Retry.budget_exhausted` | Budget refused a retry | — |
|
|
586
|
+
|
|
587
|
+
---
|
|
588
|
+
|
|
589
|
+
### All three layers together
|
|
590
|
+
|
|
591
|
+
The most complete pattern for a production service — circuit breaker, bulkhead, budget, timeout, and observability in a single engine:
|
|
592
|
+
|
|
593
|
+
```typescript
|
|
594
|
+
import { CircuitBreaker } from '@backendkit-labs/circuit-breaker';
|
|
595
|
+
import { Bulkhead } from '@backendkit-labs/bulkhead';
|
|
596
|
+
import { Logger } from '@backendkit-labs/observability';
|
|
597
|
+
import { RetryEngine } from '@backendkit-labs/retry';
|
|
598
|
+
|
|
599
|
+
const cb = new CircuitBreaker({ name: 'payments', threshold: 5 });
|
|
600
|
+
const bulkhead = new Bulkhead({ maxConcurrent: 10, maxQueue: 20 });
|
|
601
|
+
const logger = new Logger({ service: 'payments-client' });
|
|
602
|
+
|
|
603
|
+
const engine = new RetryEngine({
|
|
604
|
+
name: 'payments-client',
|
|
605
|
+
defaultConfig: {
|
|
606
|
+
maxAttempts: 4,
|
|
607
|
+
backoff: { type: 'exponential', baseDelay: 200, maxDelay: 5_000, jitter: 'full' },
|
|
608
|
+
budget: { windowMs: 60_000, maxRetryRatio: 0.15 }, // max 15% retries per minute
|
|
609
|
+
timeout: { attemptTimeoutMs: 3_000, globalTimeoutMs: 12_000 },
|
|
610
|
+
},
|
|
611
|
+
integrations: {
|
|
612
|
+
circuitBreaker: cb,
|
|
613
|
+
bulkhead,
|
|
614
|
+
observability: { logger, metrics: metricsRegistry },
|
|
615
|
+
},
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
const result = await engine.execute(() => chargePayment(order));
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
**What happens per attempt:**
|
|
622
|
+
|
|
623
|
+
```
|
|
624
|
+
budget.recordCall()
|
|
625
|
+
→ checkGlobalTimeout() ← abort if 12s total exceeded
|
|
626
|
+
→ cb.canAttempt() ← fast-fail if circuit is OPEN
|
|
627
|
+
→ bulkhead.execute(...) ← limit concurrency
|
|
628
|
+
→ executeWithAttemptTimeout(3_000) ← cap each call at 3s
|
|
629
|
+
→ success: cb.onSuccess() / budget.recordSuccess()
|
|
630
|
+
→ failure: cb.onError() / budget.recordFailure()
|
|
631
|
+
→ abort? retry? budget exhausted? → backoff and loop
|
|
632
|
+
```
|
|
633
|
+
|
|
634
|
+
---
|
|
635
|
+
|
|
636
|
+
## NestJS Integration
|
|
637
|
+
|
|
638
|
+
Import `RetryModule` once at the application root. It registers `RetryService` and an optional global `RetryInterceptor`.
|
|
639
|
+
|
|
640
|
+
### Module setup
|
|
641
|
+
|
|
642
|
+
```typescript
|
|
643
|
+
import { RetryModule } from '@backendkit-labs/retry/nestjs';
|
|
644
|
+
|
|
645
|
+
@Module({
|
|
646
|
+
imports: [
|
|
647
|
+
RetryModule.forRoot({
|
|
648
|
+
engineConfig: {
|
|
649
|
+
name: 'default',
|
|
650
|
+
defaultConfig: {
|
|
651
|
+
maxAttempts: 3,
|
|
652
|
+
backoff: { type: 'exponential', baseDelay: 200, jitter: 'full' },
|
|
653
|
+
},
|
|
654
|
+
},
|
|
655
|
+
globalInterceptor: false, // set true to apply @Retry to all controllers globally
|
|
656
|
+
}),
|
|
657
|
+
],
|
|
658
|
+
})
|
|
659
|
+
export class AppModule {}
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
### RetryService — inject and execute
|
|
663
|
+
|
|
664
|
+
```typescript
|
|
665
|
+
import { Injectable } from '@nestjs/common';
|
|
666
|
+
import { RetryService } from '@backendkit-labs/retry/nestjs';
|
|
667
|
+
|
|
668
|
+
@Injectable()
|
|
669
|
+
export class PaymentsService {
|
|
670
|
+
constructor(private readonly Retry: RetryService) {}
|
|
671
|
+
|
|
672
|
+
async charge(order: Order) {
|
|
673
|
+
const result = await this.Retry.execute(
|
|
674
|
+
() => this.gateway.charge(order),
|
|
675
|
+
{ maxAttempts: 4, backoff: { type: 'exponential', baseDelay: 300 } },
|
|
676
|
+
);
|
|
677
|
+
|
|
678
|
+
if (!result.ok) throw new ServiceUnavailableException(result.error.message);
|
|
679
|
+
return result.value;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
### @Retry decorator
|
|
685
|
+
|
|
686
|
+
Mark a method for retry without changing its signature. Pairs with `RetryInterceptor`:
|
|
687
|
+
|
|
688
|
+
```typescript
|
|
689
|
+
import { Retry } from '@backendkit-labs/retry/nestjs';
|
|
690
|
+
|
|
691
|
+
@Injectable()
|
|
692
|
+
export class InventoryService {
|
|
693
|
+
@Retry({
|
|
694
|
+
maxAttempts: 3,
|
|
695
|
+
backoff: { type: 'exponential', baseDelay: 150 },
|
|
696
|
+
})
|
|
697
|
+
async reserveStock(productId: string, quantity: number) {
|
|
698
|
+
return this.http.post('/inventory/reserve', { productId, quantity });
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
### DI tokens
|
|
704
|
+
|
|
705
|
+
Inject the underlying engine or registry directly:
|
|
706
|
+
|
|
707
|
+
```typescript
|
|
708
|
+
import { Inject } from '@nestjs/common';
|
|
709
|
+
import { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN } from '@backendkit-labs/retry/nestjs';
|
|
710
|
+
import type { RetryEngine, RetryRegistry } from '@backendkit-labs/retry';
|
|
711
|
+
|
|
712
|
+
@Injectable()
|
|
713
|
+
export class MyService {
|
|
714
|
+
constructor(
|
|
715
|
+
@Inject(RETRY_ENGINE_TOKEN) private engine: RetryEngine,
|
|
716
|
+
@Inject(RETRY_REGISTRY_TOKEN) private registry: RetryRegistry,
|
|
717
|
+
) {}
|
|
718
|
+
}
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
---
|
|
722
|
+
|
|
723
|
+
## RetryRegistry
|
|
724
|
+
|
|
725
|
+
`RetryRegistry` manages named `RetryEngine` instances — useful when different services need different retry configurations in the same process.
|
|
726
|
+
|
|
727
|
+
```typescript
|
|
728
|
+
import { RetryRegistry } from '@backendkit-labs/retry';
|
|
729
|
+
|
|
730
|
+
const registry = new RetryRegistry();
|
|
731
|
+
|
|
732
|
+
const paymentEngine = registry.getOrCreate('payments', {
|
|
733
|
+
defaultConfig: { maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 300 } },
|
|
734
|
+
});
|
|
735
|
+
|
|
736
|
+
const emailEngine = registry.getOrCreate('email', {
|
|
737
|
+
defaultConfig: { maxAttempts: 5, backoff: { type: 'fixed', baseDelay: 1_000 } },
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
// Retrieve later by name
|
|
741
|
+
const engine = registry.get('payments');
|
|
742
|
+
|
|
743
|
+
// Metrics snapshot for all engines
|
|
744
|
+
const allMetrics = registry.getAllMetrics();
|
|
745
|
+
|
|
746
|
+
// Reset a specific engine's state
|
|
747
|
+
registry.reset('payments');
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
---
|
|
751
|
+
|
|
752
|
+
## API Reference
|
|
753
|
+
|
|
754
|
+
### `Retry(task, options?)`
|
|
755
|
+
|
|
756
|
+
Standalone function using a global default registry.
|
|
757
|
+
|
|
758
|
+
| Param | Type | Description |
|
|
759
|
+
|---|---|---|
|
|
760
|
+
| `task` | `() => Promise<T>` | The async operation to retry |
|
|
761
|
+
| `options` | `Partial<RetryConfig>` | Optional config overrides |
|
|
762
|
+
| Returns | `Promise<Result<T, RetryError>>` | Never throws |
|
|
763
|
+
|
|
764
|
+
### `RetryEngine`
|
|
765
|
+
|
|
766
|
+
| Method | Signature | Description |
|
|
767
|
+
|---|---|---|
|
|
768
|
+
| `execute` | `<T>(task, options?) => Promise<Result<T, RetryError>>` | Execute with retry |
|
|
769
|
+
| `executeWithContext` | `<T>(task, { correlationId? }, options?) => Promise<Result<T, RetryError>>` | Execute with correlationId |
|
|
770
|
+
| `updateDefaults` | `(partial: Partial<RetryConfig>) => void` | Update engine defaults at runtime |
|
|
771
|
+
| `getMetrics` | `() => RetryMetricsSnapshot` | Get current metrics |
|
|
772
|
+
| `resetMetrics` | `() => void` | Reset metrics counters |
|
|
773
|
+
|
|
774
|
+
### `RetryRegistry`
|
|
775
|
+
|
|
776
|
+
| Method | Signature | Description |
|
|
777
|
+
|---|---|---|
|
|
778
|
+
| `getOrCreate` | `(name, config?) => RetryEngine` | Get or create a named engine |
|
|
779
|
+
| `get` | `(name) => RetryEngine \| undefined` | Get engine by name |
|
|
780
|
+
| `reset` | `(name) => void` | Remove a named engine |
|
|
781
|
+
| `resetAll` | `() => void` | Remove all engines |
|
|
782
|
+
| `getAllMetrics` | `() => Record<string, RetryMetricsSnapshot>` | Metrics for all engines |
|
|
783
|
+
|
|
784
|
+
### NestJS exports (`@backendkit-labs/retry/nestjs`)
|
|
785
|
+
|
|
786
|
+
| Export | Type | Description |
|
|
787
|
+
|---|---|---|
|
|
788
|
+
| `RetryModule` | `DynamicModule` | `RetryModule.forRoot(options?)` |
|
|
789
|
+
| `RetryService` | `Injectable` | `.execute(task, options?)` |
|
|
790
|
+
| `Retry` | `MethodDecorator` | `@Retry(config)` |
|
|
791
|
+
| `RetryInterceptor` | `NestInterceptor` | Intercepts methods decorated with `@Retry` |
|
|
792
|
+
| `RETRY_ENGINE_TOKEN` | `string` | DI token for `RetryEngine` |
|
|
793
|
+
| `RETRY_REGISTRY_TOKEN` | `string` | DI token for `RetryRegistry` |
|
|
794
|
+
|
|
795
|
+
---
|
|
796
|
+
|
|
797
|
+
## License
|
|
798
|
+
|
|
799
|
+
Apache-2.0 — see [LICENSE](LICENSE) for details.
|
|
800
|
+
|
|
801
|
+
Part of the [BackendKit Labs](https://backendkitlabs.dev) ecosystem.
|