tricache 0.2.0 → 0.3.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
@@ -19,7 +19,8 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
19
19
 
20
20
  | Feature | Detail |
21
21
  |---|---|
22
- | **Adaptive eviction** | LFU × LRU × priority score; reservoir-sampled O(1) hot path; category limits prevent any prefix monopolising RAM |
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
24
  | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
24
25
  | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
25
26
  | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
@@ -28,6 +29,11 @@ tricache is an extremely fast three-tier Node.js cache library. It serves warm r
28
29
  | **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
29
30
  | **Tag-based invalidation** | Tag entries on write; `invalidateTag('catalog')` evicts all matching entries from L1, disk, and Redis atomically |
30
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 |
31
37
  | **OOM guard** | Polls `heapUsed/heapTotal` on a timer; emergency-evicts coldest L1 entries before the process crashes |
32
38
  | **Cold-start snapshot** | L1 serialised to disk on `SIGTERM`/`SIGINT`, reloaded on next startup — warm cache, cold process |
33
39
  | **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest; zero-downtime key rotation via `previousEncryptionKey` |
@@ -96,6 +102,19 @@ const [userA, userB] = await cache.mget(
96
102
  300,
97
103
  );
98
104
 
105
+ // Batch write
106
+ await cache.mset({
107
+ [`user:${userIdA}`]: { value: userA, ttl: 300 },
108
+ [`user:${userIdB}`]: { value: userB, ttl: 300 },
109
+ });
110
+
111
+ // Batch delete
112
+ await cache.mdel([`user:${userIdA}`, `user:${userIdB}`]);
113
+
114
+ // Warm L1 from Redis at startup
115
+ const loaded = await cache.warmFromL2('user:*');
116
+ console.log(`Pre-warmed ${loaded} user entries`);
117
+
99
118
  // Tag entries for group invalidation
100
119
  await cache.set(`product:${id}`, product, 300, undefined, { tags: ['catalog'] });
101
120
  await cache.invalidateTag('catalog'); // evict all catalog entries
