# knotkit/cache

> Bounds an in-memory key-value store by entry count or total weight, with least-recently-used, SIEVE, S3-FIFO, or caller-supplied eviction and optional expiry

## Use

```ts
import { sieveCache } from 'knotkit/cache'

const cache = sieveCache<string, number>({ capacity: 2 })

cache.set('a', 1) // []
cache.set('b', 2) // []
cache.get('a') // 1, counts as a use
cache.set('c', 3) // [{ key: 'b', value: 2 }], the entries evicted to make room
cache.peek('b') // undefined
```

```ts
import { leastRecentlyUsedCache } from 'knotkit/cache'

let now = 0
const responses = leastRecentlyUsedCache<string, Uint8Array>({
  capacity: 1_000_000, // bytes
  weigh: (_key, value) => value.byteLength,
  timeToLive: 60_000, // milliseconds of the clock below
  clock: () => now,
})

responses.set('/a', new Uint8Array(400_000))
now = 60_000
responses.get('/a') // undefined, its age has reached timeToLive
```

## What it solves

* keep the results of repeated lookups in memory without letting them grow past a fixed size
* bound a store by total byte size or cost instead of by number of entries
* let stored results expire after a fixed time while the clock stays under test control
* find out which entries were pushed out to make room, so they can be flushed or logged
* switch the eviction policy for a given traffic shape without changing any call site
* evict in an order of my own, such as by recompute cost or an assigned priority, while the cache keeps handling weights, expiry, and iteration

## Choose a layout

| Factory                                            | Choose when                                                                                                                                                                                                                                            | Cost                                                                                                                                                                                                                                                                                      |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `leastRecentlyUsedCache`kind `least-recently-used` | a key read just now is the key most likely read next, eviction must follow strict recency order, and no run of never-repeated keys is longer than capacity; on the pinned one-hit trace it keeps 19 of 50 hot keys where sieve and s3-fifo keep all 50 | one recency-list move on every get and replace; the fewest hits of the three policies on every pinned trace                                                                                                                                                                               |
| `sieveCache`kind `sieve`                           | a minority of keys takes most reads, and the keys that are read repeatedly leave more than one slot of capacity free when a scan of never-repeated keys arrives; on a pinned scan of 90 hot keys in capacity 100 it keeps all 90                       | one visited bit per entry and no list move on get; loses its whole hot set to a scan when that set fills all but one slot                                                                                                                                                                 |
| `s3FifoCache`kind `s3-fifo`                        | one-pass scans or keys requested once are common, and the repeatedly read keys fit in the main queue, which is 90 percent of capacity; on a pinned scan of 9 hot keys in capacity 10 it keeps all 9 where the other two keep none                      | three queues and a ghost key for each evicted entry, retaining up to as many evicted keys as there are entries in the main queue; the slowest policy in the bench, and 152 fewer hits than sieve on the pinned Zipf 1.0 trace                                                             |
| `customCache`kind `custom`                         | the order entries must leave in depends on a fact none of least-recently-used, sieve, or s3-fifo reads, such as recompute cost, a caller-assigned priority, or read frequency                                                                          | a wrapper call and flag check per member and a try/finally per policy callback, plus whatever the policy keeps in its own objects; with a Map-based least-recently-used policy the bench replays take 2.3 times as long as leastRecentlyUsedCache on Zipf traffic and 3.8 times on a scan |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/cache/README.md#performance)

## Try it

Cold keys per scan1616Reset

* Replay 12 rounds with four recurring keys and 16 one-off keys per round.
* At 8 entries, SIEVE hits 41.7% of requests and least recently used hits 27.4%.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/cache/demo.ts) against `knotkit/cache` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                 | Returns       | Does                                                                                                                                                                                                                       |
| -------------------------------------------------------------------------------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`leastRecentlyUsedCache`](/reference/knotkit/cache/functions/leastrecentlyusedcache/) | `Cache<K, V>` | Bounded cache that evicts the entry used least recently; a use moves the entry to the front of a recency list.                                                                                                             |
| [`sieveCache`](/reference/knotkit/cache/functions/sievecache/)                         | `Cache<K, V>` | Bounded cache that evicts with SIEVE: a hand clears visited bits from the oldest entry toward the newest and evicts the first unvisited entry.                                                                             |
| [`s3FifoCache`](/reference/knotkit/cache/functions/s3fifocache/)                       | `Cache<K, V>` | Bounded cache that evicts with S3-FIFO: a probationary queue, a main queue, and a ghost queue of recently evicted keys.                                                                                                    |
| [`customCache`](/reference/knotkit/cache/functions/customcache/)                       | `Cache<K, V>` | Bounded cache that evicts the key a caller-supplied CacheEvictionPolicy chooses; the policy sees keys only, is told when keys are added, used, and deleted, and its chosen victim is validated before anything is removed. |

