@0xdoublesharp/lru-cache-clustered 0.0.0 → 2.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/CHANGELOG.md ADDED
@@ -0,0 +1,336 @@
1
+ # 2.0.0 / 2026-04-28
2
+
3
+ ## Breaking changes — TypeScript rewrite
4
+
5
+ - Rewritten in TypeScript with full IPC type safety via discriminated unions
6
+ - Adopted `lru-cache@11` native API (was a translated layer over `lru-cache@6`)
7
+ - Renamed methods: `del → delete`, `reset → clear`, `prune → purgeStale`, `length`/`itemCount → size`, `stale → allowStale`
8
+ - Renamed options: `maxAge → ttl`, `stale → allowStale`
9
+ - Removed `parse` / `stringify` options and `setObject` / `getObject` / `mGetObjects` / `mSetObjects` — callers handle serialization
10
+ - Removed `prune: <crontime>` option — schedule `purgeStale()` from your own scheduler
11
+ - Removed `execute(method, ...args)` — call methods directly
12
+ - Renamed `master` to `primary` everywhere (matches `cluster.isPrimary`)
13
+ - Internal IPC method renamed `sendToMaster` → `sendToPrimary`
14
+
15
+ ## Features and infrastructure
16
+
17
+ - Canonical package name is now `@0xdoublesharp/lru-cache-clustered`; `lru-cache-for-clusters-as-promised` is published from the same build at the same version
18
+ - Added `LRUCacheClustered` short alias for `LRUCacheForClustersAsPromised` (both are exported)
19
+ - Repository moved to `github.com/doublesharp/lru-cache-clustered`
20
+ - Publish workflow (`scripts/prepare-publish.mjs` + `.github/workflows/npm-publish.yml`) builds once, prepares scoped and legacy package directories, and publishes both at the same version with npm provenance via GitHub Actions OIDC, triggered by `v*` tags
21
+ - Publish prep validates required build artifacts before creating package directories
22
+ - Scoped and legacy package copies share primary state in one process to avoid duplicate IPC listeners during migration
23
+ - Dual ESM + CJS publish via `package.json` `exports`
24
+ - Generic types: `LRUCacheForClustersAsPromised<K, V>`
25
+ - Node `>=22` required
26
+ - Added `destroy()` to tear down namespace caches, stats, and fetch coordination state on the primary
27
+ - Added explicit startup controls via `LRUCacheClustered.bootstrap()` and `cache.healthCheck()`
28
+ - Added size-bounded cache support (`maxSize`, `maxEntrySize`, and `size` on write paths)
29
+ - `fetch()` now uses primary-side single-flight coordination across workers; `memoize()` is exported as a top-level helper that delegates to it
30
+ - Added `wrap()` for transparent encode/decode of cached values (gzip, MessagePack, custom symmetric codecs)
31
+ - Structured error transport over IPC: rejected promises carry `name`, `message`, `code`, `stack`, and the `cause` chain
32
+ - Dropped runtime deps: `cron`, `uuid` — request IDs use a per-process monotonic counter
33
+ - pnpm for development; node:test + c8 for tests/coverage; tsup + tsc for build
34
+ - husky `pre-commit` and `pre-push` hooks; lint-staged on staged files
35
+ - 100% line/statement/function coverage
36
+ - Property-based fuzz tests for cache, IPC, and worker layers
37
+ - CI: Node 24 test workflow, Node 22 coverage workflow for Codecov, Doublcov HTML artifacts, and GitHub Pages coverage publishing from `main`, plus a Quality workflow running lint, typecheck, knip, type-coverage, build, and size-limit
38
+ - New `assets/`: logo (`LRUCacheClustered.png`) and topology SVG diagram
39
+ - New `examples/`: six runnable clustered server examples (users / memoize, rate-limit / incr, sessions, idempotency / setIfAbsent, compressed documents / wrap, multilayer LRU + Redis)
40
+ - `incr` / `decr` retained (race-safe across workers)
41
+ - `failsafe` and `timeout` retained for worker IPC
42
+
43
+ ## Migration
44
+
45
+ See README "Migrating from older releases" for the full mapping.
46
+
47
+ # 1.7.1 / 2021-03-25
48
+
49
+ - Added `static getInstance(options)` to asynchronously return an `LRUCacheForClustersAsPromised` once the underlying `LRUCache` is guaranteed to exist.
50
+ - Added `static getAllCaches()` to return all underlying `LRUCache` instances keyed by namespace. _Use only when `cluster.isMaster === true`._
51
+ - Added `getCache()` to return underlying `LRUCache` instance. _Use only when `cluster.isMaster === true`._
52
+ - Added test coverage via GitHub Actions
53
+ - Bug fixes for namespaces
54
+ - Bug fixes for prune cron jobs
55
+ - Refactoring for maintainability
56
+ - Updated tests
57
+ - Updated dependencies
58
+
59
+ # 1.7.0 / 2021-03-25
60
+
61
+ - Refactoring for maintainability
62
+ - Update dependencies
63
+ - More reliable test coverage
64
+
65
+ # 1.6.1 / 2021-03-20
66
+
67
+ - Update types
68
+
69
+ # 1.6.0 / 2021-03-20
70
+
71
+ - Refactor codebase to be more maintainable
72
+ - Support for external `parse` and `stringify` functions, used for object caching, more efficient on large objects
73
+ - Update tests, 100% code coverage
74
+ - Update documentation
75
+ - Update dependencies
76
+ - npm audit fix
77
+
78
+ # 1.5.25 / 2021-03-02
79
+
80
+ - Update dependencies
81
+
82
+ # 1.5.24 / 2020-07-02
83
+
84
+ - Update dependencies
85
+ - npm audit fix
86
+
87
+ # 1.5.23 / 2020-06-10
88
+
89
+ - Typescript support (thanks @hanspeter1!)
90
+ - Update dependencies
91
+
92
+ # 1.5.22 / 2020-05-01
93
+
94
+ - Remove yarn.lock
95
+
96
+ # 1.5.21 / 2020-05-01
97
+
98
+ - Update dependencies
99
+
100
+ # 1.5.20 / 2019-09-29
101
+
102
+ - Update dependencies
103
+
104
+ # 1.5.19 / 2019-08-03
105
+
106
+ - Update dependencies
107
+ - Fix coverage badges with nyc
108
+
109
+ # 1.5.18 / 2019-08-01
110
+
111
+ - Update dependencies
112
+ - Use nyc for coverage
113
+
114
+ # 1.5.17 / 2019-04-25
115
+
116
+ - Update dependencies
117
+ - Lint code
118
+
119
+ # 1.5.16 / 2017-11-21
120
+
121
+ - Update dependencies
122
+
123
+ # 1.5.15 / 2017-10-14
124
+
125
+ - Update dependencies
126
+
127
+ # 1.5.14 / 2017-09-11
128
+
129
+ - Update dependencies
130
+
131
+ # 1.5.13 / 2017-08-04
132
+
133
+ - Update dependencies
134
+
135
+ # 1.5.12 / 2017-07-06
136
+
137
+ - Update dependencies
138
+
139
+ # 1.5.11 / 2017-05-07
140
+
141
+ - Update dependencies
142
+
143
+ # 1.5.10 / 2017-05-07
144
+
145
+ - Deduplicate common methods - fixes CodeClimate rating to 4.0
146
+
147
+ # 1.5.9 / 2017-05-06
148
+
149
+ - Remove `npm-shrinkwrap.json`
150
+ - Update dependencies
151
+
152
+ # 1.5.8 / 2017-03-03
153
+
154
+ - Use Google ESLint config
155
+ - Update dependencies
156
+
157
+ # 1.5.7 / 2017-02-02
158
+
159
+ - Use `yarn` for installs
160
+ - Update dependencies and dev dependencies
161
+
162
+ # 1.5.6 / 2016-12-14
163
+
164
+ - Update dependencies
165
+
166
+ # 1.5.5 / 2016-12-14
167
+
168
+ - Update dependencies
169
+
170
+ # 1.5.4 / 2016-12-05
171
+
172
+ - Update dependencies
173
+
174
+ # 1.5.3 / 2016-11-19
175
+
176
+ - Update `uuid` and `developer-tools`
177
+
178
+ # 1.5.2 / 2016-11-17
179
+
180
+ - Improved debug logging
181
+
182
+ # 1.5.1 / 2016-11-17
183
+
184
+ - Add support for `mSetObjects()` and `mGetObjects()`
185
+ - Pass namespace through to pruning job for debugging
186
+
187
+ # 1.5.0 / 2016-11-16
188
+
189
+ - Add support for `mGet([key])`, `mSet({key: value}, maxAge)`, and `mDel([key])`.
190
+
191
+ # 1.4.6 / 2016-11-16
192
+
193
+ - Always use a shared cache for consistent behavior
194
+
195
+ # 1.4.5 / 2016-11-15
196
+
197
+ - Bug fix for null objects
198
+
199
+ # 1.4.4 / 2016-11-15
200
+
201
+ - Support for getting and setting objects + test coverage
202
+ Update deps
203
+ Bump version
204
+
205
+ # 1.4.3 / 2016-11-12
206
+
207
+ - Update ESLint settings
208
+ Remove duplicated code
209
+ Update deps
210
+ Bump version
211
+
212
+ # 1.4.2 / 2016-11-08
213
+
214
+ - Update dependencies
215
+ Bump version
216
+
217
+ # 1.4.1 / 2016-10-26
218
+
219
+ - bump version
220
+ - fix the tests, provide more coverage
221
+ fix for case when no options are passed in.
222
+ - Give longer to create cache
223
+ Overwrite settings if they are different (allow workers to just use
224
+ name, for example).
225
+ Better properties on create return options
226
+ Bugfix, cache master caches by namespace.
227
+
228
+ # 1.4.0 / 2016-10-21
229
+
230
+ - Use cron to optionally prune cache on the master
231
+ Support for `maxAge` parameter on `set()`
232
+ Updated debugging
233
+ Updated test coverage
234
+ Updated deps
235
+ Bumped version
236
+ - use web sequence diagrams
237
+
238
+ # 1.3.1 / 2016-10-11
239
+
240
+ - bump version
241
+ - Update code climate config
242
+ - dedupe keys test
243
+ - dedupe tests
244
+ - Dedupe test code
245
+ - fix hello test
246
+ - Refactor tests to improve coverage and remove duplicated code.
247
+ - Downgrade version of `eslint-plugin-import`
248
+ - Update deps
249
+ Add pre-push testing
250
+ Allow code climate to calc duplication
251
+
252
+ # 1.3.0 / 2016-10-03
253
+
254
+ - When `cluster.isMaster===true` and the `caches[namespace]` is
255
+ populated, use that instead of creating a `new LRUCache()` - the master
256
+ thread will now act on the same cache as the workers.
257
+ Support for updating the max, maxAge, stale of the cache.
258
+ Update README for new features.
259
+ Update tests to provide 100% coverage.
260
+ Bump version
261
+ - use a long random string as the lru key value to give the promise time
262
+ to call the failsafe with reject()
263
+ - update eslint config for code climate
264
+ - disable duplication check
265
+ - Fix `import/no-extraneous-dependencies` value
266
+
267
+ # 1.2.0 / 2016-09-30
268
+
269
+ - Bump version
270
+ - Add support and tests for `incr()`/`decr()`
271
+ Update readme.
272
+ Syntax cleanup.
273
+
274
+ # 1.1.0 / 2016-09-29
275
+
276
+ - bump version
277
+ - Update to failsafe with `resolve(undefined)` and `reject(Error)` via
278
+ `options.failsafe=reject`, update docs
279
+
280
+ # 1.0.6 / 2016-09-29
281
+
282
+ - Update readme, bump version
283
+ - bump version
284
+
285
+ # 1.0.5 / 2016-09-29
286
+
287
+ - Export `init` method stub
288
+ Some refactoring
289
+ Add tests for timeout coverage - 100% covered!
290
+ Update README for `init()`
291
+
292
+ # 1.0.4 / 2016-09-26
293
+
294
+ - Update dependencies, new lint rules, start worker for each cpu core and
295
+ then call mocha done(), don’t resolve a value if the callback has timed
296
+ out, set timeout in options, update README, bump version
297
+
298
+ # 1.0.3 / 2016-09-21
299
+
300
+ - Bump version, remove code climate issue count since it won’t update
301
+ - Update standards/linting
302
+ Update main filename
303
+ Update tests
304
+ - update developer-tools confs
305
+ lint code
306
+ - update code climate config
307
+ - use .eslintrc instead of .eslintrc.js
308
+ - ignore eslintrc.js in code climate, update config file to standards
309
+ - check in code climate file
310
+
311
+ # 1.0.2 / 2016-08-25
312
+
313
+ - fix link in readme, bump version
314
+
315
+ # 1.0.1 / 2016-08-25
316
+
317
+ - add header, eslint config, clean up code, bump version to 1.0.1
318
+
319
+ # 1.0.0 / 2016-08-25
320
+
321
+ - fix typo, more example updates
322
+ - fix example
323
+ - more comments
324
+ - add more comments
325
+ - Update README.md
326
+ update with info about `namespace` option.
327
+ - Update README.md
328
+ update with api and options, fix example
329
+ - Update README.md
330
+ add description, install, usage, patterns.
331
+ - fix for properties on promisified lru-cache
332
+ - Update readme and add git repo to package
333
+ - Update to create coverage badge
334
+ - Only fork twice for tests
335
+ - First version, linted with test coverage.
336
+ - Initial commit
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) Justin Silver
3
+ Copyright (c) 2016-2026 Justin Silver
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,7 +1,292 @@
1
- # @0xdoublesharp/lru-cache-clustered
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/LRUCacheClustered.png" alt="LRUCacheClustered" width="180" height="180">
3
+ </p>
2
4
 
