tricache 0.6.5 → 0.6.7

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 CHANGED
@@ -9,7 +9,7 @@
9
9
  [![L1 get](https://img.shields.io/badge/L1%20get-2.81%20M%2Fs-brightgreen)](BENCHMARKS.md)
10
10
  [![Thundering herd](https://img.shields.io/badge/thundering%20herd-100%25%20coalesced-brightgreen)](BENCHMARKS.md)
11
11
 
12
- tricache is an extremely fast three-tier Node.js cache library. It serves warm reads at **2.81 million operations per second** from a single thread — over 100× faster than a localhost Redis round-trip and below any network latency floor. When L1 fills, evicted entries spill to a local NVMe disk tier rather than being dropped, keeping hit rates high without unbounded RAM growth. Cache misses that reach L2 (Redis or Valkey) are automatically coalesced: no matter how many concurrent callers miss the same key, `fetchFn` fires exactly once. See the [performance section](#-performance) for full numbers. Stale-While-Revalidate, AES-256-GCM at-rest encryption, pub/sub fleet-wide invalidation, OOM guard, cold-start snapshots, and Prometheus metrics are also supported through optional configuration — with zero required fields to get started.
12
+ tricache is a three-tier Node.js cache library — in-memory (L1), local disk spill, and Redis/Valkey (L2). Warm L1 reads run at 2.81 million operations per second on a single thread (356 ns/op) — well below any network round-trip, including a local Redis call. When L1 fills, evicted entries spill to disk instead of being dropped, keeping hit rates high without unbounded RAM growth. Misses that reach L2 are coalesced across concurrent callers, so a spike of simultaneous requests for the same key triggers exactly one fetchFn call, not one per caller. See the performance section for full numbers. Optional configuration adds Stale-While-Revalidate, at-rest encryption (AES-256-GCM by default), pub/sub fleet-wide invalidation, an OOM guard, cold-start snapshots, and Prometheus metrics — none of it required to get started.
13
13
 
14
14
  <img src="https://raw.githubusercontent.com/Kareem411/TriCache/master/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
15
15
 
@@ -20,7 +20,7 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
20
20
  | Feature | Detail |
21
21
  |---|---|
22
22
  | **Adaptive eviction** | LFU × LRU × priority score + Count-Min Sketch cross-eviction frequency; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
23
- | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **78 % survival rate** in benchmark flood tests |
23
+ | **Count-Min Sketch** | 4 × 512 `Uint16Array` (4 KB) tracks historical access frequency across eviction boundaries — same-priority burst keys cannot displace long-resident entries; **84 % survival rate** in benchmark flood tests |
24
24
  | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
25
25
  | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
26
26
  | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
@@ -243,6 +243,15 @@ CacheService.create({
243
243
  adaptiveTtlMax: 86400, // ceiling: never exceed 24 h (default)
244
244
  adaptiveTtlMultiplier: 20, // p95Ms × 20 = TTL in seconds (default)
245
245
 
246
+ // ── Singleton + rate-limit safety ──────────────────────────────────────
247
+ // strictSingleton: when true, a later create() for an existing namespace
248
+ // whose options differ from the first call THROWS instead of silently
249
+ // returning the existing instance. Guards against conflicting init points.
250
+ strictSingleton: false,
251
+ // failClosed: when true, increment() re-throws on a Redis error instead of
252
+ // failing open (returning 0). Enforces the rate-limit guard during outages.
253
+ failClosed: false,
254
+
246
255
  // ── OpenTelemetry tracer ──────────────────────────────────────────────
247
256
  // Pass any @opentelemetry/api-compatible tracer. No peer dependency.
248
257
  // Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
@@ -310,7 +319,7 @@ CacheService.create({
310
319
 
311
320
  ### `CacheService.create(options?)` → `CacheService`
312
321
 
313
- Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance.
322
+ Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance. When the new options differ from what the existing singleton was built with, this is a **silent no-op by default** (a one-time warning is logged and the `singletonDivergences` metric is incremented). Set `strictSingleton: true` on the first call to instead **throw** on a divergent later call — use this when multiple init points could pass conflicting Redis credentials or TTLs.
314
323
 
315
324
  ### `CacheService.createAsync(optionsOrPromise)` → `Promise<CacheService>`
316
325
 
@@ -334,7 +343,7 @@ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` f
334
343
  |---|---|---|---|
335
344
  | `key` | `string` | — | Cache key |
336
345
  | `fetchFn` | `() => Promise<T>` | — | Called on a miss; result is cached |
337
- | `ttlSeconds` | `number` | `300` | Hard TTL in seconds |
346
+ | `ttlSeconds` | `number` | `300` | Hard TTL in seconds. **When `adaptiveTtl` is enabled, this is only authoritative until ≥ 5 samples are collected for the key — after that the library derives TTL from the p95 fetch latency** (see Adaptive TTL config). Use `opts` or a separate cache instance if you need a hard floor. |
338
347
  | `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
339
348
  | `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
340
349
  | `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
@@ -361,7 +370,7 @@ await cache.delete('org:42'); // org:42:members is evicted too
361
370
 
362
371
  ### `cache.mget<T>(keys, fetchFn, ttl?, priority?)` → `Promise<(T | undefined)[]>`
363
372
 
364
- Batch read. Returns L1-cached values for hot keys; calls `fetchFn` only with the keys that missed. Preserves input ordering.
373
+ Batch read. Checks **all three tiers** for each key — L1 (RAM), then L2 (Redis, in one pipelined `MGET`), then the L1.5 disk spill — and calls `fetchFn` only for keys that miss every tier. Preserves input ordering and counts exactly one hit per key (no double-counting across tiers).
365
374
 
366
375
  `ttl` accepts a **plain number** (uniform TTL) or a **function `(key: string) => number`** (per-key TTL). The function is only called for miss keys — L1 hits are unaffected.
367
376
 
@@ -528,7 +537,9 @@ cache.rebalance();
528
537
 
529
538
  ### `cache.increment(key, ttlSeconds?)` → `Promise<number>`
530
539
 
531
- Redis `INCR` — atomically increments a counter, setting TTL on first write. When Redis is disabled, maintains an in-process counter with the same TTL semantics so rate-limiting works in dev/test.
540
+ Distributed counter. With Redis active, atomically increments via `INCR` and returns the fleet-wide value. **By default it fails OPEN on a Redis error** — it returns `0`, so a caller's `if (count > LIMIT) reject()` guard will NOT reject during an outage. Set `failClosed: true` to re-throw the error instead, enforcing the limit even when Redis is unavailable. Track failures via `cache.metrics().counters.errors`.
541
+
542
+ When Redis is disabled, it maintains an **in-process** counter with the same TTL semantics so dev/test rate-limiting works — but rate-limiting is then per-instance, **not fleet-wide**. A one-time warning is logged the first time this fallback is used.
532
543
 
533
544
  ### `cache.metrics()` → `CacheMetrics`
534
545
 
@@ -652,7 +663,7 @@ CacheService.create({
652
663
 
653
664
  ## 🔐 Encryption
654
665
 
655
- AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Three modes are available via `encryptionMode`:
666
+ AES-256-GCM for L2 (Redis) values, disk spill files, and cold-start snapshots. Four modes are available via `encryptionMode`:
656
667
 
657
668
  | Mode | Key length | Notes |
658
669
  |---|---|---|
@@ -834,10 +845,13 @@ ioredis monitors the current master via the Sentinel topology and transparently
834
845
 
835
846
  ## ⚡ WASM Bloom filter
836
847
 
837
- A 100,000-bit filter with k=7 hash probes:
848
+ A 100,000-bit filter with k=7 hash probes is used when it is large enough for the
849
+ configured `l1MaxEntries`; otherwise a right-sized pure-JS filter is instantiated
850
+ automatically (see `createBloomFilter`). For the default 100K-bit filter:
838
851
 
839
- - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.01%**
840
- - At rated capacity (~18,000 entries) — false-positive rate ≈ **1%**
852
+ - At the default `l1MaxEntries: 2,000` — false-positive rate ≈ **0.00007%** (m=100,000, k=7)
853
+ - At its rated capacity (~10,400 entries) — false-positive rate ≈ **1%**
854
+ - When `l1MaxEntries` exceeds the WASM filter's ~10,400-entry capacity, a JS filter sized via the optimal formula (m = ⌈–n·ln p / (ln 2)²⌉, k = round(ln 2 · m / n) clamped to [4, 10]) is used instead — no capacity cliff.
841
855
  - The filter rebuilds automatically when stale bits from deleted/expired entries accumulate
842
856
 
843
857
  Mechanics:
@@ -848,6 +862,24 @@ The 562-byte WASM binary is inlined as Base64 — zero filesystem access at runt
848
862
 
849
863
  ---
850
864
 
865
+ ## 🔬 High-Performance Architecture & Memory Hygiene
866
+
867
+ TriCache is engineered for low-latency, high-throughput environments where garbage collection (GC) pauses and main-thread blocking must be minimized. The codebase employs several advanced V8 and hardware-aware optimizations:
868
+
869
+ ### ⚡ Performance & Memory Hygiene
870
+ - **Zero-Allocation Hot Paths:** To eliminate object allocation thrashing on hot L1 reads, TriCache reuses a single, pre-allocated static `_hit` object literal in [src/smart-memory-cache.ts](src/smart-memory-cache.ts) to return cache hits synchronously.
871
+ - **Fast-Path Binary Operations (Uint32Array XOR):** The XOR obfuscation engine in [src/encryption.ts](src/encryption.ts) automatically detects if buffers are 4-byte-aligned. If so, it processes the operation using `Uint32Array` views, allowing the V8 JIT compiler to compile the loop into highly-optimized, 32-bit register-level CPU `XOR` instructions instead of a slow byte-by-byte traversal.
872
+ - **Pre-allocated Eviction Pools:** During L1 eviction, candidate selection avoids generating temporary object literals. The system samples candidates into a pre-allocated `_evictPool` array and mutates their fields in-place, eliminating GC pressure when the cache is under heavy write load.
873
+
874
+ ### 🛡️ Production-First Ergonomics & Resiliency
875
+ - **Next.js HMR Resiliency:** Normal in-memory caches re-instantiate and wipe their state during Next.js Hot Module Replacement (HMR) reloads. TriCache binds its singleton instance to `globalThis` to preserve the L1 cache across hot-reload cycles in server environments.
876
+ - **Graceful Degradation & Fallbacks:**
877
+ - **L2 Circuit Breaker:** Protects your app from cascading failures if Redis gets slow or goes down, automatically failing back to L1/disk and probing Redis health on a cooldown timer.
878
+ - **Dynamic Bloom Filters:** Uses a WebAssembly Bloom filter for fast miss checks, but automatically falls back to a dynamically-sized, memory-optimized pure JS Bloom filter if the cache size exceeds the WebAssembly filter's hardcoded capacity limit.
879
+ - **CPU-Efficient Count-Min Sketch:** Keeps access-frequency history across eviction boundaries in a tight `4 rows × 512 counters` `Uint16Array` (4 KB total). This fits entirely within the CPU's L1d cache, ensuring frequency updates are essentially free.
880
+
881
+ ---
882
+
851
883
  ## 📊 Performance
852
884
 
853
885
  Measured on a single Node.js thread (no `await` on synchronous paths):
@@ -858,12 +890,12 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
858
890
  |---|---|---|---|
859
891
  | `get` — hot hit (8K entries) | **2.81 M/s** | 356 ns | bloom → Map lookup → return cached value |
860
892
  | `get` — cold miss | **7.14 M/s** | 140 ns | bloom gates → early return |
861
- | `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
862
- | `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
863
- | `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
864
- | `set` — CRITICAL priority | 730.1 K/s | 1.37 µs | same set path; skipped in eviction sort |
893
+ | `set` — tiny payload | 1.06 M/s | 944 ns | pack() + Map.set + bloom.add |
894
+ | `set` — small payload (< 512 B) | 574.1 K/s | 1.74 µs | pack() same unified path, larger payload |
895
+ | `set` — large payload (≥ 512 B) | 228.6 K/s | 4.37 µs | pack() larger payload |
896
+ | `set` — CRITICAL priority | 843.6 K/s | 1.19 µs | same set path; skipped in eviction sort |
865
897
  | `delete` — exact key | **5.36 M/s** | 186 ns | Map.delete |
866
- | `deletePattern` — glob wildcard | 7.2 K/s | 138 µs | O(n) Map scan |
898
+ | `deletePattern` — glob wildcard | 18.7 K/s | 53.48 µs | O(n) Map scan |
867
899
  | Count-Min Sketch estimate | **3.37 M/s** | 297 ns | 4 row lookups — called on every `get()` hit and `set()` |
868
900
 
869
901
  **Iterator interface (L1 live entries, 500 entries)**
@@ -148,6 +148,20 @@ var CacheEncryption = class {
148
148
  get isEnabled() {
149
149
  return this._key !== null;
150
150
  }
151
+ /**
152
+ * Snapshot the key material needed to spin up an off-main-thread worker pool.
153
+ * Replaces the previously-used `as unknown as { _key, _mode, … }` private-field
154
+ * cast in cache-service.ts — the worker pool reads these via this accessor
155
+ * instead of reaching into underscore-prefixed internals.
156
+ */
157
+ toWorkerInit() {
158
+ return {
159
+ keyBase64: this._key ? this._key.toString("base64") : "",
160
+ mode: this._mode,
161
+ prevKeyBase64: this._prevKey ? this._prevKey.toString("base64") : void 0,
162
+ prevMode: this._prevMode
163
+ };
164
+ }
151
165
  // ── String (Redis) ────────────────────────────────────────────────────────
152
166
  /**
153
167
  * Encrypt a string for Redis storage.
@@ -190,18 +204,18 @@ var CacheEncryption = class {
190
204
  */
191
205
  decrypt(value) {
192
206
  try {
193
- return this._decryptWithKey(value, this._key, this._keyObj, this._mode);
207
+ return this._decryptWithKey(value, this._key, this._keyObj);
194
208
  } catch (primaryErr) {
195
209
  if (this._prevKey) {
196
210
  try {
197
- return this._decryptWithKey(value, this._prevKey, this._prevKeyObj, this._prevMode);
211
+ return this._decryptWithKey(value, this._prevKey, this._prevKeyObj);
198
212
  } catch {
199
213
  }
200
214
  }
201
215
  throw primaryErr;
202
216
  }
203
217
  }
204
- _decryptWithKey(value, key, keyObj, mode) {
218
+ _decryptWithKey(value, key, keyObj) {
205
219
  if (value.startsWith(PREFIX_XOR)) {
206
220
  if (!key) throw new Error("Cannot decrypt: encryption key is not set");
207
221
  const masked = Buffer.from(value.slice(PREFIX_XOR.length), "base64");
@@ -236,8 +250,6 @@ var CacheEncryption = class {
236
250
  const plain = d.update(ct);
237
251
  d.final();
238
252
  return plain.toString("utf8");
239
- void mode;
240
- void key;
241
253
  }
242
254
  // ── Buffer (disk / snapshot) ──────────────────────────────────────────────
243
255
  /** Encrypt a raw Buffer for disk/snapshot. Returns MAGIC | payload when a key is set. */