tricache 0.4.0 → 0.5.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 CHANGED
@@ -6,10 +6,10 @@
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
7
7
  [![Node.js ≥ 22](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](https://nodejs.org)
8
8
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.x%20%7C%206.x-blue)](https://www.typescriptlang.org)
9
- [![L1 get](https://img.shields.io/badge/L1%20get-2.65%20M%2Fs-brightgreen)](BENCHMARKS.md)
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.65 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 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.
13
13
 
14
14
  <img src="https://raw.githubusercontent.com/Kareem411/TriCache/master/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
15
15
 
@@ -48,6 +48,9 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
48
48
  | **XFetch probabilistic early expiry** | Probabilistic background recompute keyed to last fetch duration and `xfetchBeta` — optimal protection against expiry spikes under load |
49
49
  | **`hotKeys(n)`** | Returns top N keys by Count-Min Sketch access frequency with size — no full Map scan |
50
50
  | **`dependsOn` cascade invalidation** | Tag entries with parent keys; deleting a parent automatically evicts all declared dependents from L1 |
51
+ | **`onHit` / `onMiss` callbacks** | Per-operation hit/miss hooks with tier info (`'l1'` \| `'disk'` \| `'l2'`) — no wait for the metrics interval |
52
+ | **`frozen` mode** | Dev-time mutation guard — `Object.freeze()` applied recursively to every L1 hit so accidental mutations throw immediately |
53
+ | **`tags` in `get()` opts** | Attach tags at read time; when `fetchFn` populates the entry on a miss the tags are registered automatically |
51
54
 
52
55
  ---
53
56
 
@@ -121,6 +124,10 @@ await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
121
124
  const loaded = await cache.warmFromL2('user:*');
122
125
  console.log(`Pre-warmed ${loaded} user entries`);
123
126
 
127
+ // Or auto-warm at construction + gate traffic with ready()
128
+ const cache2 = CacheService.create({ warmKeys: 'user:*' });
129
+ await cache2.ready(); // resolves once warm-up completes — ideal for k8s readiness probes
130
+
124
131
  // Atomic set-if-absent — returns true if written, false if key already cached
125
132
  const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
126
133
 
@@ -240,6 +247,12 @@ CacheService.create({
240
247
  // Can be overridden per-call via opts.notFoundTtl in cache.get().
241
248
  notFoundTtl: 30, // seconds; 0 = disabled (default)
242
249
 
250
+ // ── Startup warm-up ───────────────────────────────────────────────────
251
+ // Auto-call warmFromL2(pattern) at construction time.
252
+ // cache.ready() resolves once warm-up finishes — use as a k8s readiness gate.
253
+ // No-op when Redis is disabled or unreachable.
254
+ warmKeys: 'user:*',
255
+
243
256
  // ── Prometheus instance label ─────────────────────────────────────────
244
257
  // Adds an `instance` label to every metric in toPrometheusText().
245
258
  instanceName: 'api-us-east-1',
@@ -252,6 +265,20 @@ CacheService.create({
252
265
  // ── Metrics callback ─────────────────────────────────────────────────
253
266
  metricsIntervalMs: 60_000, // emit every 60 s (default)
254
267
  onMetrics: (m) => myMonitoring.record(m), // optional push callback
268
+
269
+ // ── Per-operation hooks ───────────────────────────────────────────────
270
+ // onHit fires on every L1, disk, or L2 hit with the caller-facing key (no prefix)
271
+ // and the tier that served it. Lower latency than waiting for onMetrics.
272
+ onHit: (key, tier) => cloudwatch.putMetricData({ key, tier }),
273
+
274
+ // onMiss fires when all three tiers are exhausted — before fetchFn is called.
275
+ onMiss: (key) => cloudwatch.putMetricData({ key }),
276
+
277
+ // ── Development mutation guard ────────────────────────────────────────
278
+ // When true, every L1 hit value is deep-frozen before being returned.
279
+ // Mutation attempts throw TypeError immediately in development.
280
+ // Do NOT enable in production — deep-freezing large objects has measurable overhead.
281
+ frozen: process.env.NODE_ENV !== 'production',
255
282
  });
256
283
  ```
257
284
 
@@ -299,6 +326,7 @@ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` f
299
326
  | `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
300
327
  | `opts.xfetchBeta` | `number` | — | XFetch β ≥ 0 — scales probabilistic early recompute by last fetch duration; higher = recompute earlier |
301
328
  | `opts.notFoundTtl` | `number` | — | Per-call TTL in seconds for `null`/`undefined` results (overrides global `notFoundTtl`) |
329
+ | `opts.tags` | `string[]` | — | Tags to register when `fetchFn` populates the entry on a miss; no-op on L1/L2 hits where tags are already registered |
302
330
 
303
331
  ### `cache.set<T>(key, data, ttlSeconds?, priority?, opts?)` → `Promise<void>`
304
332
 
@@ -317,16 +345,26 @@ await cache.set('org:42:members', members, 300, undefined, { dependsOn: ['org:42
317
345
  await cache.delete('org:42'); // org:42:members is evicted too
318
346
  ```
319
347
 
320
- ### `cache.mget<T>(keys, fetchFn, ttlSeconds?, priority?)` → `Promise<(T | undefined)[]>`
348
+ ### `cache.mget<T>(keys, fetchFn, ttl?, priority?)` → `Promise<(T | undefined)[]>`
321
349
 
322
350
  Batch read. Returns L1-cached values for hot keys; calls `fetchFn` only with the keys that missed. Preserves input ordering.
323
351
 
352
+ `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.
353
+
324
354
  ```typescript
355
+ // Uniform TTL
325
356
  const [userA, userB] = await cache.mget(
326
357
  ['user:1', 'user:2'],
327
358
  (missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
328
359
  300,
329
360
  );
361
+
362
+ // Per-key TTL — heterogeneous data in one batch call
363
+ const results = await cache.mget(
364
+ ['user:1', 'config:global', 'feature:flags'],
365
+ fetchFn,
366
+ (key) => key.startsWith('config:') ? 3600 : 300,
367
+ );
330
368
  ```
331
369
 
332
370
  ### `cache.mset<T>(entries)` → `Promise<void>`
@@ -358,6 +396,22 @@ const loaded = await cache.warmFromL2('user:*');
358
396
  console.log(`Pre-warmed ${loaded} user entries from Redis`);
359
397
  ```
360
398
 
399
+ ### `cache.ready()` → `Promise<void>`
400
+
401
+ Returns a Promise that resolves once the cache is fully initialised. Without `warmKeys`, resolves immediately. With `warmKeys`, resolves once the automatic `warmFromL2` call completes.
402
+
403
+ Designed for k8s readiness probes — await before accepting traffic, then never call again:
404
+
405
+ ```typescript
406
+ const cache = CacheService.create({ warmKeys: 'user:*' });
407
+
408
+ // k8s readiness probe endpoint
409
+ app.get('/ready', async (_req, res) => {
410
+ await cache.ready();
411
+ res.sendStatus(200);
412
+ });
413
+ ```
414
+
361
415
  ### `cache.has(key)` → `boolean`
362
416
 
363
417
  Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
@@ -669,52 +723,52 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
669
723
 
670
724
  | Operation | Throughput | Latency | Notes |
671
725
  |---|---|---|---|
672
- | `get` — hot hit (8K entries) | **2.60 M/s** | 385 ns | bloom → Map lookup → return cached value |
673
- | `get` — cold miss | **7.07 M/s** | 141 ns | bloom gates → early return |
726
+ | `get` — hot hit (8K entries) | **2.81 M/s** | 356 ns | bloom → Map lookup → return cached value |
727
+ | `get` — cold miss | **7.14 M/s** | 140 ns | bloom gates → early return |
674
728
  | `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
675
729
  | `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
676
730
  | `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
677
731
  | `set` — CRITICAL priority | 730.1 K/s | 1.37 µs | same set path; skipped in eviction sort |
678
- | `delete` — exact key | **3.94 M/s** | 254 ns | Map.delete |
732
+ | `delete` — exact key | **5.36 M/s** | 186 ns | Map.delete |
679
733
  | `deletePattern` — glob wildcard | 7.2 K/s | 138 µs | O(n) Map scan |
680
- | Count-Min Sketch estimate | **2.97 M/s** | 336 ns | 4 row lookups — called on every `get()` hit and `set()` |
734
+ | Count-Min Sketch estimate | **3.37 M/s** | 297 ns | 4 row lookups — called on every `get()` hit and `set()` |
681
735
 
682
736
  **Iterator interface (L1 live entries, 500 entries)**
683
737
 
684
738
  | Method | Throughput | Latency | Notes |
685
739
  |---|---|---|---|
686
- | `cache.keys()` | 34.1 K/s | 29 µs | no `[key,entry]` tuple allocation — +19 % vs v0.2.0 |
687
- | `cache.values()` | 33.6 K/s | 30 µs | `yield*` delegation — +4 % vs v0.2.0 |
688
- | `cache.entries()` | 24.5 K/s | 41 µs | `[strippedKey, value]` pairs |
689
- | raw `Map` iteration (baseline) | 351 K/s | 2.85 µs | no expiry check, no generator overhead |
740
+ | `cache.keys()` | 26.6 K/s | 37.53 µs | no `[key,entry]` tuple allocation |
741
+ | `cache.values()` | 35.5 K/s | 28.19 µs | `yield*` delegation |
742
+ | `cache.entries()` | 24.0 K/s | 41.73 µs | `[strippedKey, value]` pairs |
743
+ | raw `Map` iteration (baseline) | 277.2 K/s | 3.61 µs | no expiry check, no generator overhead |
690
744
 
691
745
  **CacheService (end-to-end)**
692
746
 
693
747
  | Operation | Throughput | Latency | Notes |
694
748
  |---|---|---|---|
695
- | `get` — L1 warm hit | **1.86 M/s** | 539 ns | inflight check → l1.get → return cached value |
696
- | `get` — SWR stale serve | **796 K/s** | 1.26 µs | serves stale; revalidates async |
749
+ | `get` — L1 warm hit | **2.03 M/s** | 491 ns | inflight check → l1.get → return cached value |
750
+ | `get` — SWR stale serve | **1.78 M/s** | 562 ns | serves stale; revalidates async |
697
751
  | `get` — miss + fetchFn | 13.7 K/s | 73 µs | Promise microtask + l1.set |
698
- | `set` | 31.0 K/s | 32 µs | l1.set + disk.save (fire-and-forget) |
699
- | `delete` — exact key | 7.9 K/s | 126 µs | l1.delete + disk.delete + backplane |
752
+ | `set` | 28.7 K/s | 34.86 µs | l1.set + disk.save (fire-and-forget) |
753
+ | `delete` — exact key | 7.3 K/s | 137.82 µs | l1.delete + disk.delete + backplane |
700
754
  | `delete` — glob `*` | 687 K/s | 1.46 µs | l1.deletePattern O(n) + disk glob |
701
755
 
702
756
  **Encryption** (IV pool, pre-allocated output buffers)
703
757
 
704
758
  | Mode | Payload | Encrypt | Decrypt |
705
759
  |---|---|---|---|
706
- | AES-256-GCM | 64 B | 114 K/s / 8.75 µs | 133 K/s / 7.52 µs |
707
- | AES-256-GCM | 512 B | 70.3 K/s / 14.21 µs | 114 K/s / 8.80 µs |
708
- | AES-256-GCM | 4 KB | 41.7 K/s / 23.99 µs | 43.0 K/s / 23.24 µs |
709
- | AES-128-GCM | 64 B | 127 K/s / 7.89 µs | 145 K/s / 6.91 µs |
710
- | AES-128-GCM | 512 B | 90.8 K/s / 11.01 µs | 132 K/s / 7.59 µs |
711
- | AES-128-GCM | 4 KB | 48.9 K/s / 20.47 µs | 42.9 K/s / 23.32 µs |
712
- | AES-128-CTR | 64 B | 181 K/s / 5.51 µs | 192 K/s / 5.21 µs |
713
- | AES-128-CTR | 512 B | 175 K/s / 5.71 µs | 182 K/s / 5.50 µs |
714
- | AES-128-CTR | 4 KB | 61.8 K/s / 16.18 µs | 54.0 K/s / 18.51 µs |
715
- | XOR _(obfuscation only)_ | 64 B | 2.37 M/s / 422 ns | 2.11 M/s / 475 ns |
716
- | XOR _(obfuscation only)_ | 512 B | 598 K/s / 1.67 µs | 513 K/s / 1.95 µs |
717
- | XOR _(obfuscation only)_ | 4 KB | 82.7 K/s / 12.09 µs | 146 K/s / 6.84 µs |
760
+ | AES-256-GCM | 64 B | 140.4 K/s / 7.12 µs | 155.5 K/s / 6.43 µs |
761
+ | AES-256-GCM | 512 B | 103.1 K/s / 9.70 µs | 142.9 K/s / 6.99 µs |
762
+ | AES-256-GCM | 4 KB | 58.4 K/s / 17.12 µs | 48.0 K/s / 20.84 µs |
763
+ | AES-128-GCM | 64 B | 148.8 K/s / 6.72 µs | 173.0 K/s / 5.78 µs |
764
+ | AES-128-GCM | 512 B | 135.7 K/s / 7.37 µs | 158.8 K/s / 6.30 µs |
765
+ | AES-128-GCM | 4 KB | 70.2 K/s / 14.24 µs | 53.2 K/s / 18.79 µs |
766
+ | AES-128-CTR | 64 B | 187.9 K/s / 5.32 µs | 196.9 K/s / 5.08 µs |
767
+ | AES-128-CTR | 512 B | 183.5 K/s / 5.45 µs | 185.6 K/s / 5.39 µs |
768
+ | AES-128-CTR | 4 KB | 78.4 K/s / 12.75 µs | 71.8 K/s / 13.93 µs |
769
+ | XOR _(obfuscation only)_ | 64 B | 2.43 M/s / 412 ns | 2.10 M/s / 476 ns |
770
+ | XOR _(obfuscation only)_ | 512 B | 665.5 K/s / 1.50 µs | 715.3 K/s / 1.40 µs |
771
+ | XOR _(obfuscation only)_ | 4 KB | 114.5 K/s / 8.73 µs | 77.6 K/s / 12.89 µs |
718
772
 
719
773
  > AES and XOR string-path numbers shown (Redis L2). Buffer path (disk/snapshot) is 5–20% faster — no base64 overhead.
720
774
  > AES-128-GCM is 5–50% faster than AES-256-GCM depending on payload (gap widens at mid-range sizes on AES-NI hardware).