3
- This `0.0.0` package is a placeholder release used to create the npm package record before configuring npm trusted publishing.
5
+ <h1 align="center">@0xdoublesharp/lru-cache-clustered</h1>
4
6
 
5
- Install a real release version once `2.0.0` or later is published.
7
+ <p align="center"><sub>Pikas cache hay for the winter. This package caches everything else.</sub></p>
6
8
 
7
- Repository: https://github.com/doublesharp/lru-cache-clustered
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered"><img src="https://img.shields.io/npm/v/%400xdoublesharp%2Flru-cache-clustered.svg" alt="npm"></a>
11
+ <a href="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml"><img src="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
12
+ <a href="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/coverage.yml"><img src="https://github.com/doublesharp/lru-cache-clustered/actions/workflows/coverage.yml/badge.svg" alt="Coverage"></a>
13
+ <a href="https://codecov.io/gh/doublesharp/lru-cache-clustered"><img src="https://codecov.io/gh/doublesharp/lru-cache-clustered/branch/main/graph/badge.svg" alt="codecov"></a>
14
+ <a href="https://www.npmjs.com/package/@0xdoublesharp/lru-cache-clustered"><img src="https://img.shields.io/npm/dt/%400xdoublesharp%2Flru-cache-clustered.svg" alt="Downloads"></a>
15
+ </p>
16
+
17
+ ---
18
+
19
+ Node's `cluster` module gives every worker its own heap, so an in-process cache duplicates across workers and every worker cold-starts alone. An 8-worker service with a 200 MB cache pays **1.6 GB to hold the same data eight times**.
20
+
21
+ This package keeps a single `lru-cache` in the primary and lets every worker read and write it over `cluster` IPC. One copy of the data, shared warmth across workers, and atomic counters and single-flight fetches that stay correct cluster-wide. No Redis tier, no sidecar.
22
+
23
+ <p align="center">
24
+ <img src="https://raw.githubusercontent.com/doublesharp/lru-cache-clustered/main/assets/topology.svg" alt="One LRU cache shared across cluster workers via IPC. The primary process holds a Map of namespaced LRUCache instances; each worker sends typed IPC requests to the primary for every cache operation." width="100%">
25
+ </p>
26
+
27
+ ## Highlights
28
+
29
+ | Capability | What it gives you |
30
+ | ------------------------------ | ---------------------------------------------------------------------------------------------------------- |
31
+ | **One cache, N workers** | The primary owns the data. Memory cost stays flat as you scale workers, instead of multiplying. |
32
+ | **No per-worker cold start** | The first worker to load a value warms it for every other worker. |
33
+ | **Atomic counters** | `incr` / `decr` execute on the primary, so they stay race-safe under any worker count. |
34
+ | **Cluster-wide single-flight** | Concurrent misses for the same key collapse to one fetch via `fetch()` / `memoize()`. |
35
+ | **Atomic claims** | `setIfAbsent()` lets exactly one worker win a key &mdash; perfect for idempotent intake or once-only init. |
36
+ | **Pluggable codecs** | `wrap()` layers gzip, MessagePack, or any symmetric encoder over a cache without changing call sites. |
37
+ | **Per-namespace stats** | Hits, misses, sets, deletes, evictions, size &mdash; ready to scrape, no extra wiring. |
38
+ | **Rate-limiter-friendly TTLs** | `incr` keeps the original window ticking instead of resetting it on every bump. |
39
+ | **Structured IPC errors** | Worker-side rejections preserve `name`, `code`, `cause`, and `stack` from the primary. |
40
+
41
+ ## Install
42
+
43
+ `lru-cache` is a peer dependency &mdash; install it alongside this package so you control the version.
44
+
45
+ ```sh
46
+ npm install @0xdoublesharp/lru-cache-clustered lru-cache
47
+ pnpm add @0xdoublesharp/lru-cache-clustered lru-cache
48
+ yarn add @0xdoublesharp/lru-cache-clustered lru-cache
49
+ ```
50
+
51
+ TypeScript first. Dual ESM + CJS. Requires Node &ge; 22.
52
+
53
+ > The legacy package name `lru-cache-for-clusters-as-promised` is published from the same build at the same version, so existing imports keep working during a phased migration.
54
+
55
+ ## Quick start
56
+
57
+ ```ts
58
+ import cluster from 'node:cluster';
59
+ import { availableParallelism } from 'node:os';
60
+ import { LRUCacheClustered } from '@0xdoublesharp/lru-cache-clustered';
61
+
62
+ LRUCacheClustered.bootstrap();
63
+
64
+ const cache = new LRUCacheClustered<string, string>({
65
+ namespace: 'sessions',
66
+ max: 1000,
67
+ ttl: 60_000,
68
+ });
69
+
70
+ if (cluster.isPrimary) {
71
+ for (let i = 0; i < availableParallelism(); i++) cluster.fork();
72
+ } else {
73
+ await cache.set('user:42', JSON.stringify({ name: 'ada' }));
74
+ console.log(await cache.get('user:42'));
75
+ // {"name":"ada"} - every worker sees the same value
76
+ }
77
+ ```
78
+
79
+ A few things worth knowing up front:
80
+
81
+ - **`LRUCacheClustered` is the short alias** for `LRUCacheForClustersAsPromised`. The long name is still exported.
82
+ - **Import in the primary before `cluster.fork()`.** The primary-side IPC listener is installed at module import. Call `LRUCacheClustered.bootstrap()` if you want that setup to be explicit.
83
+ - **This is a coordination layer, not a security boundary.** Any code in any worker can use any namespace it knows; do not expose namespaces to untrusted callers.
84
+
85
+ ## When to use it
86
+
87
+ Reach for this package when you have a multi-worker Node service and want shared in-process caching without standing up a separate caching tier:
88
+
89
+ - Session and profile caches
90
+ - Rate limiters and quota counters
91
+ - Feature flag snapshots
92
+ - Deduplicating expensive API or database calls
93
+ - Any cache-aside pattern across workers
94
+
95
+ It is also a strong fit as the **L1 in a multi-layer cache** in front of Redis or Memcached. Hot keys are served in-process, the long tail falls through to the shared remote cache, and the origin only sees true cold misses.
96
+
97
+ Reach for something else when you need sharing across multiple machines (use Redis or Memcached, or layer this in front of one), or when your hottest path cannot tolerate an IPC hop on a miss. See [Performance profile](#performance-profile).
98
+
99
+ ## Examples
100
+
101
+ Runnable clustered server examples &mdash; see [`examples/README.md`](./examples/README.md) for run instructions and curl recipes.
102
+
103
+ - [`clustered-users-server.ts`](./examples/clustered-users-server.ts) &mdash; shared read-through user cache via `memoize()` / `fetch()`
104
+ - [`clustered-rate-limit-server.ts`](./examples/clustered-rate-limit-server.ts) &mdash; fixed-window rate limiting via atomic `incr()`
105
+ - [`clustered-session-server.ts`](./examples/clustered-session-server.ts) &mdash; shared session storage via `set()` / `get()` / `delete()`
106
+ - [`clustered-idempotency-server.ts`](./examples/clustered-idempotency-server.ts) &mdash; idempotent job intake via `setIfAbsent()`
107
+ - [`clustered-compressed-documents-server.ts`](./examples/clustered-compressed-documents-server.ts) &mdash; compressed document caching via `wrap()`
108
+ - [`clustered-multilayer-redis-server.ts`](./examples/clustered-multilayer-redis-server.ts) &mdash; clustered LRU as L1 in front of Redis as L2, with cluster-wide single-flight on cold keys
109
+
110
+ ## How it works
111
+
112
+ `new LRUCacheClustered(...)` branches at construction:
113
+
114
+ - **In the primary** (`cluster.isPrimary === true`), the instance owns and operates on the in-process `LRUCache` for its namespace directly &mdash; no IPC, no allocation per call.
115
+ - **In a worker**, every operation becomes a typed IPC request to the primary; the returned Promise resolves with the response.
116
+
117
+ Instances in different workers that share a `namespace` operate on the same primary-side cache. Those instances should agree on cache options (`max`, `ttl`, `allowStale`, ...): reusing a namespace with conflicting options throws rather than silently keeping whichever process initialized it first.
118
+
119
+ > **Initialization semantics.** In a worker, `new LRUCacheClustered(...)` eagerly sends the `init` message, but `cache.ready` is ordering-only and intentionally swallows init failure. Use `await cache.healthCheck()` or `await LRUCacheClustered.getInstance(...)` when startup should fail fast if the primary cannot register the namespace.
120
+
121
+ ## Performance profile
122
+
123
+ - **Primary mode** &mdash; operations dispatch directly to the local `lru-cache` instance, bypassing the IPC machinery entirely (no message build, no request-ID allocation, no pending-response bookkeeping).
124
+ - **Worker mode** &mdash; every cache operation is an IPC round trip through the primary.
125
+ - **Hot misses** &mdash; `fetch()` and `memoize()` collapse concurrent misses for the same key across workers, so origin work scales with unique keys, not concurrent callers.
126
+ - **Design tradeoff** &mdash; pick this package when cross-worker sharing and single-copy memory matter more than per-call latency; pick plain per-process `lru-cache` when your hottest path cannot afford the IPC hop.
127
+
128
+ ## Options
129
+
130
+ The serializable subset of [`lru-cache`](https://github.com/isaacs/node-lru-cache) constructor options passes through (`max`, `maxSize`, `maxEntrySize`, `ttl`, `allowStale`, `updateAgeOnGet`, `updateAgeOnHas`, `noDeleteOnStaleGet`, `ttlAutopurge`). Plus:
131
+
132
+ | Option | Type | Default | Description |
133
+ | ----------- | ----------------------- | ----------- | ------------------------------------------------------------------------------------------------------------- |
134
+ | `namespace` | `string` | `'default'` | Logical name. Instances sharing a namespace share state on the primary. |
135
+ | `timeout` | `number` | `100` | Worker IPC timeout in ms. |
136
+ | `failsafe` | `'resolve' \| 'reject'` | `'resolve'` | On worker IPC timeout: `'resolve'` resolves with `undefined`; `'reject'` rejects with `Error('IPC timeout')`. |
137
+
138
+ Function-valued `lru-cache` options such as `dispose`, `disposeAfter`, `sizeCalculation`, or `fetchMethod` do not cross IPC and are not supported by this wrapper.
139
+
140
+ > **`failsafe: 'resolve'` caveat.** On timeout, `'resolve'` returns `undefined` for _every_ op, regardless of declared return type. For `get` / `peek` that is natural; for `has` / `set` / `delete` / `incr` / `decr` / `size` it can surprise callers (`undefined + 1 === NaN`). Use `'reject'` if typed-shape correctness on timeout matters.
141
+
142
+ > **Size-bounded caches.** When you use `maxSize` or `maxEntrySize`, provide `size` on every write path (`set`, `setIfAbsent`, `mSet`, `fetch`, `memoize`, and the first `incr` / `decr` for a counter key). `sizeCalculation` does not cross IPC, so the primary cannot infer it for you.
143
+
144
+ > **Fail-fast startup.** `LRUCacheClustered.getInstance()` and `cache.healthCheck()` always reject if the primary cannot answer, regardless of `failsafe`, so you can use them as hard startup checks.
145
+
146
+ > **Key/value contract.** Like `lru-cache`, keys and values must be non-nullish. Passing `null` or `undefined` rejects instead of relying on ambiguous cache semantics.
147
+
148
+ ## API
149
+
150
+ ### Static
151
+
152
+ | Method | Description |
153
+ | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
154
+ | `LRUCacheClustered.bootstrap()` | Installs the primary-side cluster listener immediately. Useful when you want an explicit bootstrap call instead of relying on module import side effects. |
155
+ | `LRUCacheClustered.getInstance(options)` | Async factory. In a worker, awaits the init message so the primary has registered the namespace before returning. Preferred when worker startup should fail fast on init errors. |
156
+ | `LRUCacheClustered.getAllCaches()` | Returns the `Map<namespace, LRUCache>` registry. **Primary only** &mdash; throws in workers. |
157
+
158
+ ### Core
159
+
160
+ | Method | Returns | Notes |
161
+ | ------------------------------------------ | ------------------------- | --------------------------------------------------------- |
162
+ | `get(key)` | `Promise<V \| undefined>` | |
163
+ | `set(key, value, { ttl?, size? })` | `Promise<boolean>` | |
164
+ | `setIfAbsent(key, value, { ttl?, size? })` | `Promise<boolean>` | Atomic on the primary. `false` if the key already exists. |
165
+ | `delete(key)` | `Promise<boolean>` | |
166
+ | `has(key)` | `Promise<boolean>` | |
167
+ | `peek(key)` | `Promise<V \| undefined>` | Does not update LRU position. |
168
+ | `clear()` | `Promise<void>` | |
169
+
170
+ ### Multi
171
+
172
+ | Method | Returns | Notes |
173
+ | -------------------------------- | --------------------------------- | ------------------------------------------------------------------------------------- |
174
+ | `mGet(keys)` | `Promise<Map<K, V \| undefined>>` | |
175
+ | `mSet(entries, { ttl?, size? })` | `Promise<void>` | `entries: Iterable<[K, V] \| [K, V, { ttl?, size? }]>`; outer opts apply as defaults. |
176
+ | `mDelete(keys)` | `Promise<void>` | |
177
+
178
+ ### Enumeration
179
+
180
+ | Method | Returns | Notes |
181
+ | -------------------------- | ------------------------------- | --------------------------------------------------------------- |
182
+ | `keys()` | `Promise<K[]>` | MRU first. |
183
+ | `values()` | `Promise<V[]>` | MRU first. |
184
+ | `entries()` | `Promise<[K, V][]>` | MRU first. |
185
+ | `[Symbol.asyncIterator]()` | `AsyncIterableIterator<[K, V]>` | `for await (const [k, v] of cache)`. Materializes the full set. |
186
+ | `dump()` | `Promise<[K, Entry][]>` | Serializable snapshot. |
187
+ | `load(entries)` | `Promise<void>` | Restores from a `dump()`, preserving per-entry TTL metadata. |
188
+ | `size()` | `Promise<number>` | |
189
+
190
+ ### Counters and cache-aside
191
+
192
+ | Method | Returns | Notes |
193
+ | ---------------------------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------ |
194
+ | `incr(key, amount?, { ttl?, size? })` | `Promise<number>` | Atomic on the primary. `ttl` is set on the **first** write only; later increments do not reset it (rate limiters). |
195
+ | `decr(key, amount?, { ttl?, size? })` | `Promise<number>` | Same. |
196
+ | `fetch(key, fetcher, { ttl?, size?, forceRefresh })` | `Promise<V>` | Cache-aside with cluster-wide single-flight semantics. See [Single-flight semantics](#single-flight-semantics). |
197
+ | `memoize(cache, fn, keyFn, opts?)` | `(args) => Promise<V>` | Top-level helper. Single-flight via `cache.fetch()`. See [`memoize` helper](#memoize-helper). |
198
+
199
+ ### Lifecycle, metrics, tunables
200
+
201
+ | Method | Returns | Notes |
202
+ | ---------------------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
203
+ | `getRemainingTTL(key)` | `Promise<number>` | ms until expiry. `Infinity` for keys with no TTL; `0` for missing keys. |
204
+ | `purgeStale()` | `Promise<boolean>` | Removes expired entries. |
205
+ | `healthCheck()` | `Promise<void>` | Verifies that the primary can resolve the namespace and answer requests. |
206
+ | `stats()` | `Promise<Stats>` | `{ hits, misses, sets, deletes, evictions, size, namespace }`. |
207
+ | `destroy()` | `Promise<boolean>` | Removes the namespace cache, stats, and primary-side coordination state. Later use of the same instance recreates it with the original options. |
208
+ | `getCache()` | `LRUCache \| undefined` | Underlying `lru-cache` for this namespace. **Primary only**. |
209
+ | `ready` | `Promise<void>` | Resolves once worker init has been dispatched. Useful for ordering only; use `getInstance()` if init failures should reject. |
210
+ | `max(value?)` | `Promise<number>` | Getter and setter. Setter preserves entries and remaining TTL metadata. |
211
+ | `ttl(value?)` | `Promise<number>` | Getter and setter. |
212
+ | `allowStale(value?)` | `Promise<boolean>` | Getter and setter. |
213
+
214
+ ## `wrap` &mdash; codec / compression
215
+
216
+ `wrap(cache, codec)` returns a typed view where values pass through an `encode` / `decode` pair on the way in and out. Use it for compression (gzip, brotli), serialization (MessagePack), or any custom symmetric transform. The library stays codec-agnostic &mdash; bring your own.
217
+
218
+ ```ts
219
+ import { gzipSync, gunzipSync } from 'node:zlib';
220
+ import { LRUCacheClustered, wrap } from '@0xdoublesharp/lru-cache-clustered';
221
+
222
+ // Encode to a string (base64 here) so the wire format is Buffer-safe in workers.
223
+ // See the Buffer caveat below.
224
+ const inner = new LRUCacheClustered<string, string>({ namespace: 'big-blobs', max: 1000 });
225
+
226
+ const cache = wrap(inner, {
227
+ encode: (v: unknown) => gzipSync(Buffer.from(JSON.stringify(v), 'utf8')).toString('base64'),
228
+ decode: (raw: string) => JSON.parse(gunzipSync(Buffer.from(raw, 'base64')).toString('utf8')),
229
+ });
230
+
231
+ await cache.set('user:42', { id: 42, name: 'ada' });
232
+ await cache.get('user:42'); // decoded back to { id: 42, name: 'ada' }
233
+ ```
234
+
235
+ `encode` and `decode` may be sync or async. The wrapped surface covers value-touching ops (`get`, `set`, `setIfAbsent`, `peek`, `mGet`, `mSet`, `values`, `entries`, async iteration, `fetch`) plus the lifecycle and metric pass-throughs (`has`, `delete`, `keys`, `size`, `clear`, `destroy`, `healthCheck`, `purgeStale`, `getRemainingTTL`, `stats`).
236
+
237
+ `incr` / `decr` and `dump` / `load` are not wrapped &mdash; they speak in numbers or the raw stored form. Reach them via `wrapped.cache` if you need them.
238
+
239
+ > **Buffer-typed values.** Cluster IPC serializes through JSON, which does not preserve `Buffer`. If a codec stores `Buffer` directly, in worker mode the decoded side will receive `{ type: 'Buffer', data: number[] }` and most binary APIs will reject it. Encode to a string (base64, hex) &mdash; or rehydrate inside `decode` &mdash; when the wrapped cache is read from workers. Primary-only use is unaffected.
240
+
241
+ ## `memoize` helper
242
+
243
+ Cache-aside in one line. Concurrent calls for the same key coordinate through `cache.fetch()` so only one caller does the underlying work at a time.
244
+
245
+ ```ts
246
+ import { LRUCacheClustered, memoize } from '@0xdoublesharp/lru-cache-clustered';
247
+
248
+ const cache = new LRUCacheClustered<string, User>({ namespace: 'users', ttl: 60_000 });
249
+
250
+ const getUser = memoize(
251
+ cache,
252
+ (id: string) => fetchUserFromDB(id),
253
+ (id) => `user:${id}`,
254
+ { ttl: 60_000 },
255
+ );
256
+
257
+ await getUser('42'); // first call: hits DB
258
+ await getUser('42'); // second call: cached
259
+ ```
260
+
261
+ ### Single-flight semantics
262
+
263
+ Both `memoize()` and `cache.fetch()` coordinate through the primary so concurrent misses for the same key collapse to one in-flight fetch across instances and workers.
264
+
265
+ Passing `forceRefresh: true` skips both the cache lookup and any in-flight claim and starts a fresh leader fetch. Concurrent callers without `forceRefresh` still wait on whichever fetch is in flight and reuse its result.
266
+
267
+ The cache `timeout` option only bounds each worker IPC request. It does not cancel user fetcher work after a worker owns the primary-side single-flight lock, so production fetchers should enforce their own upstream timeout or abort policy.
268
+
269
+ ## Errors
270
+
271
+ **Worker mode.** When a primary-side handler throws, the worker's promise rejects with a reconstructed `Error` carrying the original `name`, `message`, `code`, `stack`, and `cause` chain. The rejected value is always a plain `Error` (subclass identity is not crossed over IPC), but `.name`, `.code`, and `.cause` are intact, so logging and cause-chain walking work. Errors travel as `{ name, message, code?, stack?, cause? }` on the wire.
272
+
273
+ **Primary mode.** No IPC: a thrown `Error` rejects as-is (subclass identity preserved); a thrown non-`Error` value is wrapped in `new Error(String(value))`. For `Error` throws the two modes are observably equivalent.
274
+
275
+ ## Debugging
276
+
277
+ ```sh
278
+ DEBUG=lru-cache-clustered-* node app.js
279
+ ```
280
+
281
+ Available namespaces:
282
+
283
+ - `lru-cache-clustered-primary` &mdash; cache creation, registry events
284
+ - `lru-cache-clustered-messages` &mdash; every request/response over IPC
285
+
286
+ ## Upgrading from 1.x
287
+
288
+ The 2.x line is a TypeScript rewrite on top of `lru-cache@11` with renamed methods and options. See [`docs/migration.md`](./docs/migration.md) for the full method, option, and package mapping, and [`CHANGELOG.md`](./CHANGELOG.md) for the complete 2.0 release notes.
289
+
290
+ ## License
291
+
292
+ MIT &mdash; see [LICENSE](./LICENSE).