tricache 0.3.0 → 0.4.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/README.md CHANGED
@@ -29,6 +29,11 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
29
29
  | **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
30
30
  | **Tag-based invalidation** | Tag entries on write; `invalidateTag('catalog')` evicts all matching entries from L1, disk, and Redis atomically |
31
31
  | **Batch read** | `mget()` collects L1 hits, calls `fetchFn` only for misses, preserves ordering |
32
+ | **Batch write** | `mset()` / `mdel()` write or delete many keys in a single `Promise.all` call |
33
+ | **TTL jitter** | `ttlJitterFactor` spreads expirations across a configurable ± window — prevents thundering-cliff mass-expiry |
34
+ | **OpenTelemetry spans** | Structural `ICacheTracer` / `ICacheSpan` interfaces — pass any OTEL-compatible tracer; no peer dep required |
35
+ | **L2 circuit breaker** | Suspends Redis after N consecutive failures; auto-probes after cooldown; state visible in `metrics()` |
36
+ | **`warmFromL2(pattern)`** | Scan Redis and pre-populate L1 at startup; returns count loaded; no-op when Redis unavailable |
32
37
  | **OOM guard** | Polls `heapUsed/heapTotal` on a timer; emergency-evicts coldest L1 entries before the process crashes |
33
38
  | **Cold-start snapshot** | L1 serialised to disk on `SIGTERM`/`SIGINT`, reloaded on next startup — warm cache, cold process |
34
39
  | **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest; zero-downtime key rotation via `previousEncryptionKey` |
@@ -37,6 +42,12 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
37
42
  | **Pluggable logger** | Bring your own `pino`, `winston`, etc. |
38
43
  | **L2 read-only mode** | `l2WriteMode: 'read-only'` reads from Redis but skips all writes — canary deploys, read replicas |
39
44
  | **Eviction callback** | `onEviction(key, reason)` fires on every L1 eviction with a typed reason string |
45
+ | **Negative caching (`notFoundTtl`)** | Cache `null`/`undefined` fetchFn results for a configurable TTL — prevents hammering upstream on repeated misses |
46
+ | **`setIfAbsent()`** | Atomic "set if not cached" — L1 `has()` check → Redis `SET NX EX` → L1 set on success; returns `true` if written, `false` if already present |
47
+ | **Refresh-ahead** | Proactively recompute an entry in the background when remaining TTL falls below a configured fraction — zero-latency freshness |
48
+ | **XFetch probabilistic early expiry** | Probabilistic background recompute keyed to last fetch duration and `xfetchBeta` — optimal protection against expiry spikes under load |
49
+ | **`hotKeys(n)`** | Returns top N keys by Count-Min Sketch access frequency with size — no full Map scan |
50
+ | **`dependsOn` cascade invalidation** | Tag entries with parent keys; deleting a parent automatically evicts all declared dependents from L1 |
40
51
 
41
52
  ---
42
53
 
@@ -97,6 +108,30 @@ const [userA, userB] = await cache.mget(
97
108
  300,
98
109
  );
99
110
 
111
+ // Batch write
112
+ await cache.mset({
113
+ [`user:${userIdA}`]: { value: userA, ttl: 300 },
114
+ [`user:${userIdB}`]: { value: userB, ttl: 300 },
115
+ });
116
+
117
+ // Batch delete
118
+ await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
119
+
120
+ // Warm L1 from Redis at startup
121
+ const loaded = await cache.warmFromL2('user:*');
122
+ console.log(`Pre-warmed ${loaded} user entries`);
123
+
124
+ // Atomic set-if-absent — returns true if written, false if key already cached
125
+ const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
126
+
127
+ // Dependency cascade: deleting 'org:42' automatically evicts 'org:42:config'
128
+ await cache.set('org:42:config', config, 300, undefined, { dependsOn: ['org:42'] });
129
+ await cache.delete('org:42'); // also evicts org:42:config
130
+
131
+ // Top 10 hottest keys by Count-Min Sketch frequency
132
+ const hot = cache.hotKeys(10);
133
+ console.log(hot); // [{ key: 'user:1', hits: 842, sizeBytes: 512 }, ...]
134
+
100
135
  // Tag entries for group invalidation
101
136
  await cache.set(`product:${id}`, product, 300, undefined, { tags: ['catalog'] });
102
137
  await cache.invalidateTag('catalog'); // evict all catalog entries