Cost per member. Open a row for every operation.

`leastRecentlyUsedCache` 12 members

| Member          | Cost                             |
| --------------- | -------------------------------- |
| `size`          | O(1)                             |
| `totalWeight`   | O(1)                             |
| `get`           | O(1) average                     |
| `peek`          | O(1) average                     |
| `has`           | O(1) average                     |
| `set`           | O(1) amortized per entry evicted |
| `delete`        | O(1) average                     |
| `clear`         | O(n)                             |
| `deleteExpired` | O(n)                             |
| `keys`          | O(1) per step, O(n) total        |
| `values`        | O(1) per step, O(n) total        |
| `entries`       | O(1) per step, O(n) total        |

`sieveCache` 12 members

| Member          | Cost                             |
| --------------- | -------------------------------- |
| `size`          | O(1)                             |
| `totalWeight`   | O(1)                             |
| `get`           | O(1) average                     |
| `peek`          | O(1) average                     |
| `has`           | O(1) average                     |
| `set`           | O(1) amortized per entry evicted |
| `delete`        | O(1) average                     |
| `clear`         | O(n)                             |
| `deleteExpired` | O(n)                             |
| `keys`          | O(1) per step, O(n) total        |
| `values`        | O(1) per step, O(n) total        |
| `entries`       | O(1) per step, O(n) total        |

`s3FifoCache` 12 members

| Member          | Cost                             |
| --------------- | -------------------------------- |
| `size`          | O(1)                             |
| `totalWeight`   | O(1)                             |
| `get`           | O(1) average                     |
| `peek`          | O(1) average                     |
| `has`           | O(1) average                     |
| `set`           | O(1) amortized per entry evicted |
| `delete`        | O(1) average                     |
| `clear`         | O(n)                             |
| `deleteExpired` | O(n)                             |
| `keys`          | O(1) per step, O(n) total        |
| `values`        | O(1) per step, O(n) total        |
| `entries`       | O(1) per step, O(n) total        |

`customCache` 12 members

| Member          | Cost                                                                                              |
| --------------- | ------------------------------------------------------------------------------------------------- |
| `size`          | O(1)                                                                                              |
| `totalWeight`   | O(1)                                                                                              |
| `get`           | O(1) average plus the policy's used                                                               |
| `peek`          | O(1) average                                                                                      |
| `has`           | O(1) average                                                                                      |
| `set`           | O(1) average plus the policy's added or used, plus its chooseVictim and deleted per entry evicted |
| `delete`        | O(1) average plus the policy's deleted                                                            |
| `clear`         | O(n) plus the policy's clear                                                                      |
| `deleteExpired` | O(n) plus the policy's deleted per expired entry                                                  |
| `keys`          | O(1) per step, O(n) total                                                                         |
| `values`        | O(1) per step, O(n) total                                                                         |
| `entries`       | O(1) per step, O(n) total                                                                         |

## What you pass in

| Input                                                                                                                              | Type                                           | Get one from                       |
| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------- |
| time source for expiry; nothing in the cache reads the time on its own                                                             | `Clock`                                        | [`knotkit/cache`](/modules/cache/) |
| entry weight for a total-weight capacity bound                                                                                     | `(key: K, value: V) => number`                 | `the caller`                       |
| eviction order for a custom cache: a factory from capacity to the callbacks added, used, deleted, chooseVictim, and optional clear | `(capacity: number) => CacheEvictionPolicy<K>` | [`knotkit/cache`](/modules/cache/) |

## Errors