@@ -180,6 +199,24 @@ CacheService.create({
180
199
  // reason: 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual'
181
200
  onEviction: (key, reason) => metrics.increment(`cache.eviction.${reason}`),
182
201
 
202
+ // ── TTL jitter ────────────────────────────────────────────────────────
203
+ // Multiply each TTL by a random factor in [1-j, 1+j] to spread expiry.
204
+ // Prevents mass-expiry stampedes ("thundering cliff").
205
+ // Range [0, 1]; default 0 (no jitter).
206
+ ttlJitterFactor: 0.15, // ± 15 % spread
207
+
208
+ // ── OpenTelemetry tracer ──────────────────────────────────────────────
209
+ // Pass any @opentelemetry/api-compatible tracer. No peer dependency.
210
+ // Spans: 'tricache.get' | 'tricache.set' | 'tricache.delete'
211
+ // Attributes: cache.key_prefix, cache.hit ('l1'|'disk'|'l2'|'miss')
212
+ tracer: trace.getTracer('my-app'),
213
+
214
+ // ── L2 circuit breaker ────────────────────────────────────────────────
215
+ // Opens after N consecutive Redis errors; probes after cooldown ms.
216
+ // State visible in cache.metrics().l2CircuitBreaker.state
217
+ l2CircuitBreakerThreshold: 5, // default
218
+ l2CircuitBreakerCooldownMs: 30_000, // default
219
+
183
220
  // ── Prometheus instance label ─────────────────────────────────────────
184
221
  // Adds an `instance` label to every metric in toPrometheusText().
185
222
  instanceName: 'api-us-east-1',
@@ -261,6 +298,35 @@ const [userA, userB] = await cache.mget(
261
298
  );
262
299
  ```
263
300
 
301
+ ### `cache.mset<T>(entries)` → `Promise<void>`
302
+
303
+ Write multiple entries in a single call. Each entry accepts `value`, `ttl`, `priority`, and `tags`.
304
+
305
+ ```typescript
306
+ await cache.mset({
307
+ 'user:1': { value: alice, ttl: 300, priority: CachePriority.HIGH, tags: ['users'] },
308
+ 'user:2': { value: bob, ttl: 300 },
309
+ });
310
+ ```
311
+
312
+ ### `cache.mdel(keys)` → `Promise<void>`
313
+
314
+ Delete multiple keys in a single call. No-op for keys that do not exist.
315
+
316
+ ```typescript
317
+ await cache.mdel(['user:1', 'user:2', 'user:3']);
318
+ ```
319
+
320
+ ### `cache.warmFromL2(pattern)` → `Promise<number>`
321
+
322
+ 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.
323
+
324
+ ```typescript
325
+ // In your application startup
326
+ const loaded = await cache.warmFromL2('user:*');
327
+ console.log(`Pre-warmed ${loaded} user entries from Redis`);
328
+ ```
329
+
264
330
  ### `cache.has(key)` → `boolean`
265
331
 
266
332
  Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
@@ -371,6 +437,32 @@ process.on('SIGTERM', async () => {
371
437
  });
372
438
  ```
373
439
 
440
+ ### `cache.keys()` → `Generator<string>`
441
+
442
+ Lazily yields the key for every live (non-expired) L1 entry. Namespace prefix is stripped automatically. Uses a dedicated generator that skips intermediate tuple allocation.
443
+
444
+ ```typescript
445
+ for (const key of cache.keys()) console.log(key);
446
+ ```
447
+
448
+ ### `cache.values<T>()` → `Generator<T>`
449
+
450
+ Lazily yields the cached value for every live L1 entry. Returns the live deserialized object (same reference semantics as `get()`). Uses `yield*` delegation — no intermediate generator frame.
451
+
452
+ ```typescript
453
+ for (const session of cache.values<Session>()) evict(session);
454
+ ```
455
+
456
+ ### `cache.entries<T>()` → `Generator<[string, T]>`
457
+
458
+ Lazily yields `[key, value]` pairs for every live L1 entry. Key has namespace prefix stripped.
459
+
460
+ ```typescript
461
+ for (const [key, user] of cache.entries<User>()) sync(key, user);
462
+ ```
463
+
464
+ > **JIT note:** all three generators iterate `SmartMemoryCache.cache` (a single `Map`). V8 maintains per-call-site type feedback; having three generator functions share the same Map means no single one gets the full monomorphic specialization budget. In practice the throughput impact is ≤5 % relative to each running in isolation. See [BENCHMARKS.md](BENCHMARKS.md) for numbers.
465
+
374
466
  ### `cache.destroy()` → `Promise<void>`
375
467
 
376
468
  Closes the Redis connection, unsubscribes the backplane, and stops all background timers.
@@ -520,25 +612,35 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
520
612
 
521
613
  | Operation | Throughput | Latency | Notes |
522
614
  |---|---|---|---|
523
- | `get` — hot hit (8K entries) | **2.65 M/s** | 377 ns | bloom → Map lookup → return cached value |
524
- | `get` — cold miss | **6.77 M/s** | 148 ns | bloom gates → early return |
525
- | `set` — tiny payload | 915 K/s | 1.09 µs | pack() + Map.set + bloom.add |
526
- | `set` — small payload (≈ 512 B) | 562 K/s | 1.78 µs | pack() same unified path, larger payload |
527
- | `set` — large payload (≥ 512 B) | 213.6 K/s | 4.68 µs | pack() larger payload |
528
- | `set` — CRITICAL priority | 489.7 K/s | 2.04 µs | same set path; skipped in eviction sort |
529
- | `delete` — exact key | **4.40 M/s** | 227 ns | Map.delete |
530
- | `deletePattern` — glob wildcard | 7.1 K/s | 141 µs | O(n) Map scan |
615
+ | `get` — hot hit (8K entries) | **2.60 M/s** | 385 ns | bloom → Map lookup → return cached value |
616
+ | `get` — cold miss | **7.07 M/s** | 141 ns | bloom gates → early return |
617
+ | `set` — tiny payload | 899 K/s | 1.11 µs | pack() + Map.set + bloom.add |
618
+ | `set` — small payload (≈ 512 B) | 554 K/s | 1.81 µs | pack() same unified path, larger payload |
619
+ | `set` — large payload (≥ 512 B) | 205.3 K/s | 4.87 µs | pack() larger payload |
620
+ | `set` — CRITICAL priority | 730.1 K/s | 1.37 µs | same set path; skipped in eviction sort |
621
+ | `delete` — exact key | **3.94 M/s** | 254 ns | Map.delete |
622
+ | `deletePattern` — glob wildcard | 7.2 K/s | 138 µs | O(n) Map scan |
623
+ | Count-Min Sketch estimate | **2.97 M/s** | 336 ns | 4 row lookups — called on every `get()` hit and `set()` |
624
+
625
+ **Iterator interface (L1 live entries, 500 entries)**
626
+
627
+ | Method | Throughput | Latency | Notes |
628
+ |---|---|---|---|
629
+ | `cache.keys()` | 34.1 K/s | 29 µs | no `[key,entry]` tuple allocation — +19 % vs v0.2.0 |
630
+ | `cache.values()` | 33.6 K/s | 30 µs | `yield*` delegation — +4 % vs v0.2.0 |
631
+ | `cache.entries()` | 24.5 K/s | 41 µs | `[strippedKey, value]` pairs |
632
+ | raw `Map` iteration (baseline) | 351 K/s | 2.85 µs | no expiry check, no generator overhead |
531
633
 
532
634
  **CacheService (end-to-end)**
533
635
 
534
636
  | Operation | Throughput | Latency | Notes |
535
637
  |---|---|---|---|
536
- | `get` — L1 warm hit | **2.16 M/s** | 462 ns | inflight check → l1.get → return cached value |
537
- | `get` — SWR stale serve | **2.04 M/s** | 491 ns | serves stale; revalidates async |
538
- | `get` — miss + fetchFn | 14.2 K/s | 70 µs | Promise microtask + l1.set |
539
- | `set` | 32.3 K/s | 30.93 µs | l1.set + disk.save (fire-and-forget) |
540
- | `delete` — exact key | 6.5 K/s | 154 µs | l1.delete + disk.delete + backplane |
541
- | `delete` — glob `*` | 781.5 K/s | 1.28 µs | l1.deletePattern O(n) + disk glob |
638
+ | `get` — L1 warm hit | **1.86 M/s** | 539 ns | inflight check → l1.get → return cached value |
639
+ | `get` — SWR stale serve | **796 K/s** | 1.26 µs | serves stale; revalidates async |
640
+ | `get` — miss + fetchFn | 13.7 K/s | 73 µs | Promise microtask + l1.set |
641
+ | `set` | 31.0 K/s | 32 µs | l1.set + disk.save (fire-and-forget) |
642
+ | `delete` — exact key | 7.9 K/s | 126 µs | l1.delete + disk.delete + backplane |
643
+ | `delete` — glob `*` | 687 K/s | 1.46 µs | l1.deletePattern O(n) + disk glob |
542
644
 
543
645
  **Encryption** (IV pool, pre-allocated output buffers)
544
646