@@ -181,6 +216,30 @@ CacheService.create({
181
216
  // reason: 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual'
182
217
  onEviction: (key, reason) => metrics.increment(`cache.eviction.${reason}`),
183
218
 
219
+ // ── TTL jitter ────────────────────────────────────────────────────────
220
+ // Multiply each TTL by a random factor in [1-j, 1+j] to spread expiry.
221
+ // Prevents mass-expiry stampedes ("thundering cliff").
222
+ // Range [0, 1]; default 0 (no jitter).
223
+ ttlJitterFactor: 0.15, // ± 15 % spread
224
+
225
+ // ── OpenTelemetry tracer ──────────────────────────────────────────────
226
+ // Pass any @opentelemetry/api-compatible tracer. No peer dependency.
227
+ // Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
228
+ // Attributes: cache.key_prefix, cache.hit ('l1'|'disk'|'l2'|'miss')
229
+ tracer: trace.getTracer('my-app'),
230
+
231
+ // ── L2 circuit breaker ────────────────────────────────────────────────
232
+ // Opens after N consecutive Redis errors; probes after cooldown ms.
233
+ // State visible in cache.metrics().l2CircuitBreaker.state
234
+ l2CircuitBreakerThreshold: 5, // default
235
+ l2CircuitBreakerCooldownMs: 30_000, // default
236
+
237
+ // ── Negative caching ──────────────────────────────────────────────────
238
+ // Cache null/undefined fetchFn results for this many seconds globally.
239
+ // Prevents repeated upstream calls for keys that genuinely don't exist.
240
+ // Can be overridden per-call via opts.notFoundTtl in cache.get().
241
+ notFoundTtl: 30, // seconds; 0 = disabled (default)
242
+
184
243
  // ── Prometheus instance label ─────────────────────────────────────────
185
244
  // Adds an `instance` label to every metric in toPrometheusText().
186
245
  instanceName: 'api-us-east-1',
@@ -237,6 +296,9 @@ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` f
237
296
  | `ttlSeconds` | `number` | `300` | Hard TTL in seconds |
238
297
  | `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
239
298
  | `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
299
+ | `opts.refreshAhead` | `number` | — | Fraction `(0, 1]` of TTL — triggers background recompute when `remaining ≤ ttl × (1 - refreshAhead)` |
300
+ | `opts.xfetchBeta` | `number` | — | XFetch β ≥ 0 — scales probabilistic early recompute by last fetch duration; higher = recompute earlier |
301
+ | `opts.notFoundTtl` | `number` | — | Per-call TTL in seconds for `null`/`undefined` results (overrides global `notFoundTtl`) |
240
302
 
241
303
  ### `cache.set<T>(key, data, ttlSeconds?, priority?, opts?)` → `Promise<void>`
242
304
 
@@ -245,9 +307,14 @@ Writes to L1 and (in production) L2. Publishes an invalidation to the backplane.
245
307
  | Parameter | Type | Default | Description |
246
308
  |---|---|---|---|
247
309
  | `opts.tags` | `string[]` | `[]` | Associate tags with this entry for group invalidation |
310
+ | `opts.dependsOn` | `string[]` | `[]` | Parent keys — when any parent is deleted, this entry is automatically evicted from L1 |
248
311
 
249
312
  ```typescript
250
313
  await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'featured'] });
314
+
315
+ // Cascade invalidation: evicting 'org:42' also evicts 'org:42:members'
316
+ await cache.set('org:42:members', members, 300, undefined, { dependsOn: ['org:42'] });
317
+ await cache.delete('org:42'); // org:42:members is evicted too
251
318
  ```
252
319
 
253
320
  ### `cache.mget<T>(keys, fetchFn, ttlSeconds?, priority?)` → `Promise<(T | undefined)[]>`
@@ -262,6 +329,35 @@ const [userA, userB] = await cache.mget(
262
329
  );
263
330
  ```
264
331
 
332
+ ### `cache.mset<T>(entries)` → `Promise<void>`
333
+
334
+ Write multiple entries in a single call. Each entry accepts `value`, `ttl`, `priority`, and `tags`.
335
+
336
+ ```typescript
337
+ await cache.mset({
338
+ 'user:1': { value: alice, ttl: 300, priority: CachePriority.HIGH, tags: ['users'] },
339
+ 'user:2': { value: bob, ttl: 300 },
340
+ });
341
+ ```
342
+
343
+ ### `cache.mdel(keys)` → `Promise<void>`
344
+
345
+ Delete multiple keys in a single call. No-op for keys that do not exist.
346
+
347
+ ```typescript
348
+ await cache.mdel(['user:1', 'user:2', 'user:3']);
349
+ ```
350
+
351
+ ### `cache.warmFromL2(pattern)` → `Promise<number>`
352
+
353
+ Scan Redis for keys matching a glob pattern (e.g. `'user:*'`) and load their values into L1 with a 10-minute TTL. Returns the number of keys loaded. Returns `0` immediately when Redis is disabled or unreachable — safe to call unconditionally at startup.
354
+
355
+ ```typescript
356
+ // In your application startup
357
+ const loaded = await cache.warmFromL2('user:*');
358
+ console.log(`Pre-warmed ${loaded} user entries from Redis`);
359
+ ```
360
+
265
361
  ### `cache.has(key)` → `boolean`
266
362
 
267
363
  Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
