tricache 0.5.0 → 0.6.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.
@@ -20,6 +20,7 @@ import { Redis as RedisClient } from 'ioredis';
20
20
  import { pack, unpack } from 'msgpackr';
21
21
  import crypto from 'crypto';
22
22
  import os from 'os';
23
+ import v8 from 'node:v8';
23
24
  import fs from 'fs';
24
25
  import path from 'path';
25
26
 
@@ -112,6 +113,137 @@ class L2CircuitBreaker {
112
113
  // Priority inference — override by passing priority explicitly to get()
113
114
  // ─────────────────────────────────────────────────────────────────────────────
114
115
 
116
+ /**
117
+ * Recursively freezes an object and all its nested properties.
118
+ * Used only when `CacheOptions.frozen` is true (dev/test mode).
119
+ * Already-frozen objects are skipped to avoid redundant traversal.
120
+ */
121
+ function deepFreeze<T>(obj: T): T {
122
+ if (obj === null || typeof obj !== 'object' || Object.isFrozen(obj)) return obj;
123
+ Object.freeze(obj);
124
+ for (const v of Object.values(obj as object)) deepFreeze(v);
125
+ return obj;
126
+ }
127
+
128
+ // ─── Adaptive TTL latency tracker ────────────────────────────────────────────
129
+
130
+ /**
131
+ * Lightweight per-key fetch-latency ring buffer.
132
+ *
133
+ * Each key gets a `Float64Array` of `samples` slots written in round-robin
134
+ * order. A separate `{ head, count }` object tracks the write pointer and
135
+ * how many slots have been filled so far. Once a key has ≥ 5 samples the
136
+ * p95 percentile can be read back with `.p95(key)`.
137
+ *
138
+ * Total memory per key: 8 × samples bytes (Float64Array) + one small object.
139
+ * With defaults (32 samples, 5 000 keys): ~1.3 MB worst-case.
140
+ *
141
+ * Key eviction: the internal Map preserves insertion order. When `maxKeys`
142
+ * is reached the oldest-inserted key is removed before the new one is added —
143
+ * no extra LRU bookkeeping required.
144
+ */
145
+ /** Per-key metadata stored alongside each ring buffer. */
146
+ interface LatencyMeta {
147
+ head: number; // ring-buffer write pointer
148
+ count: number; // filled slots (≤ samples)
149
+ p95: number; // cached p95 value (valid when !dirty && count ≥ 5)
150
+ dirty: boolean; // true when a new sample was written since last p95 computation
151
+ }
152
+
153
+ class LatencyTracker {
154
+ private readonly samples: number;
155
+ private readonly maxKeys: number;
156
+ private readonly bufs = new Map<string, Float64Array>();
157
+ private readonly meta = new Map<string, LatencyMeta>();
158
+ /** Shared sort buffer — safe to reuse because JS is single-threaded. */
159
+ private readonly scratch: Float64Array;
160
+
161
+ constructor(samples: number, maxKeys: number) {
162
+ this.samples = samples;
163
+ this.maxKeys = maxKeys;
164
+ this.scratch = new Float64Array(samples);
165
+ }
166
+
167
+ record(key: string, deltaMs: number): void {
168
+ let buf = this.bufs.get(key);
169
+ let m = this.meta.get(key);
170
+ if (buf === undefined) {
171
+ if (this.bufs.size >= this.maxKeys) {
172
+ // Evict oldest key (Map insertion order)
173
+ const oldest = this.bufs.keys().next().value as string;
174
+ this.bufs.delete(oldest);
175
+ this.meta.delete(oldest);
176
+ }
177
+ buf = new Float64Array(this.samples);
178
+ m = { head: 0, count: 0, p95: 0, dirty: false };
179
+ this.bufs.set(key, buf);
180
+ this.meta.set(key, m);
181
+ }
182
+ buf[m!.head] = deltaMs;
183
+ m!.head = (m!.head + 1) % this.samples;
184
+ if (m!.count < this.samples) m!.count++;
185
+ m!.dirty = true; // new sample → cached p95 is stale
186
+ }
187
+
188
+ /**
189
+ * Recomputes the p95 for the given key into `m.p95` and clears `m.dirty`.
190
+ * Uses the shared scratch buffer — no heap allocation.
191
+ */
192
+ private _computeP95(buf: Float64Array, m: LatencyMeta): void {
193
+ const n = m.count;
194
+ this.scratch.set(buf.subarray(0, n));
195
+ const view = this.scratch.subarray(0, n);
196
+ view.sort(); // TypedArray numeric sort — no comparator needed
197
+ m.p95 = view[Math.ceil(n * 0.95) - 1];
198
+ m.dirty = false;
199
+ }
200
+
201
+ /**
202
+ * Returns the p95 fetch latency for `key` in milliseconds, or `null` when
203
+ * fewer than 5 samples have been collected (not enough data yet).
204
+ * Uses a dirty-flag cache — sort only runs when a new sample was recorded.
205
+ */
206
+ p95(key: string): number | null {
207
+ const buf = this.bufs.get(key);
208
+ const m = this.meta.get(key);
209
+ if (!buf || !m || m.count < 5) return null;
210
+ if (m.dirty) this._computeP95(buf, m);
211
+ return m.p95;
212
+ }
213
+
214
+ get trackedKeys(): number { return this.bufs.size; }
215
+
216
+ /**
217
+ * Top-20 slowest keys by p95, sorted descending.
218
+ * Keys with < 5 samples are excluded (not enough data for a reliable p95).
219
+ *
220
+ * Only dirty keys (those with new samples since the last call) pay the sort
221
+ * cost. Keys whose p95 is already cached are O(1) reads — so repeated
222
+ * metrics() calls with no intervening fetches are essentially free.
223
+ */
224
+ snapshot(
225
+ prefixLen: number,
226
+ multiplierSec: number,
227
+ minMs: number,
228
+ maxMs: number,
229
+ ): Array<{ key: string; p95Ms: number; adaptedTtlSec: number }> {
230
+ const out: Array<{ key: string; p95Ms: number; adaptedTtlSec: number }> = [];
231
+ for (const [key, buf] of this.bufs) {
232
+ const m = this.meta.get(key)!;
233
+ if (m.count < 5) continue;
234
+ if (m.dirty) this._computeP95(buf, m); // sort only when new sample arrived
235
+ const p95 = m.p95;
236
+ const adaptedMs = Math.max(minMs, Math.min(maxMs, Math.round(p95 * multiplierSec * 1_000)));
237
+ out.push({
238
+ key: prefixLen > 0 ? key.slice(prefixLen) : key,
239
+ p95Ms: Math.round(p95),
240
+ adaptedTtlSec: Math.round(adaptedMs / 1_000),
241
+ });
242
+ }
243
+ return out.sort((a, b) => b.p95Ms - a.p95Ms).slice(0, 20);
244
+ }
245
+ }
246
+
115
247
  function inferPriority(cacheKey: string): CachePriority {
116
248
  if (cacheKey.includes('auth:') || cacheKey.includes('session:')) return CachePriority.CRITICAL;
117
249
  if (cacheKey.includes('user:') || cacheKey.includes('org:') || cacheKey.includes('profile:')) return CachePriority.HIGH;
@@ -147,10 +279,18 @@ export class CacheService {
147
279
  staleIfError: number;
148
280
  l2WriteMode: 'read-write' | 'read-only';
149
281
  instanceName: string;
282
+ l1EvictionWatermark: number;
150
283
  ttlJitterFactor: number;
151
284
  tracer: ICacheTracer | undefined;
152
285
  notFoundTtl: number;
153
286
  warmKeys: string | undefined;
287
+ onHit: ((key: string, tier: 'l1' | 'disk' | 'l2') => void) | undefined;
288
+ onMiss: ((key: string) => void) | undefined;
289
+ frozen: boolean;
290
+ adaptiveTtl: boolean;
291
+ adaptiveTtlMinMs: number;
292
+ adaptiveTtlMaxMs: number;
293
+ adaptiveTtlMultiplier: number;
154
294
  };
155
295
  /** Pre-computed once — opts.namespace never changes after construction. */
156
296
  private readonly _namespace: string;
@@ -172,9 +312,11 @@ export class CacheService {
172
312
  private snapshotLoaded = false;
173
313
  private _readyPromise: Promise<void> = Promise.resolve();
174
314
  private cleanupInterval: ReturnType<typeof setInterval> | null = null;
315
+ private diskJanitorInterval: ReturnType<typeof setInterval> | null = null;
175
316
  private oomInterval: ReturnType<typeof setInterval> | null = null;
176
317
  private metricsInterval: ReturnType<typeof setInterval> | null = null;
177
318
  private _shutdownHandler: (() => void) | null = null;
319
+ private latencyTracker: LatencyTracker | null = null;
178
320
  private readonly instanceId: string;
179
321
  private readonly backplaneChannel: string;
180
322
  private subClient: RedisClient | null = null;
@@ -254,10 +396,18 @@ export class CacheService {
254
396
  staleIfError: options.staleIfError ?? 0,
255
397
  l2WriteMode: options.l2WriteMode ?? 'read-write',
256
398
  instanceName: options.instanceName ?? '',
399
+ l1EvictionWatermark: Math.min(Math.max(options.l1EvictionWatermark ?? 0.9, 0), 1),
257
400
  ttlJitterFactor: Math.min(Math.max(options.ttlJitterFactor ?? 0, 0), 1),
258
401
  tracer: options.tracer,
259
402
  notFoundTtl: options.notFoundTtl ?? 0,
260
403
  warmKeys: options.warmKeys,
404
+ onHit: options.onHit,
405
+ onMiss: options.onMiss,
406
+ frozen: options.frozen ?? false,
407
+ adaptiveTtl: options.adaptiveTtl ?? false,
408
+ adaptiveTtlMinMs: (options.adaptiveTtlMin ?? 10) * 1_000,
409
+ adaptiveTtlMaxMs: (options.adaptiveTtlMax ?? 86_400) * 1_000,
410
+ adaptiveTtlMultiplier: options.adaptiveTtlMultiplier ?? 20,
261
411
  };
262
412
 
263
413
  // Circuit breaker for L2 Redis
@@ -265,6 +415,13 @@ export class CacheService {
265
415
  const cbCooldownMs = options.l2CircuitBreakerCooldownMs ?? 30_000;
266
416
  this.cb = new L2CircuitBreaker(cbThreshold, cbCooldownMs);
267
417
 
418
+ // Adaptive TTL latency tracker (only allocated when the feature is enabled)
419
+ if (this.opts.adaptiveTtl) {
420
+ const samples = options.adaptiveTtlSamples ?? 32;
421
+ const maxKeys = options.adaptiveTtlMaxKeys ?? 5_000;
422
+ this.latencyTracker = new LatencyTracker(samples, maxKeys);
423
+ }
424
+
268
425
  // L1.5 disk tier
269
426
  this.disk = new DiskTier({
270
427
  dir: this.opts.diskCacheDir,
@@ -283,7 +440,14 @@ export class CacheService {
283
440
  maxBytes: this.opts.l1MaxBytes,
284
441
  maxEntries: this.opts.l1MaxEntries,
285
442
  categories: this.opts.categoryLimits,
286
- diskSpill: (key: string, entry: SmartCacheEntry) => { void this.disk.save(key, entry as unknown as DiskCacheEntry); },
443
+ evictionWatermark: this.opts.l1EvictionWatermark,
444
+ diskSpill: (key: string, entry: SmartCacheEntry) => {
445
+ // Defer disk.save() entirely to the next event-loop tick so the synchronous
446
+ // preamble inside save() (SHA-256 keyToPath + msgpackr pack) does not block
447
+ // the l1.set() → smartEvict → diskSpill call chain. Mirrors what the
448
+ // backplane handler already does for remote invalidations.
449
+ setImmediate(() => { void this.disk.save(key, entry as unknown as DiskCacheEntry); });
450
+ },
287
451
  onEviction: options.onEviction,
288
452
  logger,
289
453
  });
@@ -299,21 +463,29 @@ export class CacheService {
299
463
  process.once('SIGTERM', this._shutdownHandler);
300
464
  process.once('SIGINT', this._shutdownHandler);
301
465
 
302
- // Periodic cleanup (5 min)
466
+ // Periodic L1 cleanup (5 min): expires stale entries and rebalances frequency counters.
467
+ // Disk cleanup is handled entirely by the janitor below — purgeExpired() is NOT called
468
+ // here to avoid a synchronous O(fileCount) event-loop stall at scale.
303
469
  this.cleanupInterval = setInterval(() => {
304
470
  const cleaned = this.l1.cleanup();
305
- const diskPurged = this.disk.purgeExpired();
306
- if (cleaned > 0 || diskPurged > 0) {
307
- this.logger.debug('Periodic cache cleanup', { cleaned, diskPurged });
308
- }
471
+ if (cleaned > 0) this.logger.debug('Periodic L1 cleanup', { cleaned });
309
472
  }, 5 * 60 * 1000);
310
473
  if (this.cleanupInterval.unref) this.cleanupInterval.unref(); // don't block process exit
311
474
 
475
+ // Disk janitor: sole owner of disk expiry. Scans one of 256 subdirectory buckets per tick
476
+ // (30 s × 256 = 128-min full cycle). Each tick is bounded to one bucket's worth of
477
+ // readFileSync + decrypt + unpack work, capping per-tick event-loop occupancy.
478
+ this.diskJanitorInterval = setInterval(() => {
479
+ const purged = this.disk.purgeNextBucket();
480
+ if (purged > 0) this.logger.debug('Disk janitor tick', { purged });
481
+ }, 30_000);
482
+ if (this.diskJanitorInterval.unref) this.diskJanitorInterval.unref();
483
+
312
484
  // OOM protection: evict coldest L1 entries when heap pressure rises
313
485
  if (this.opts.oomProtection) {
314
486
  this.oomInterval = setInterval(() => {
315
- const mem = process.memoryUsage();
316
- const used = mem.heapUsed / mem.heapTotal;
487
+ const heap = v8.getHeapStatistics();
488
+ const used = heap.used_heap_size / heap.heap_size_limit;
317
489
  if (used >= this.opts.oomHeapThreshold) {
318
490
  const evicted = this.l1.evictPercentage(this.opts.oomEvictPercent);
319
491
  this.counters.oomEvictions++;
@@ -413,10 +585,18 @@ export class CacheService {
413
585
  return Math.round(ttlMs * (1 + (Math.random() * 2 - 1) * j));
414
586
  }
415
587
 
588
+ /** Shared no-op span for the common case where no tracer is configured.
589
+ * Using a singleton avoids allocating a fresh object literal on every get/set/delete call. */
590
+ private static readonly _nullSpan: ICacheSpan = {
591
+ setAttribute() { return this; },
592
+ setStatus() { return this; },
593
+ end() {},
594
+ };
595
+
416
596
  /** Start an OTEL-compatible span if a tracer is configured. Returns a no-op span otherwise. */
417
597
  private _startSpan(name: string): ICacheSpan {
418
598
  if (this.opts.tracer) return this.opts.tracer.startSpan(name);
419
- return { setAttribute() { return this; }, setStatus() { return this; }, end() {} };
599
+ return CacheService._nullSpan;
420
600
  }
421
601
 
422
602
  private initBackplane(): void {
@@ -645,20 +825,39 @@ export class CacheService {
645
825
  refreshAhead?: number; // 0–1: trigger background recompute at this fraction of TTL elapsed
646
826
  xfetchBeta?: number; // > 0: XFetch probabilistic early expiration (uses stored delta)
647
827
  notFoundTtl?: number; // seconds; cache null/undefined results with this TTL instead
828
+ /**
829
+ * Tags to associate with this cache entry when fetchFn populates it on a miss.
830
+ * Tags are registered in the in-process `tagIndex` and (if Redis is enabled) mirrored
831
+ * via `SADD` so that `invalidateTag()` covers disk-spill and multi-instance nodes.
832
+ * On an L1/L2 hit the tags are already registered — this field is a no-op for hits.
833
+ */
834
+ tags?: string[];
648
835
  } = {},
649
836
  ): Promise<T> {
650
837
  const span = this._startSpan('tricache.get');
651
- span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
838
+ if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
652
839
  const k = this.nk(cacheKey); // namespaced key used for all storage
653
840
  this.counters.gets++;
654
841
 
842
+ // Normalize all opts fields to plain locals once. Every opts.XXX read
843
+ // elsewhere in this function would hit a polymorphic IC when callers pass
844
+ // different option shapes: {}, { swr }, { refreshAhead }, { tags }, etc.
845
+ // Reading everything here collapses all downstream accesses to fast
846
+ // monomorphic local-variable reads regardless of call-site variety.
847
+ const optSwr = opts.swr ?? 0;
848
+ const optPriority = opts.priority;
849
+ const optRefreshAhead = opts.refreshAhead;
850
+ const optXfetchBeta = opts.xfetchBeta;
851
+ const optNotFoundTtl = opts.notFoundTtl;
852
+ const optTags = opts.tags;
853
+
655
854
  // L1: in-memory (fastest path)
656
855
  const l1Hit = this.l1.get(k);
657
856
  if (l1Hit !== null) {
658
857
  if (l1Hit.isStale) {
659
- const swrGraceMs = (opts.swr ?? 0) * 1_000;
858
+ const swrGraceMs = optSwr * 1_000;
660
859
  if (swrGraceMs > 0 && !this.revalidating.has(k)) {
661
- const priority = opts.priority ?? inferPriority(cacheKey);
860
+ const priority = optPriority ?? inferPriority(cacheKey);
662
861
  this.revalidating.add(k);
663
862
  void this._revalidate(k, fetchFn, ttlSeconds * 1_000, swrGraceMs, priority);
664
863
  this.counters.swrRevalidations++;
@@ -670,27 +869,32 @@ export class CacheService {
670
869
  this.logger.debug('L1 hit');
671
870
  // Refresh-ahead and XFetch: proactively recompute a fresh entry before it expires.
672
871
  // l1Hit already carries expiresAt/ttlMs/delta — no second Map lookup needed.
673
- if (!this.revalidating.has(k) && (opts.refreshAhead || opts.xfetchBeta)) {
674
- const now = Date.now();
872
+ // Check opts first — pointless work when neither feature is configured.
873
+ // Local aliases for the opts fields already normalised at function entry.
874
+ const ra = optRefreshAhead;
875
+ const xb = optXfetchBeta;
876
+ if (ra || xb) {
877
+ // Reuse the timestamp already captured by l1.get() — avoids a second Date.now() syscall.
878
+ const now = l1Hit.fetchedAt ?? Date.now();
675
879
  const remaining = l1Hit.expiresAt - now;
676
880
  const entryTtl = l1Hit.ttlMs ?? ttlSeconds * 1_000;
677
881
 
678
- const shouldRefreshAhead = opts.refreshAhead != null && opts.refreshAhead > 0
679
- ? remaining <= entryTtl * (1 - opts.refreshAhead)
680
- : false;
882
+ const shouldRefreshAhead = ra ? remaining <= entryTtl * (1 - ra) : false;
681
883
 
682
884
  // XFetch: fire with probability proportional to recompute cost (delta) vs. remaining TTL
683
885
  // Formula: fire when remaining <= delta * beta * -ln(U), U ~ uniform(0,1)
684
- const shouldXFetch = opts.xfetchBeta != null && opts.xfetchBeta > 0 && l1Hit.delta != null
685
- ? remaining <= l1Hit.delta * opts.xfetchBeta * -Math.log(Math.random())
886
+ const shouldXFetch = xb && l1Hit.delta != null
887
+ ? remaining <= l1Hit.delta * xb * -Math.log(Math.random())
686
888
  : false;
687
889
 
688
- if (shouldRefreshAhead || shouldXFetch) {
890
+ // Set.has() deferred to here — the common case (fresh key, threshold not crossed)
891
+ // never pays the ~30 ns lookup cost.
892
+ if ((shouldRefreshAhead || shouldXFetch) && !this.revalidating.has(k)) {
689
893
  // Defer inferPriority until we actually need it — avoids 3× string.includes()
690
894
  // scans on every warm hit when the threshold check is false (the common case).
691
- const priority = opts.priority ?? inferPriority(cacheKey);
895
+ const priority = optPriority ?? inferPriority(cacheKey);
692
896
  this.revalidating.add(k);
693
- void this._revalidate(k, fetchFn, entryTtl, (opts.swr ?? 0) * 1_000, priority);
897
+ void this._revalidate(k, fetchFn, entryTtl, optSwr * 1_000, priority);
694
898
  this.counters.swrRevalidations++;
695
899
  this.logger.debug(
696
900
  shouldXFetch ? 'XFetch: proactive background recompute' : 'Refresh-ahead: proactive background recompute',
@@ -700,13 +904,15 @@ export class CacheService {
700
904
  }
701
905
  }
702
906
  this.counters.l1Hits++;
907
+ this.opts.onHit?.(cacheKey, 'l1');
908
+ if (this.opts.frozen) deepFreeze(l1Hit.value);
703
909
  span.setAttribute('cache.hit', 'l1').end();
704
910
  return l1Hit.value as T;
705
911
  }
706
912
 
707
913
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
708
- const swrGraceMs = (opts.swr ?? 0) * 1_000;
709
- const priority = opts.priority ?? inferPriority(cacheKey);
914
+ const swrGraceMs = optSwr * 1_000;
915
+ const priority = optPriority ?? inferPriority(cacheKey);
710
916
 
711
917
  // L2: Redis (distributed, production-only by default)
712
918
  if (!this._redisDisabled) {
@@ -719,6 +925,7 @@ export class CacheService {
719
925
  const parsed = JSON.parse(decrypted) as T;
720
926
  this.l1.set(k, parsed, ttlMs, priority);
721
927
  this.counters.l2Hits++;
928
+ this.opts.onHit?.(cacheKey, 'l2');
722
929
  this.logger.debug('L2 hit (Redis)', { cacheKey });
723
930
  span.setAttribute('cache.hit', 'l2').end();
724
931
  return parsed;
@@ -740,6 +947,7 @@ export class CacheService {
740
947
  const l1Check = this.l1.get(k);
741
948
  if (l1Check !== null) {
742
949
  this.counters.diskHits++;
950
+ this.opts.onHit?.(cacheKey, 'disk');
743
951
  this.logger.debug('L1.5 hit (disk → L1)', { cacheKey });
744
952
  span.setAttribute('cache.hit', 'disk').end();
745
953
  return l1Check.value as T;
@@ -748,6 +956,7 @@ export class CacheService {
748
956
  }
749
957
 
750
958
  span.setAttribute('cache.hit', 'miss');
959
+ this.opts.onMiss?.(cacheKey);
751
960
 
752
961
  // Cache MISS: thundering-herd prevention
753
962
  const existing = this.inflight.get(k);
@@ -766,13 +975,29 @@ export class CacheService {
766
975
  const delta = Date.now() - fetchStart;
767
976
 
768
977
  // Negative caching: null/undefined results get their own (shorter) TTL
769
- const notFoundTtlMs = (opts.notFoundTtl ?? this.opts.notFoundTtl) * 1_000;
770
- const effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
978
+ const notFoundTtlMs = (optNotFoundTtl ?? this.opts.notFoundTtl) * 1_000;
979
+ let effectiveTtl = (data == null && notFoundTtlMs > 0) ? notFoundTtlMs : ttlMs;
980
+
981
+ // Adaptive TTL: record this fetch duration and override the caller-supplied
982
+ // TTL once ≥ 5 samples are available for the key.
983
+ // Skipped for negative-cache (null/undefined) results — those use notFoundTtl.
984
+ if (this.latencyTracker && data != null) {
985
+ this.latencyTracker.record(k, delta);
986
+ const p95 = this.latencyTracker.p95(k);
987
+ if (p95 !== null) {
988
+ const adaptedMs = Math.round(p95 * this.opts.adaptiveTtlMultiplier * 1_000);
989
+ effectiveTtl = Math.max(
990
+ this.opts.adaptiveTtlMinMs,
991
+ Math.min(this.opts.adaptiveTtlMaxMs, adaptedMs),
992
+ );
993
+ }
994
+ }
771
995
 
772
996
  const staleAt = swrGraceMs > 0 ? Date.now() + effectiveTtl : undefined;
773
997
  const storeTtl = swrGraceMs > 0 ? effectiveTtl + swrGraceMs : effectiveTtl;
774
998
 
775
999
  this.l1.set(k, data, storeTtl, priority, staleAt, delta);
1000
+ if (optTags?.length) await this._registerTags(k, optTags, Math.ceil(effectiveTtl / 1_000));
776
1001
 
777
1002
  if (!this._redisDisabled) {
778
1003
  try {
@@ -813,6 +1038,10 @@ export class CacheService {
813
1038
  const data = await fetchFn();
814
1039
  const delta = Date.now() - fetchStart;
815
1040
  const staleAt = Date.now() + ttlMs;
1041
+
1042
+ // Keep the latency tracker current during SWR background revalidations too
1043
+ if (this.latencyTracker && data != null) this.latencyTracker.record(cacheKey, delta);
1044
+
816
1045
  this.l1.set(cacheKey, data, ttlMs + swrGraceMs, priority, staleAt, delta);
817
1046
 
818
1047
  if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
@@ -844,35 +1073,14 @@ export class CacheService {
844
1073
  /** Explicitly write a value into L1 (+ L2 in production). */
845
1074
  async set<T>(cacheKey: string, data: T, ttlSeconds = 300, priority?: CachePriority, opts?: { tags?: string[]; dependsOn?: string[] }): Promise<void> {
846
1075
  const span = this._startSpan('tricache.set');
847
- span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
1076
+ if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
848
1077
  const ttlMs = this._jitterTtl(ttlSeconds * 1_000);
849
1078
  const p = priority ?? inferPriority(cacheKey);
850
1079
  const k = this.nk(cacheKey);
851
1080
  this.counters.sets++;
852
1081
  this.l1.set(k, data, ttlMs, p);
853
1082
 
854
- // Register tags in the in-process index (+ Redis SADD)
855
- if (opts?.tags?.length) {
856
- for (const tag of opts.tags) {
857
- const tagKey = this.nk(`_tag_:${tag}`);
858
- let members = this.tagIndex.get(tagKey);
859
- if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
860
- members.add(k);
861
- }
862
- if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
863
- try {
864
- const client = await this.getRedis();
865
- const pl = client.pipeline();
866
- for (const tag of opts.tags) {
867
- const tagKey = this.nk(`_tag_:${tag}`);
868
- pl.sadd(tagKey, k);
869
- pl.expire(tagKey, ttlSeconds + 3_600);
870
- }
871
- await pl.exec();
872
- this.cb.onSuccess();
873
- } catch { this.cb.onFailure(); /* tags are best-effort */ }
874
- }
875
- }
1083
+ if (opts?.tags?.length) await this._registerTags(k, opts.tags, ttlSeconds);
876
1084
 
877
1085
  // Register dependency patterns: when any key matching a pattern is deleted,
878
1086
  // this key (k) is automatically cascaded.
@@ -902,6 +1110,32 @@ export class CacheService {
902
1110
  span.end();
903
1111
  }
904
1112
 
1113
+ /**
1114
+ * Register tags for a cache key in the in-process index and (if Redis is enabled) in
1115
+ * the Redis SADD index. Tags are best-effort — a Redis failure does not throw.
1116
+ */
1117
+ private async _registerTags(k: string, tags: string[], ttlSeconds: number): Promise<void> {
1118
+ for (const tag of tags) {
1119
+ const tagKey = this.nk(`_tag_:${tag}`);
1120
+ let members = this.tagIndex.get(tagKey);
1121
+ if (!members) { members = new Set(); this.tagIndex.set(tagKey, members); }
1122
+ members.add(k);
1123
+ }
1124
+ if (!this._redisDisabled && this.opts.l2WriteMode === 'read-write') {
1125
+ try {
1126
+ const client = await this.getRedis();
1127
+ const pl = client.pipeline();
1128
+ for (const tag of tags) {
1129
+ const tagKey = this.nk(`_tag_:${tag}`);
1130
+ pl.sadd(tagKey, k);
1131
+ pl.expire(tagKey, ttlSeconds + 3_600);
1132
+ }
1133
+ await pl.exec();
1134
+ this.cb.onSuccess();
1135
+ } catch { this.cb.onFailure(); /* tags are best-effort */ }
1136
+ }
1137
+ }
1138
+
905
1139
  /**
906
1140
  * Delete one key or a glob pattern (supports `*` wildcard).
907
1141
  *
@@ -911,7 +1145,7 @@ export class CacheService {
911
1145
  */
912
1146
  async delete(cacheKey: string): Promise<void> {
913
1147
  const span = this._startSpan('tricache.delete');
914
- span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
1148
+ if (this.opts.tracer) span.setAttribute('cache.key_prefix', cacheKey.split(':')[0]);
915
1149
  const isPattern = cacheKey.includes('*');
916
1150
  const k = this.nk(cacheKey);
917
1151
  this.counters.deletes++;
@@ -920,7 +1154,13 @@ export class CacheService {
920
1154
  this.l1.deletePattern(k);
921
1155
  } else {
922
1156
  this.l1.delete(k);
923
- this.disk.delete(k);
1157
+ // Defer the synchronous SHA-256 hash + fs syscalls to the next event-loop tick so
1158
+ // the caller's await resolves without blocking. Matches what the backplane handler
1159
+ // already does for remote invalidations: setImmediate(() => this.disk.delete(msg.key)).
1160
+ // A re-get in the narrow window before the deferred call fires would get an L1 miss
1161
+ // and promote the disk entry back — acceptable for a cache (same trade-off the backplane
1162
+ // path already accepts).
1163
+ setImmediate(() => this.disk.delete(k));
924
1164
  // Cascade: invalidate any key that declared it depends on this exact key's pattern
925
1165
  this._cascadeDependencies(k);
926
1166
  // Clean up: remove k from all dependency registrations (it is gone)
@@ -1100,6 +1340,34 @@ export class CacheService {
1100
1340
  }
1101
1341
  }
1102
1342
 
1343
+ /**
1344
+ * High-throughput bulk scan over all live L1 entries.
1345
+ *
1346
+ * Compared with `entries()` this avoids generator frame overhead, per-entry
1347
+ * `[key, value]` tuple allocation, and the `key.slice()` allocation when the
1348
+ * caller uses the `offset` parameter instead of pre-slicing.
1349
+ *
1350
+ * ```typescript
1351
+ * // Zero extra string allocations — use rawKey + offset directly:
1352
+ * cache.scan((rawKey, value, offset) => {
1353
+ * const key = rawKey.slice(offset); // allocate only if needed
1354
+ * sync(key, value as User);
1355
+ * });
1356
+ * ```
1357
+ *
1358
+ * @param fn Called once per live L1 entry.
1359
+ * `rawKey` — key with namespace prefix still attached.
1360
+ * `value` — deserialized cached value.
1361
+ * `offset` — `rawKey.slice(offset)` gives the bare key without namespace.
1362
+ */
1363
+ scan<T = unknown>(fn: (rawKey: string, value: T, offset: number) => void): void {
1364
+ const prefixLen = this._namespace ? this._namespace.length + 1 : 0;
1365
+ this.l1.scan((key, entry, pfx) => {
1366
+ const value = (entry.value !== undefined ? entry.value : entry.data) as T;
1367
+ fn(key, value, pfx);
1368
+ }, prefixLen);
1369
+ }
1370
+
1103
1371
  /**
1104
1372
  * Extend the TTL of a key in L1 (and fire-and-forget EXPIRE in Redis) without fetching.
1105
1373
  * Returns `false` if the key is absent or already expired.
@@ -1240,7 +1508,7 @@ export class CacheService {
1240
1508
  * const loaded = await cache.warmFromL2('org:*');
1241
1509
  * console.log(`Warmed ${loaded} keys from Redis`);
1242
1510
  */
1243
- async warmFromL2(pattern: string): Promise<number> {
1511
+ async warmFromL2(pattern: string, opts?: { priority?: CachePriority }): Promise<number> {
1244
1512
  if (this._redisDisabled) return 0;
1245
1513
  try {
1246
1514
  const client = await this.getRedis();
@@ -1277,8 +1545,8 @@ export class CacheService {
1277
1545
  // Use a 10-minute TTL as a reasonable default; the real TTL is not
1278
1546
  // returned by GET (use PTTL to be precise, but that doubles round-trips).
1279
1547
  const remainingMs = 10 * 60 * 1_000;
1280
- this.l1.set(matchedKeys[i], parsed, remainingMs, inferPriority(matchedKeys[i]));
1281
- loaded++;
1548
+ this.l1.set(matchedKeys[i], parsed, remainingMs, opts?.priority ?? inferPriority(matchedKeys[i]));
1549
+ loaded++;;
1282
1550
  } catch { /* skip malformed entries */ }
1283
1551
  }
1284
1552
  void now; // suppress unused warning
@@ -1329,6 +1597,61 @@ export class CacheService {
1329
1597
  }
1330
1598
  }
1331
1599
 
1600
+ /**
1601
+ * Invalidate all keys associated with any of the given tags in a single operation.
1602
+ * Combines multiple `invalidateTag()` calls into one Redis pipeline round-trip,
1603
+ * reducing latency when invalidating several related tags together.
1604
+ *
1605
+ * Note: Redis pipelines are batched, not atomic. All L1/disk deletes happen
1606
+ * synchronously before the Redis round-trip.
1607
+ *
1608
+ * @example
1609
+ * // Instead of three serial round-trips:
1610
+ * await cache.invalidateTags(['case:acme', 'org:acme', 'ai-chat:acme']);
1611
+ */
1612
+ async invalidateTags(tags: string[]): Promise<void> {
1613
+ if (tags.length === 0) return;
1614
+ if (tags.length === 1) { await this.invalidateTag(tags[0]); return; }
1615
+
1616
+ // In-process: collect all member keys across all tags and remove from L1 + disk
1617
+ const tagKeys: string[] = [];
1618
+ const allMembers = new Set<string>();
1619
+ for (const tag of tags) {
1620
+ const tagKey = this.nk(`_tag_:${tag}`);
1621
+ tagKeys.push(tagKey);
1622
+ const members = this.tagIndex.get(tagKey) ?? new Set<string>();
1623
+ for (const k of members) allMembers.add(k);
1624
+ this.tagIndex.delete(tagKey);
1625
+ }
1626
+ for (const k of allMembers) {
1627
+ this.l1.delete(k);
1628
+ this.disk.delete(k);
1629
+ }
1630
+
1631
+ if (!this._redisDisabled) {
1632
+ try {
1633
+ const client = await this.getRedis();
1634
+ // Single round-trip: pipeline SMEMBERS for all tag keys
1635
+ const pl = client.pipeline();
1636
+ for (const tagKey of tagKeys) pl.smembers(tagKey);
1637
+ const smResults = await pl.exec() as Array<[Error | null, string[] | null]>;
1638
+
1639
+ // Merge Redis members into the master delete set
1640
+ const toDelete: string[] = [...allMembers];
1641
+ for (const [err, redisMembers] of smResults) {
1642
+ if (!err && redisMembers) {
1643
+ for (const k of redisMembers) { if (!allMembers.has(k)) toDelete.push(k); }
1644
+ }
1645
+ }
1646
+ // Single DEL for all member keys + tag keys
1647
+ const keysToRemove = [...toDelete, ...tagKeys];
1648
+ if (keysToRemove.length > 0) await client.del(...keysToRemove);
1649
+ } catch (err) {
1650
+ this.logger.debug('invalidateTags: Redis unavailable', { tags, error: (err as Error).message });
1651
+ }
1652
+ }
1653
+ }
1654
+
1332
1655
  /**
1333
1656
  * Measure L1 / disk / Redis latency.
1334
1657
  * Useful for health checks and dashboards.
@@ -1565,6 +1888,18 @@ export class CacheService {
1565
1888
  maxBytes: this.opts.l1MaxBytes,
1566
1889
  },
1567
1890
  disk: this.disk.stats,
1891
+ ...(this.latencyTracker && {
1892
+ adaptiveTtl: {
1893
+ enabled: true as const,
1894
+ trackedKeys: this.latencyTracker.trackedKeys,
1895
+ slowestKeys: this.latencyTracker.snapshot(
1896
+ this._namespace ? this._namespace.length + 1 : 0, // strip "namespace:" prefix
1897
+ this.opts.adaptiveTtlMultiplier,
1898
+ this.opts.adaptiveTtlMinMs,
1899
+ this.opts.adaptiveTtlMaxMs,
1900
+ ),
1901
+ },
1902
+ }),
1568
1903
  };
1569
1904
  }
1570
1905
 
@@ -1633,9 +1968,10 @@ export class CacheService {
1633
1968
 
1634
1969
  /** Close Redis connections and stop all background timers. */
1635
1970
  async destroy(): Promise<void> {
1636
- if (this.cleanupInterval) clearInterval(this.cleanupInterval);
1637
- if (this.oomInterval) clearInterval(this.oomInterval);
1638
- if (this.metricsInterval) clearInterval(this.metricsInterval);
1971
+ if (this.cleanupInterval) clearInterval(this.cleanupInterval);
1972
+ if (this.diskJanitorInterval) clearInterval(this.diskJanitorInterval);
1973
+ if (this.oomInterval) clearInterval(this.oomInterval);
1974
+ if (this.metricsInterval) clearInterval(this.metricsInterval);
1639
1975
  if (this._shutdownHandler) {
1640
1976
  process.off('SIGTERM', this._shutdownHandler);
1641
1977
  process.off('SIGINT', this._shutdownHandler);
@@ -1649,6 +1985,7 @@ export class CacheService {
1649
1985
  try { await this.redis.disconnect(); } catch { /* ok */ }
1650
1986
  this.redis = null;
1651
1987
  }
1988
+ this.disk.close();
1652
1989
  }
1653
1990
 
1654
1991
  }