tricache 0.1.0 → 0.3.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
@@ -1,30 +1,17 @@
1
- # tricache ⚡
1
+ # TriCache
2
2
 
3
- [![CI](https://github.com/Kareem411/tricache/actions/workflows/ci.yml/badge.svg)](https://github.com/Kareem411/tricache/actions/workflows/ci.yml)
3
+ [![CI](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml/badge.svg)](https://github.com/Kareem411/TriCache/actions/workflows/ci.yml)
4
4
  [![npm version](https://img.shields.io/npm/v/tricache.svg)](https://www.npmjs.com/package/tricache)
5
+ [![npm downloads](https://img.shields.io/npm/dm/tricache.svg)](https://www.npmjs.com/package/tricache)
5
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
6
7
  [![Node.js ≥ 22](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](https://nodejs.org)
7
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)
10
+ [![Thundering herd](https://img.shields.io/badge/thundering%20herd-100%25%20coalesced-brightgreen)](BENCHMARKS.md)
8
11
 
9
- **Stop paying for slow.** tricache is a three-tier Node.js cache that serves **1.4 million reads/second** from RAM, spills cold entries to NVMe instead of dropping them on the floor, and fans out invalidations across your entire fleet in real time — all behind a single `npm install`.
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.
10
13
 
11
- Built for production from day one: adaptive LFU×LRU×priority eviction, AES-256-GCM at-rest encryption, WASM Bloom filter, Stale-While-Revalidate, thundering-herd prevention, OOM guard, cold-start snapshots, and Prometheus metrics. Zero required configuration.
12
-
13
- ```
14
- Request
15
- │
16
- ▼
17
- L1 — SmartMemoryCache (in-process RAM, 200 MB default, adaptive LFU×LRU×priority eviction)
18
- │ miss
19
- ▼
20
- L1.5 — DiskTier (NVMe spill, 500 MB default, 2–100 µs, holds evicted L1 entries)
21
- │ miss
22
- ▼
23
- L2 — Redis / Valkey (distributed, production-only by default, pub/sub invalidation)
24
- │ miss
25
- ▼
26
- fetchFn() (your database / API call — fires exactly once per key under load)
27
- ```
14
+ <img src="https://raw.githubusercontent.com/Kareem411/TriCache/master/public/SmartMemoryCache_DiskTier.jpeg" width="600" alt="tricache architecture" />
28
15
 
29
16
  ---
30
17
 
@@ -32,18 +19,24 @@ fetchFn() (your database / API call — fires exactly once per key
32
19
 
33
20
  | Feature | Detail |
34
21
  |---|---|
35
- | **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 |
36
24
  | **WASM Bloom filter** | 562-byte binary inlined as Base64 — O(k=7) guaranteed-miss detection, no filesystem access, pure-JS fallback |
37
25
  | **msgpackr serialization** | All entries packed with msgpackr — uniform binary format, no JSON at any payload size |
38
26
  | **Stale-While-Revalidate** | Serve stale instantly, revalidate in background — zero added latency on cache hit |
27
+ | **Stale-if-error** | Extend a stale entry's TTL when SWR revalidation fails — no errors served during upstream outages |
39
28
  | **Thundering-herd prevention** | Inflight `Promise` registry — only one `fetchFn` call per key regardless of concurrency |
40
29
  | **Pub/sub invalidation backplane** | Redis pub/sub channel propagates deletes across all instances in real time |
30
+ | **Tag-based invalidation** | Tag entries on write; `invalidateTag('catalog')` evicts all matching entries from L1, disk, and Redis atomically |
31
+ | **Batch read** | `mget()` collects L1 hits, calls `fetchFn` only for misses, preserves ordering |
41
32
  | **OOM guard** | Polls `heapUsed/heapTotal` on a timer; emergency-evicts coldest L1 entries before the process crashes |
42
33
  | **Cold-start snapshot** | L1 serialised to disk on `SIGTERM`/`SIGINT`, reloaded on next startup — warm cache, cold process |
43
- | **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest |
34
+ | **AES-256-GCM encryption** | L2 (Redis) values, disk spill files, and snapshots encrypted at rest; zero-downtime key rotation via `previousEncryptionKey` |
44
35
  | **Prometheus metrics** | `cache.metrics()` + `CacheService.toPrometheusText()` — drop into any `/metrics` endpoint |
45
- | **Distributed counter** | `cache.increment()` backed by Redis `INCR` for distributed rate limiting |
36
+ | **Distributed counter** | `cache.increment()` backed by Redis `INCR` for distributed rate limiting; in-process fallback when Redis is disabled |
46
37
  | **Pluggable logger** | Bring your own `pino`, `winston`, etc. |
38
+ | **L2 read-only mode** | `l2WriteMode: 'read-only'` reads from Redis but skips all writes — canary deploys, read replicas |
39
+ | **Eviction callback** | `onEviction(key, reason)` fires on every L1 eviction with a typed reason string |
47
40
 
48
41
  ---
49
42
 
@@ -94,6 +87,23 @@ const dashboard = await cache.get(
94
87
  // Distributed rate-limiting counter
95
88
  const hits = await cache.increment(`ratelimit:${ip}`, 60 /* TTL seconds */);
96
89
 
90
+ // Check if a key is cached (fast, no fetch)
91
+ const isCached = cache.has(`user:${userId}`);
92
+
93
+ // Batch read
94
+ const [userA, userB] = await cache.mget(
95
+ [`user:${userIdA}`, `user:${userIdB}`],
96
+ (missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
97
+ 300,
98
+ );
99
+
100
+ // Tag entries for group invalidation
101
+ await cache.set(`product:${id}`, product, 300, undefined, { tags: ['catalog'] });
102
+ await cache.invalidateTag('catalog'); // evict all catalog entries
103
+
104
+ // Health check with tier latencies
105
+ const { l1, disk, l2 } = await cache.ping();
106
+
97
107
  // Prometheus metrics
98
108
  const snap = cache.metrics();
99
109
  console.log(CacheService.toPrometheusText(snap));
@@ -152,6 +162,29 @@ CacheService.create({
152
162
  // node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
153
163
  encryptionKey: process.env.CACHE_ENCRYPTION_KEY,
154
164
 
165
+ // Zero-downtime key rotation — remove after all old entries have expired
166
+ previousEncryptionKey: process.env.PREV_ENCRYPTION_KEY,
167
+ previousEncryptionMode: 'aes-256-gcm', // defaults to current encryptionMode
168
+
169
+ // ── L2 write mode ────────────────────────────────────────────────────
170
+ // 'read-write' (default) — reads and writes to Redis
171
+ // 'read-only' — reads from Redis, skips all writes (canary / replica)
172
+ l2WriteMode: 'read-write',
173
+
174
+ // ── Stale-if-error ───────────────────────────────────────────────────
175
+ // Extra seconds to extend a stale L1 entry's expiry when a SWR fetchFn fails.
176
+ // Prevents serving errors while the upstream is temporarily down.
177
+ staleIfError: 300, // keep stale for 5 more minutes on revalidation error
178
+
179
+ // ── Eviction callback ────────────────────────────────────────────────
180
+ // Called synchronously whenever L1 evicts a key.
181
+ // reason: 'capacity' | 'category' | 'rebalance' | 'oom' | 'ttl' | 'manual'
182
+ onEviction: (key, reason) => metrics.increment(`cache.eviction.${reason}`),
183
+
184
+ // ── Prometheus instance label ─────────────────────────────────────────
185
+ // Adds an `instance` label to every metric in toPrometheusText().
186
+ instanceName: 'api-us-east-1',
187
+
155
188
  // ── Cold-start snapshot ──────────────────────────────────────────────
156
189
  snapshotPath: '/tmp/my-app-cache-snapshot.msgpack',
157
190
  snapshotMaxAgeMs: 2 * 60 * 60 * 1000, // 2 hours (default)
@@ -179,6 +212,14 @@ CacheService.create({
179
212
 
180
213
  Returns the process-level singleton. Options are only applied on the **first** call per namespace — subsequent calls return the existing instance.
181
214
 
215
+ ### `CacheService.createAsync(optionsOrPromise)` → `Promise<CacheService>`
216
+
217
+ Async factory that resolves a `Promise<CacheOptions>` before constructing the singleton. Useful when config is fetched from a secret store at startup.
218
+
219
+ ```typescript
220
+ const cache = await CacheService.createAsync(fetchSecretsFromVault());
221
+ ```
222
+
182
223
  ### `CacheService.reset(options?)` → `CacheService`
183
224
 
184
225
  Destroys the existing singleton and creates a fresh one. Useful in tests.
@@ -187,6 +228,8 @@ Destroys the existing singleton and creates a fresh one. Useful in tests.
187
228
 
188
229
  Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` fires at most once per key regardless of concurrency.
189
230
 
231
+ > **Reference semantics:** on an L1 hit, the returned value is the live JS object stored in the entry — not a deep copy. Mutating it will corrupt the cached entry. Deep-clone at the call site if you need an independent copy.
232
+
190
233
  | Parameter | Type | Default | Description |
191
234
  |---|---|---|---|
192
235
  | `key` | `string` | — | Cache key |
@@ -195,29 +238,121 @@ Get from cache or call `fetchFn` on a miss. The inflight map ensures `fetchFn` f
195
238
  | `opts.swr` | `number` | `0` | Stale-While-Revalidate grace seconds |
196
239
  | `opts.priority` | `CachePriority` | auto-inferred | Eviction priority override |
197
240
 
198
- ### `cache.set<T>(key, data, ttlSeconds?, priority?)` → `Promise<void>`
241
+ ### `cache.set<T>(key, data, ttlSeconds?, priority?, opts?)` → `Promise<void>`
199
242
 
200
243
  Writes to L1 and (in production) L2. Publishes an invalidation to the backplane.
201
244
 
245
+ | Parameter | Type | Default | Description |
246
+ |---|---|---|---|
247
+ | `opts.tags` | `string[]` | `[]` | Associate tags with this entry for group invalidation |
248
+
249
+ ```typescript
250
+ await cache.set('product:1', data, 60, undefined, { tags: ['catalog', 'featured'] });
251
+ ```
252
+
253
+ ### `cache.mget<T>(keys, fetchFn, ttlSeconds?, priority?)` → `Promise<(T | undefined)[]>`
254
+
255
+ Batch read. Returns L1-cached values for hot keys; calls `fetchFn` only with the keys that missed. Preserves input ordering.
256
+
257
+ ```typescript
258
+ const [userA, userB] = await cache.mget(
259
+ ['user:1', 'user:2'],
260
+ (missKeys) => db.users.findByIds(missKeys).then(rowsToMap),
261
+ 300,
262
+ );
263
+ ```
264
+
265
+ ### `cache.has(key)` → `boolean`
266
+
267
+ Return `true` if the key exists in L1 and has not expired. Bloom-filter fast-path — no fetch, no disk or Redis round-trip.
268
+
269
+ ### `cache.ttl(key)` → `number | null`
270
+
271
+ Return the remaining TTL in **seconds** for a key currently held in L1. Returns `null` if the key is absent or expired. Does not fetch or consume the value.
272
+
273
+ ```typescript
274
+ const remaining = cache.ttl('user:123'); // e.g. 247 (seconds left)
275
+ if (remaining !== null && remaining < 30) await cache.touch('user:123', 300);
276
+ ```
277
+
278
+ ### `cache.touch(key, newTtlSeconds)` → `Promise<boolean>`
279
+
280
+ Extend the TTL of a key in L1 (and fire-and-forget `EXPIRE` in Redis) without reading or re-fetching its value. Returns `false` if the key is absent or already expired.
281
+
282
+ ### `cache.getIfFresh<T>(key)` → `T | null`
283
+
284
+ Return the L1 value only if it is **fresh** (not yet in the SWR grace window). Returns `null` when absent, expired, or stale — without triggering a revalidation.
285
+
286
+ ```typescript
287
+ const fresh = cache.getIfFresh<User>('user:123');
288
+ if (fresh !== null) return fresh; // serve from L1, no network hop
289
+ ```
290
+
291
+ ### `cache.invalidateTag(tag)` → `Promise<void>`
292
+
293
+ Evict all entries associated with a tag from L1, disk, and Redis.
294
+
295
+ ```typescript
296
+ await cache.set('product:1', data, 60, undefined, { tags: ['catalog'] });
297
+ await cache.set('product:2', data, 60, undefined, { tags: ['catalog'] });
298
+ await cache.invalidateTag('catalog'); // evicts both entries
299
+ ```
300
+
301
+ ### `cache.ping()` → `Promise<CachePingResult>`
302
+
303
+ Measure L1 / disk / Redis latency in milliseconds. Returns `{ l1, disk, l2 }` — `l2` is `null` when Redis is disabled. Suitable for health-check endpoints.
304
+
305
+ ```typescript
306
+ app.get('/health', async (_req, res) => {
307
+ const { l1, disk, l2 } = await cache.ping();
308
+ res.json({ status: 'ok', latencyMs: { l1, disk, l2 } });
309
+ });
310
+ ```
311
+
312
+ ### `cache.drainToL2()` → `Promise<number>`
313
+
314
+ Pipeline all live L1 entries to Redis in a single round-trip. Returns the number of keys written. Useful for warming a new Redis node or zero-downtime failover.
315
+
202
316
  ### `cache.delete(key)` → `Promise<void>`
203
317
 
204
318
  Deletes one exact key or a glob pattern (`user:abc:*`). Propagates to disk, Redis, and all backplane peers.
205
319
 
320
+ ### `cache.clear(prefix?)` → `Promise<void>`
321
+
322
+ Flush all entries, or only those whose key starts with `prefix`. Propagates to disk and Redis.
323
+
324
+ ```typescript
325
+ await cache.clear(); // flush everything
326
+ await cache.clear('session:'); // flush only session keys
327
+ ```
328
+
329
+ ### `cache.rebalance()` → `void`
330
+
331
+ Evict L1 entries that now violate the current category or global capacity limits. Useful when `categoryLimits` are tightened after startup — normally, existing entries are not re-evaluated until they expire naturally.
332
+
333
+ ```typescript
334
+ // Tighten analytics limit at runtime, then immediately enforce it
335
+ cache.options.categoryLimits['analytics:'].maxEntries = 50;
336
+ cache.rebalance();
337
+ ```
338
+
206
339
  ### `cache.increment(key, ttlSeconds?)` → `Promise<number>`
207
340
 
208
- Redis `INCR` — atomically increments a counter, setting TTL on first write. Returns `0` when Redis is disabled (safe for dev).
341
+ 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.
209
342
 
210
343
  ### `cache.metrics()` → `CacheMetrics`
211
344
 
212
345
  Returns a full metrics snapshot including hit rates, bloom filter stats, backplane counters, OOM eviction history, and tier sizes.
213
346
 
214
- ### `CacheService.toPrometheusText(metrics, prefix?)` → `string`
347
+ ### `CacheService.toPrometheusText(metrics, prefix?, instanceName?)` → `string`
215
348
 
216
- Converts a `CacheMetrics` snapshot to Prometheus text exposition format. Paste into your `/metrics` route.
349
+ Converts a `CacheMetrics` snapshot to Prometheus text exposition format. Pass `instanceName` to add an `instance` label alongside `namespace`.
217
350
 
218
351
  ```typescript
219
352
  app.get('/metrics', (_req, res) => {
220
- res.type('text/plain').send(CacheService.toPrometheusText(cache.metrics()));
353
+ res.type('text/plain').send(
354
+ CacheService.toPrometheusText(cache.metrics(), 'tricache', 'api-us-east-1'),
355
+ );
221
356
  });
222
357
  ```
223
358
 
@@ -225,9 +360,43 @@ app.get('/metrics', (_req, res) => {
225
360
 
226
361
  Lightweight L1 and disk stats without the full metrics breakdown.
227
362
 
228
- ### `cache.writeSnapshot()` / `cache.loadSnapshot()`
363
+ ### `cache.writeSnapshot(altPath?)` / `cache.loadSnapshot()`
364
+
365
+ Manual snapshot control. Called automatically on `SIGTERM`/`SIGINT` — only needed when you manage shutdown yourself. `writeSnapshot()` accepts an optional path to write to an alternate location without touching the configured default snapshot file.
366
+
367
+ ```typescript
368
+ // Graceful-shutdown hook — write to a dated backup path
369
+ process.on('SIGTERM', async () => {
370
+ await cache.writeSnapshot(`/backups/cache-${Date.now()}.snap`);
371
+ process.exit(0);
372
+ });
373
+ ```
374
+
375
+ ### `cache.keys()` → `Generator<string>`
376
+
377
+ 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.
229
378
 
230
- Manual snapshot control. Called automatically on `SIGTERM`/`SIGINT` — only needed when you manage shutdown yourself.
379
+ ```typescript
380
+ for (const key of cache.keys()) console.log(key);
381
+ ```
382
+
383
+ ### `cache.values<T>()` → `Generator<T>`
384
+
385
+ 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.
386
+
387
+ ```typescript
388
+ for (const session of cache.values<Session>()) evict(session);
389
+ ```
390
+
391
+ ### `cache.entries<T>()` → `Generator<[string, T]>`
392
+
393
+ Lazily yields `[key, value]` pairs for every live L1 entry. Key has namespace prefix stripped.
394
+
395
+ ```typescript
396
+ for (const [key, user] of cache.entries<User>()) sync(key, user);
397
+ ```
398
+
399
+ > **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.
231
400
 
232
401
  ### `cache.destroy()` → `Promise<void>`
233
402
 
@@ -340,6 +509,18 @@ CacheService.create({ encryptionKey: '<base64-key>', encryptionMode: 'xor' });
340
509
 
341
510
  Existing plaintext values are read transparently during key rotation.
342
511
 
512
+ ### Zero-downtime key rotation
513
+
514
+ Set `previousEncryptionKey` to your old key while rolling out a new one. The cache tries the current key first; if decryption fails it transparently retries with the previous key. Remove `previousEncryptionKey` once all old entries have expired.
515
+
516
+ ```typescript
517
+ CacheService.create({
518
+ encryptionKey: process.env.NEW_ENCRYPTION_KEY, // new AES-256 key
519
+ previousEncryptionKey: process.env.OLD_ENCRYPTION_KEY, // fallback for old entries
520
+ // previousEncryptionMode defaults to current encryptionMode
521
+ });
522
+ ```
523
+
343
524
  ---
344
525
 
345
526
  ## ⚡ WASM Bloom filter
@@ -366,49 +547,59 @@ Measured on a single Node.js thread (no `await` on synchronous paths):
366
547
 
367
548
  | Operation | Throughput | Latency | Notes |
368
549
  |---|---|---|---|
369
- | `get` — hot hit (8K entries) | 1.24 M/s | 807 ns | bloom → Map lookup |
370
- | `get` — cold miss | 7.32 M/s | 137 ns | bloom gates → early return |
371
- | `set` — tiny payload | 1.03 M/s | 974 ns | pack() + Map.set + bloom.add |
372
- | `set` — small payload (≈ 512 B) | 519 K/s | 1.93 µs | pack() same unified path, larger payload |
373
- | `set` — large payload (≥ 512 B) | 225 K/s | 4.44 µs | pack() larger payload |
374
- | `set` — CRITICAL priority | 693 K/s | 1.44 µs | same set path; skipped in eviction sort |
375
- | `delete` — exact key | 3.08 M/s | 325 ns | Map.delete |
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 |
376
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()` |
559
+
560
+ **Iterator interface (L1 live entries, 500 entries)**
561
+
562
+ | Method | Throughput | Latency | Notes |
563
+ |---|---|---|---|
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 |
377
568
 
378
569
  **CacheService (end-to-end)**
379
570
 
380
571
  | Operation | Throughput | Latency | Notes |
381
572
  |---|---|---|---|
382
- | `get` — L1 warm hit | 1.39 M/s | 720 ns | inflight check → l1.get |
383
- | `get` — SWR stale serve | 1.34 M/s | 744 ns | serves stale; revalidates async |
384
- | `get` — miss + fetchFn | 17.8 K/s | 56.2 µs | Promise microtask + l1.set |
385
- | `set` | 28.3 K/s | 35.3 µs | l1.set + disk.save (fire-and-forget) |
386
- | `delete` — exact key | 29.7 K/s | 33.6 µs | l1.delete + disk.delete + backplane |
387
- | `delete` — glob `*` | 723 K/s | 1.38 µs | l1.deletePattern O(n) + disk glob |
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 |
388
579
 
389
580
  **Encryption** (IV pool, pre-allocated output buffers)
390
581
 
391
582
  | Mode | Payload | Encrypt | Decrypt |
392
583
  |---|---|---|---|
393
- | AES-256-GCM | 64 B | 129 K/s / 7.78 µs | 147 K/s / 6.80 µs |
394
- | AES-256-GCM | 512 B | 120 K/s / 8.33 µs | 103 K/s / 9.72 µs |
395
- | AES-256-GCM | 4 KB | 56.3 K/s / 17.8 µs | 46.3 K/s / 21.6 µs |
396
- | AES-128-GCM | 64 B | 116 K/s / 8.66 µs | 153 K/s / 6.55 µs |
397
- | AES-128-GCM | 512 B | 125 K/s / 7.99 µs | 141 K/s / 7.12 µs |
398
- | AES-128-GCM | 4 KB | 58.6 K/s / 17.1 µs | 55.1 K/s / 18.2 µs |
399
- | AES-128-CTR | 64 B | 142 K/s / 7.02 µs | 194 K/s / 5.15 µs |
400
- | AES-128-CTR | 512 B | 181 K/s / 5.54 µs | 190 K/s / 5.25 µs |
401
- | AES-128-CTR | 4 KB | 85.5 K/s / 11.7 µs | 60.0 K/s / 16.7 µs |
402
- | XOR _(obfuscation only)_ | 64 B | 2.34 M/s / 428 ns | 1.88 M/s / 531 ns |
403
- | XOR _(obfuscation only)_ | 512 B | 549 K/s / 1.82 µs | 893 K/s / 1.12 µs |
404
- | XOR _(obfuscation only)_ | 4 KB | 102 K/s / 9.86 µs | 181 K/s / 5.51 µs |
584
+ | AES-256-GCM | 64 B | 114 K/s / 8.75 µs | 133 K/s / 7.52 µs |
585
+ | AES-256-GCM | 512 B | 70.3 K/s / 14.21 µs | 114 K/s / 8.80 µs |
586
+ | AES-256-GCM | 4 KB | 41.7 K/s / 23.99 µs | 43.0 K/s / 23.24 µs |
587
+ | AES-128-GCM | 64 B | 127 K/s / 7.89 µs | 145 K/s / 6.91 µs |
588
+ | AES-128-GCM | 512 B | 90.8 K/s / 11.01 µs | 132 K/s / 7.59 µs |
589
+ | AES-128-GCM | 4 KB | 48.9 K/s / 20.47 µs | 42.9 K/s / 23.32 µs |
590
+ | AES-128-CTR | 64 B | 181 K/s / 5.51 µs | 192 K/s / 5.21 µs |
591
+ | AES-128-CTR | 512 B | 175 K/s / 5.71 µs | 182 K/s / 5.50 µs |
592
+ | AES-128-CTR | 4 KB | 61.8 K/s / 16.18 µs | 54.0 K/s / 18.51 µs |
593
+ | XOR _(obfuscation only)_ | 64 B | 2.37 M/s / 422 ns | 2.11 M/s / 475 ns |
594
+ | XOR _(obfuscation only)_ | 512 B | 598 K/s / 1.67 µs | 513 K/s / 1.95 µs |
595
+ | XOR _(obfuscation only)_ | 4 KB | 82.7 K/s / 12.09 µs | 146 K/s / 6.84 µs |
405
596
 
406
597
  > AES and XOR string-path numbers shown (Redis L2). Buffer path (disk/snapshot) is 5–20% faster — no base64 overhead.
407
598
  > AES-128-GCM is 5–50% faster than AES-256-GCM depending on payload (gap widens at mid-range sizes on AES-NI hardware).
408
599
  > AES-128-CTR removes the GHASH MAC step: ~50% faster than AES-128-GCM at small payloads; use only when integrity is guaranteed by transport.
409
600
  > XOR numbers are for the buffer path (32-bit word-level XOR, 4 bytes/iteration). XOR dominates at small payloads (no cipher setup) and remains ~2× faster than AES at 4 KB.
410
601
 
411
- Run `pnpm bench` for a full breakdown including bloom filter cost, compression trade-offs, eviction pressure, concurrency, and a realistic 80/15/5 read/miss/write workload.
602
+ See [BENCHMARKS.md](BENCHMARKS.md) for the full breakdown: bloom filter cost, serialization by payload size, eviction pressure, concurrency analysis, multi-tenancy isolation, and a realistic 80/15/5 read/miss/write workload.
412
603
 
413
604
  ---
414
605
 
@@ -427,7 +618,7 @@ Bug reports and pull requests are welcome!
427
618
 
428
619
  ## 🛡️ Security
429
620
 
430
- Found a vulnerability? **Please don't open a public issue.** Report it privately via [GitHub Security Advisories](https://github.com/Kareem411/tricache/security/advisories/new) so it can be patched before disclosure.
621
+ Found a vulnerability? **Please don't open a public issue.** Report it privately via [GitHub Security Advisories](https://github.com/Kareem411/TriCache/security/advisories/new) so it can be patched before disclosure.
431
622
 
432
623
  For encryption key generation and rotation best practices, see the [Encryption](#-encryption) section.
433
624