@@ -288,6 +384,32 @@ const fresh = cache.getIfFresh<User>('user:123');
288
384
  if (fresh !== null) return fresh; // serve from L1, no network hop
289
385
  ```
290
386
 
387
+ ### `cache.setIfAbsent<T>(key, value, ttlSeconds?)` → `Promise<boolean>`
388
+
389
+ Atomically write `value` only if `key` is not already cached. Checks L1 first, then attempts a Redis `SET NX EX`. Returns `true` if the value was written, `false` if a live entry already existed.
390
+
391
+ Useful for distributed lock-style writes, session initialisation, or any pattern where you must not overwrite an already-cached value.
392
+
393
+ ```typescript
394
+ const written = await cache.setIfAbsent(`session:${id}`, sessionData, 3600);
395
+ if (!written) {
396
+ // session already exists — do not overwrite
397
+ }
398
+ ```
399
+
400
+ ### `cache.hotKeys(n?)` → `Array<{ key: string; hits: number; sizeBytes: number }>`
401
+
402
+ Returns the top `n` live L1 keys ranked by Count-Min Sketch access frequency. Namespace prefix is stripped from each key. Expired entries are excluded. Default `n = 10`.
403
+
404
+ ```typescript
405
+ const hot = cache.hotKeys(5);
406
+ // [
407
+ // { key: 'user:1', hits: 1024, sizeBytes: 512 },
408
+ // { key: 'product:7', hits: 893, sizeBytes: 256 },
409
+ // ...
410
+ // ]
411
+ ```
412
+
291
413
  ### `cache.invalidateTag(tag)` → `Promise<void>`
292
414
 
293
415
  Evict all entries associated with a tag from L1, disk, and Redis.
@@ -547,35 +669,35 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
547
669
 
548
670
  | Operation | Throughput | Latency | Notes |
549
671
  |---|---|---|---|
550
- | `get` — hot hit (8K entries) | **2.19 M/s** | 457 ns | bloom → Map lookup → return cached value |
551
- | `get` — cold miss | **5.81 M/s** | 172 ns | bloom gates → early return |
552
- | `set` — tiny payload | 915 K/s | 1.09 µs | pack() + Map.set + bloom.add |
553
- | `set` — small payload (≈ 512 B) | 562 K/s | 1.78 µs | pack() same unified path, larger payload |
554
- | `set` — large payload (≥ 512 B) | 213.6 K/s | 4.68 µs | pack() larger payload |
555
- | `set` — CRITICAL priority | 489.7 K/s | 2.04 µs | same set path; skipped in eviction sort |
556
- | `delete` — exact key | **4.40 M/s** | 227 ns | Map.delete |
557
- | `deletePattern` — glob wildcard | 7.1 K/s | 141 µs | O(n) Map scan |
558
- | Count-Min Sketch estimate | **3.04 M/s** | 329 ns | 4 row lookups — called on every `get()` hit and `set()` |
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 |
674
+ | `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
675
+ | `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
676
+ | `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
677
+ | `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 |
679
+ | `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()` |
559
681
 
560
682
  **Iterator interface (L1 live entries, 500 entries)**
561
683
 
562
684
  | Method | Throughput | Latency | Notes |
563
685
  |---|---|---|---|
564
- | `cache.keys()` | 34.5 K/s | 29 µs | no `[key,entry]` tuple allocation — +19 % vs v0.2.0 |
565
- | `cache.values()` | 35 K/s | 29 µs | `yield*` delegation — +4 % vs v0.2.0 |
566
- | `cache.entries()` | 28 K/s | 35 µs | `[strippedKey, value]` pairs |
567
- | raw `Map` iteration (baseline) | 338 K/s | 3 µs | no expiry check, no generator overhead |
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 |
568
690
 
569
691
  **CacheService (end-to-end)**
570
692
 
571
693
  | Operation | Throughput | Latency | Notes |
572
694
  |---|---|---|---|
573
- | `get` — L1 warm hit | **2.16 M/s** | 462 ns | inflight check → l1.get → return cached value |
574
- | `get` — SWR stale serve | **2.04 M/s** | 491 ns | serves stale; revalidates async |
575
- | `get` — miss + fetchFn | 14.2 K/s | 70 µs | Promise microtask + l1.set |
576
- | `set` | 32.3 K/s | 30.93 µs | l1.set + disk.save (fire-and-forget) |
577
- | `delete` — exact key | 6.5 K/s | 154 µs | l1.delete + disk.delete + backplane |
578
- | `delete` — glob `*` | 781.5 K/s | 1.28 µs | l1.deletePattern O(n) + disk glob |
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 |
697
+ | `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 |
700
+ | `delete` — glob `*` | 687 K/s | 1.46 µs | l1.deletePattern O(n) + disk glob |
579
701
 
580
702
  **Encryption** (IV pool, pre-allocated output buffers)
581
703