Every error this module throws is `CacheInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `INVALID_CAPACITY` `INVALID_WEIGHT` `ENTRY_TOO_HEAVY` `INVALID_VALUE` `INVALID_TIME_TO_LIVE` `MISSING_CLOCK` `INVALID_CLOCK_READING` `INVALID_VICTIM` `REENTRANT_POLICY`

## When not to use it

| If you need to…                                                                   | Use instead                                                                                             |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| deduplicate concurrent asynchronous lookups, or compute a missing value on demand | a Map\<K, Promise\<V>> next to a Cache, because the cache is synchronous and stores no promises for you |
| a map that must never drop an entry                                               | Map                                                                                                     |
| store artifacts by the hash of their content and prove what a key returns         | [`knotkit/cas`](/modules/cas/)                                                                          |
| give different entries different lifetimes inside one cache                       | one cache per lifetime, each built with its own timeToLive                                              |
| count how often keys occur in a stream without keeping the keys                   | [`knotkit/scalar-sketch`](/modules/scalar-sketch/)                                                      |

## Performance

Measured by the suite in [`packages/cache/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/cache/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone. [Compare the recorded timings](/benchmarks/#cache).

## Prompt an agent

Prompt · knotkit/cacheCopy prompt

```
Use knotkit/cache for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/cache'.

Exports:
- `leastRecentlyUsedCache` → `Cache<K, V>`: Bounded cache that evicts the entry used least recently; a use moves the entry to the front of a recency list.
- `sieveCache` → `Cache<K, V>`: Bounded cache that evicts with SIEVE: a hand clears visited bits from the oldest entry toward the newest and evicts the first unvisited entry.
- `s3FifoCache` → `Cache<K, V>`: Bounded cache that evicts with S3-FIFO: a probationary queue, a main queue, and a ghost queue of recently evicted keys.
- `customCache` → `Cache<K, V>`: Bounded cache that evicts the key a caller-supplied CacheEvictionPolicy chooses; the policy sees keys only, is told when keys are added, used, and deleted, and its chosen victim is validated before anything is removed.

Pick the layout by these rules:
- `leastRecentlyUsedCache` (kind 'least-recently-used') when a key read just now is the key most likely read next, eviction must follow strict recency order, and no run of never-repeated keys is longer than capacity; on the pinned one-hit trace it keeps 19 of 50 hot keys where sieve and s3-fifo keep all 50
- `sieveCache` (kind 'sieve') when a minority of keys takes most reads, and the keys that are read repeatedly leave more than one slot of capacity free when a scan of never-repeated keys arrives; on a pinned scan of 90 hot keys in capacity 100 it keeps all 90
- `s3FifoCache` (kind 's3-fifo') when one-pass scans or keys requested once are common, and the repeatedly read keys fit in the main queue, which is 90 percent of capacity; on a pinned scan of 9 hot keys in capacity 10 it keeps all 9 where the other two keep none
- `customCache` (kind 'custom') when the order entries must leave in depends on a fact none of least-recently-used, sieve, or s3-fifo reads, such as recompute cost, a caller-assigned priority, or read frequency

Inputs and their sources:
- time source for expiry; nothing in the cache reads the time on its own: `Clock` from `knotkit/cache`
- entry weight for a total-weight capacity bound: `(key: K, value: V) => number` from `the caller`
- eviction order for a custom cache: a factory from capacity to the callbacks added, used, deleted, chooseVictim, and optional clear: `(capacity: number) => CacheEvictionPolicy<K>` from `knotkit/cache`

Use something else when:
- deduplicate concurrent asynchronous lookups, or compute a missing value on demand → a Map<K, Promise<V>> next to a Cache, because the cache is synchronous and stores no promises for you
- a map that must never drop an entry → Map
- store artifacts by the hash of their content and prove what a key returns → knotkit/cas
- give different entries different lifetimes inside one cache → one cache per lifetime, each built with its own timeToLive
- count how often keys occur in a stream without keeping the keys → knotkit/scalar-sketch

Errors are CacheInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/cache.md
Types: node_modules/knotkit/cache/ and https://knotkit.jkomyno.dev/reference/knotkit/cache/
```

## See also

* [API reference](/reference/knotkit/cache/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/cache/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/cache/knotkit.capability.json)suggest a change to the source record
