Skip to content

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

import {
function sieveCache<K, V>(options: CacheOptions<K, V>): Cache<K, V>

Create a

Cache

that evicts with SIEVE (Zhang et al., NSDI '24).

Each entry carries a visited bit that get sets. A hand walks from the oldest entry toward the newest, clearing set bits, and evicts the first entry whose bit is clear; it stays where it stopped for the next eviction. An entry read since the hand last passed it therefore survives one more pass, and new entries never move older ones.

Choose it as the default for skewed traffic, where a minority of keys takes most reads. During a one-pass scan of keys never read again, the hand clears each read entry once and then chases the scanned keys toward the head, evicting them rather than the read entries behind it; but when read entries fill all but one slot, the hand walks off the head, wraps to the tail, and the scan pushes out every entry not read during it. get and a set of a key already held count as uses; peek and has do not.

get, peek, has, and delete run in O(1) average time. set runs in O(1) amortized time per entry it evicts: the hand clears each visited bit at most once per set. Iteration is O(n) over every slot allocated since the last clear.

@throws ― {CacheInvalidInputError} With INVALID_CAPACITY when capacity is not a positive safe integer (or, with weigh, not a positive finite number), MISSING_CLOCK when timeToLive comes without clock, or INVALID_TIME_TO_LIVE when timeToLive is not a positive finite number.

@example

const cache = sieveCache<string, number>({ capacity: 2 })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'b', value: 2 }]

sieveCache
} from 'knotkit/cache'
const
const cache: Cache<string, number>
cache
=
sieveCache<string, number>(options: CacheOptions<string, number>): Cache<string, number>

Create a

Cache

that evicts with SIEVE (Zhang et al., NSDI '24).

Each entry carries a visited bit that get sets. A hand walks from the oldest entry toward the newest, clearing set bits, and evicts the first entry whose bit is clear; it stays where it stopped for the next eviction. An entry read since the hand last passed it therefore survives one more pass, and new entries never move older ones.

Choose it as the default for skewed traffic, where a minority of keys takes most reads. During a one-pass scan of keys never read again, the hand clears each read entry once and then chases the scanned keys toward the head, evicting them rather than the read entries behind it; but when read entries fill all but one slot, the hand walks off the head, wraps to the tail, and the scan pushes out every entry not read during it. get and a set of a key already held count as uses; peek and has do not.

get, peek, has, and delete run in O(1) average time. set runs in O(1) amortized time per entry it evicts: the hand clears each visited bit at most once per set. Iteration is O(n) over every slot allocated since the last clear.

@throws ― {CacheInvalidInputError} With INVALID_CAPACITY when capacity is not a positive safe integer (or, with weigh, not a positive finite number), MISSING_CLOCK when timeToLive comes without clock, or INVALID_TIME_TO_LIVE when timeToLive is not a positive finite number.

@example

const cache = sieveCache<string, number>({ capacity: 2 })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'b', value: 2 }]

sieveCache
<string, number>({
CacheOptions<string, number>.capacity: number

The bound the cache keeps itself within. Without

weigh

, it counts entries and must be a positive safe integer. With

weigh

, it bounds the exact sum of the supplied binary floating-point weights and may be any positive finite number. There is no rounding tolerance at the bound.

capacity
: 2 })
const cache: Cache<string, number>
cache
.
Cache<string, number>.set: (key: string, value: number) => readonly CacheEntry<string, number>[]

Store the value under the key, replacing any value already there, after evicting what the policy chooses until the entry fits. The key just set is never evicted by its own call.

@returns ― The entries evicted to make room, in eviction order. Expired entries removed along the way are not reported. Empty when nothing was evicted.

@throws ― {CacheInvalidInputError} With code INVALID_VALUE when the value is undefined, INVALID_WEIGHT when weigh returns anything but a positive finite number, ENTRY_TOO_HEAVY when the entry alone outweighs capacity, or INVALID_CLOCK_READING when the injected clock returns a non-finite number. The cache is unchanged after any of these. A customCache also throws INVALID_VICTIM when its policy's chooseVictim names a key the cache does not hold or the key being set.

set
('a', 1) // []
const cache: Cache<string, number>
cache
.
Cache<string, number>.set: (key: string, value: number) => readonly CacheEntry<string, number>[]

Store the value under the key, replacing any value already there, after evicting what the policy chooses until the entry fits. The key just set is never evicted by its own call.

@returns ― The entries evicted to make room, in eviction order. Expired entries removed along the way are not reported. Empty when nothing was evicted.

@throws ― {CacheInvalidInputError} With code INVALID_VALUE when the value is undefined, INVALID_WEIGHT when weigh returns anything but a positive finite number, ENTRY_TOO_HEAVY when the entry alone outweighs capacity, or INVALID_CLOCK_READING when the injected clock returns a non-finite number. The cache is unchanged after any of these. A customCache also throws INVALID_VICTIM when its policy's chooseVictim names a key the cache does not hold or the key being set.

set
('b', 2) // []
const cache: Cache<string, number>
cache
.
Cache<string, number>.get: (key: string) => number | undefined

Return the value stored under the key, counting the read as a use for the eviction policy, or undefined when the key is absent or expired.

@throws ― {CacheInvalidInputError} With code INVALID_CLOCK_READING when the injected clock returns a non-finite number.

get
('a') // 1, counts as a use
const cache: Cache<string, number>
cache
.
Cache<string, number>.set: (key: string, value: number) => readonly CacheEntry<string, number>[]

Store the value under the key, replacing any value already there, after evicting what the policy chooses until the entry fits. The key just set is never evicted by its own call.

@returns ― The entries evicted to make room, in eviction order. Expired entries removed along the way are not reported. Empty when nothing was evicted.

@throws ― {CacheInvalidInputError} With code INVALID_VALUE when the value is undefined, INVALID_WEIGHT when weigh returns anything but a positive finite number, ENTRY_TOO_HEAVY when the entry alone outweighs capacity, or INVALID_CLOCK_READING when the injected clock returns a non-finite number. The cache is unchanged after any of these. A customCache also throws INVALID_VICTIM when its policy's chooseVictim names a key the cache does not hold or the key being set.

set
('c', 3) // [{ key: 'b', value: 2 }], the entries evicted to make room
const cache: Cache<string, number>
cache
.
Cache<string, number>.peek: (key: string) => number | undefined

Return the value stored under the key without counting the read as a use, or undefined when the key is absent or expired.

@throws ― {CacheInvalidInputError} With code INVALID_CLOCK_READING when the injected clock returns a non-finite number.

peek
('b') // undefined
cache.ts
import {
function leastRecentlyUsedCache<K, V>(options: CacheOptions<K, V>): Cache<K, V>

Create a

Cache

that evicts the entry used least recently.

Choose it when a key read recently is likely to be read again soon and the traffic has no long one-pass scans: a scan of keys never read again pushes every older entry out. get and a set of a key already held count as uses; peek and has do not.

get, peek, has, delete, and set run in O(1) average time, plus O(1) per entry set evicts. Iteration is O(n) over every slot allocated since the last clear.

@throws ― {CacheInvalidInputError} With INVALID_CAPACITY when capacity is not a positive safe integer (or, with weigh, not a positive finite number), MISSING_CLOCK when timeToLive comes without clock, or INVALID_TIME_TO_LIVE when timeToLive is not a positive finite number.

@example

const cache = leastRecentlyUsedCache<string, number>({ capacity: 2 })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'b', value: 2 }]

leastRecentlyUsedCache
} from 'knotkit/cache'
let
let now: number
now
= 0
const
const responses: Cache<string, Uint8Array<ArrayBufferLike>>
responses
=
leastRecentlyUsedCache<string, Uint8Array<ArrayBufferLike>>(options: CacheOptions<string, Uint8Array<ArrayBufferLike>>): Cache<string, Uint8Array<ArrayBufferLike>>

Create a

Cache

that evicts the entry used least recently.

Choose it when a key read recently is likely to be read again soon and the traffic has no long one-pass scans: a scan of keys never read again pushes every older entry out. get and a set of a key already held count as uses; peek and has do not.

get, peek, has, delete, and set run in O(1) average time, plus O(1) per entry set evicts. Iteration is O(n) over every slot allocated since the last clear.

@throws ― {CacheInvalidInputError} With INVALID_CAPACITY when capacity is not a positive safe integer (or, with weigh, not a positive finite number), MISSING_CLOCK when timeToLive comes without clock, or INVALID_TIME_TO_LIVE when timeToLive is not a positive finite number.

@example

const cache = leastRecentlyUsedCache<string, number>({ capacity: 2 })
cache.set('a', 1)
cache.set('b', 2)
cache.get('a')
cache.set('c', 3) // [{ key: 'b', value: 2 }]

leastRecentlyUsedCache
<string,
interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike>

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
>({
CacheOptions<string, Uint8Array<ArrayBufferLike>>.capacity: number

The bound the cache keeps itself within. Without

weigh

, it counts entries and must be a positive safe integer. With

weigh

, it bounds the exact sum of the supplied binary floating-point weights and may be any positive finite number. There is no rounding tolerance at the bound.

capacity
: 1_000_000, // bytes
CacheOptions<string, Uint8Array<ArrayBufferLike>>.weigh?: ((key: string, value: Uint8Array<ArrayBufferLike>) => number) | undefined

Give one entry's share of

capacity

. Called once per set, before the cache changes. The result must be a positive finite number no larger than capacity. Omit it to weigh every entry as 1.

weigh
: (
_key: string
_key
,
value: Uint8Array<ArrayBufferLike>
value
) =>
value: Uint8Array<ArrayBufferLike>
value
.
Uint8Array<ArrayBufferLike>.byteLength: number

The length in bytes of the array.

byteLength
,
CacheOptions<string, Uint8Array<ArrayBufferLike>>.timeToLive?: number | undefined

How long after its set an entry stays readable, in the milliseconds of

clock

. An entry whose age has reached timeToLive is never returned again. Requires clock.

timeToLive
: 60_000, // milliseconds of the clock below
CacheOptions<string, Uint8Array<ArrayBufferLike>>.clock?: Clock | undefined

The time source that

timeToLive

is measured against. A clock that moves backwards only delays expiry.

clock
: () =>
let now: number
now
,
})
const responses: Cache<string, Uint8Array<ArrayBufferLike>>
responses
.
Cache<string, Uint8Array<ArrayBufferLike>>.set: (key: string, value: Uint8Array<ArrayBufferLike>) => readonly CacheEntry<string, Uint8Array<ArrayBufferLike>>[]

Store the value under the key, replacing any value already there, after evicting what the policy chooses until the entry fits. The key just set is never evicted by its own call.

@returns ― The entries evicted to make room, in eviction order. Expired entries removed along the way are not reported. Empty when nothing was evicted.

@throws ― {CacheInvalidInputError} With code INVALID_VALUE when the value is undefined, INVALID_WEIGHT when weigh returns anything but a positive finite number, ENTRY_TOO_HEAVY when the entry alone outweighs capacity, or INVALID_CLOCK_READING when the injected clock returns a non-finite number. The cache is unchanged after any of these. A customCache also throws INVALID_VICTIM when its policy's chooseVictim names a key the cache does not hold or the key being set.

set
('/a', new
var Uint8Array: Uint8ArrayConstructor
new (length: number) => Uint8Array<ArrayBuffer> (+6 overloads)
Uint8Array
(400_000))
let now: number
now
= 60_000
const responses: Cache<string, Uint8Array<ArrayBufferLike>>
responses
.
Cache<string, Uint8Array<ArrayBufferLike>>.get: (key: string) => Uint8Array<ArrayBufferLike> | undefined

Return the value stored under the key, counting the read as a use for the eviction policy, or undefined when the key is absent or expired.

@throws ― {CacheInvalidInputError} With code INVALID_CLOCK_READING when the injected clock returns a non-finite number.

get
('/a') // undefined, its age has reached timeToLive
  • 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
FactoryChoose whenCost
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 50one 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 90one 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 nonethree 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 frequencya 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

{"v":1,"box":[60.6181,94.1597,845.1333,437.3555],"x":{"s":"log","lim":[3.53081198516,72.5045686589],"inv":false,"g":0,"t":"Cache capacity (entries)","tk":[[4,"4"],[6,"6"],[8,"8"],[12,"12"],[16,"16"],[24,"24"],[32,"32"],[48,"48"],[64,"64"]],"b":10},"y":{"s":"linear","lim":[26.7380952381,42.3095238095],"inv":false,"g":0,"tk":[[27.380952381,"27.4"],[35,"35"],[41.6666666667,"41.7"]]},"ti":"SIEVE reaches the hit ceiling at 6 entries; least recently used at 24","a":[{"k":"line","c":"#fffff8","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,34.5238095238,32,34.5238095238,48,36.9047619048,64,38.0952380952],"p":[93.01,423.19,198.26,423.19,272.94,423.19,378.2,423.19,452.88,423.19,558.13,265.76,632.81,265.76,738.07,213.28,812.75,187.04]},{"k":"line","c":"#5b6b7c","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,34.5238095238,32,34.5238095238,48,36.9047619048,64,38.0952380952],"p":[93.01,423.19,198.26,423.19,272.94,423.19,378.2,423.19,452.88,423.19,558.13,265.76,632.81,265.76,738.07,213.28,812.75,187.04]},{"k":"line","c":"#fffff8","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[93.01,423.19,198.26,423.19,272.94,423.19,378.2,423.19,452.88,423.19,558.13,108.33,632.81,108.33,738.07,108.33,812.75,108.33]},{"k":"line","c":"#1d5fa6","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[93.01,423.19,198.26,423.19,272.94,423.19,378.2,423.19,452.88,423.19,558.13,108.33,632.81,108.33,738.07,108.33,812.75,108.33]},{"k":"line","c":"#fffff8","s":"x","d":[4,27.380952381,6,41.6666666667,8,41.6666666667,12,41.6666666667,16,41.6666666667,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[93.01,423.19,198.26,108.33,272.94,108.33,378.2,108.33,452.88,108.33,558.13,108.33,632.81,108.33,738.07,108.33,812.75,108.33]},{"k":"line","c":"#c4501b","s":"x","d":[4,27.380952381,6,41.6666666667,8,41.6666666667,12,41.6666666667,16,41.6666666667,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[93.01,423.19,198.26,108.33,272.94,108.33,378.2,108.33,452.88,108.33,558.13,108.33,632.81,108.33,738.07,108.33,812.75,108.33]},{"k":"line","c":"#fffff8","s":"x","d":[4,37.2023809524,6,40.4761904762,8,40.4761904762,12,40.4761904762,16,40.4761904762,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[93.01,206.72,198.26,134.57,272.94,134.57,378.2,134.57,452.88,134.57,558.13,108.33,632.81,108.33,738.07,108.33,812.75,108.33]},{"k":"line","c":"#0b7f61","s":"x","d":[4,37.2023809524,6,40.4761904762,8,40.4761904762,12,40.4761904762,16,40.4761904762,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[93.01,206.72,198.26,134.57,272.94,134.57,378.2,134.57,452.88,134.57,558.13,108.33,632.81,108.33,738.07,108.33,812.75,108.33]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#0b7f61"}],"lg":[]} 4 6 8 12 16 24 32 48 64 Cache capacity (entries) 27.4 35 41.7 Ceiling 41.7%: every repeat hits, every first request misses custom FIFO runs underneath, also 27.4% Requests that hit (%) custom FIFO least-recently-used sieve s3-fifo SIEVE reaches the hit ceiling at 6 entries; least recently used at 24
{"v":1,"box":[60.6181,122.3921,397.1333,437.3555],"x":{"s":"log","lim":[3.53081198516,72.5045686589],"inv":false,"g":0,"t":"Cache capacity (entries)","tk":[[4,"4"],[6,"6"],[8,"8"],[12,"12"],[16,"16"],[24,"24"],[32,"32"],[48,"48"],[64,"64"]],"b":10},"y":{"s":"linear","lim":[26.7380952381,42.3095238095],"inv":false,"g":0,"tk":[[27.380952381,"27.4"],[35,"35"],[41.6666666667,"41.7"]]},"ti":"SIEVE reaches the hit ceiling at 6\nentries; least recently used at 24","a":[{"k":"line","c":"#fffff8","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,34.5238095238,32,34.5238095238,48,36.9047619048,64,38.0952380952],"p":[74.51,424.35,119.66,424.35,151.69,424.35,196.84,424.35,228.88,424.35,274.02,279.87,306.06,279.87,351.21,231.71,383.24,207.63]},{"k":"line","c":"#5b6b7c","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,34.5238095238,32,34.5238095238,48,36.9047619048,64,38.0952380952],"p":[74.51,424.35,119.66,424.35,151.69,424.35,196.84,424.35,228.88,424.35,274.02,279.87,306.06,279.87,351.21,231.71,383.24,207.63]},{"k":"line","c":"#fffff8","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[74.51,424.35,119.66,424.35,151.69,424.35,196.84,424.35,228.88,424.35,274.02,135.4,306.06,135.4,351.21,135.4,383.24,135.4]},{"k":"line","c":"#1d5fa6","s":"x","d":[4,27.380952381,6,27.380952381,8,27.380952381,12,27.380952381,16,27.380952381,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[74.51,424.35,119.66,424.35,151.69,424.35,196.84,424.35,228.88,424.35,274.02,135.4,306.06,135.4,351.21,135.4,383.24,135.4]},{"k":"line","c":"#fffff8","s":"x","d":[4,27.380952381,6,41.6666666667,8,41.6666666667,12,41.6666666667,16,41.6666666667,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[74.51,424.35,119.66,135.4,151.69,135.4,196.84,135.4,228.88,135.4,274.02,135.4,306.06,135.4,351.21,135.4,383.24,135.4]},{"k":"line","c":"#c4501b","s":"x","d":[4,27.380952381,6,41.6666666667,8,41.6666666667,12,41.6666666667,16,41.6666666667,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[74.51,424.35,119.66,135.4,151.69,135.4,196.84,135.4,228.88,135.4,274.02,135.4,306.06,135.4,351.21,135.4,383.24,135.4]},{"k":"line","c":"#fffff8","s":"x","d":[4,37.2023809524,6,40.4761904762,8,40.4761904762,12,40.4761904762,16,40.4761904762,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[74.51,225.69,119.66,159.47,151.69,159.47,196.84,159.47,228.88,159.47,274.02,135.4,306.06,135.4,351.21,135.4,383.24,135.4]},{"k":"line","c":"#0b7f61","s":"x","d":[4,37.2023809524,6,40.4761904762,8,40.4761904762,12,40.4761904762,16,40.4761904762,24,41.6666666667,32,41.6666666667,48,41.6666666667,64,41.6666666667],"p":[74.51,225.69,119.66,159.47,151.69,159.47,196.84,159.47,228.88,159.47,274.02,135.4,306.06,135.4,351.21,135.4,383.24,135.4]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#0b7f61"}],"lg":[]} 4 6 8 12 16 24 32 48 64 Cache capacity (entries) 27.4 35 41.7 Ceiling 41.7%: every repeat hits, every first request misses custom FIFO runs underneath, also 27.4% Requests that hit (%) custom FIFO least-recently-used sieve s3-fifo SIEVE reaches the hit ceiling at 6 entries; least recently used at 24
  • 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 against knotkit/cache in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
leastRecentlyUsedCacheCache<K, V>Bounded cache that evicts the entry used least recently; a use moves the entry to the front of a recency list.
sieveCacheCache<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.
s3FifoCacheCache<K, V>Bounded cache that evicts with S3-FIFO: a probationary queue, a main queue, and a ghost queue of recently evicted keys.
customCacheCache<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
MemberCost
sizeO(1)
totalWeightO(1)
getO(1) average
peekO(1) average
hasO(1) average
setO(1) amortized per entry evicted
deleteO(1) average
clearO(n)
deleteExpiredO(n)
keysO(1) per step, O(n) total
valuesO(1) per step, O(n) total
entriesO(1) per step, O(n) total
sieveCache 12 members
MemberCost
sizeO(1)
totalWeightO(1)
getO(1) average
peekO(1) average
hasO(1) average
setO(1) amortized per entry evicted
deleteO(1) average
clearO(n)
deleteExpiredO(n)
keysO(1) per step, O(n) total
valuesO(1) per step, O(n) total
entriesO(1) per step, O(n) total
s3FifoCache 12 members
MemberCost
sizeO(1)
totalWeightO(1)
getO(1) average
peekO(1) average
hasO(1) average
setO(1) amortized per entry evicted
deleteO(1) average
clearO(n)
deleteExpiredO(n)
keysO(1) per step, O(n) total
valuesO(1) per step, O(n) total
entriesO(1) per step, O(n) total
customCache 12 members
MemberCost
sizeO(1)
totalWeightO(1)
getO(1) average plus the policy's used
peekO(1) average
hasO(1) average
setO(1) average plus the policy's added or used, plus its chooseVictim and deleted per entry evicted
deleteO(1) average plus the policy's deleted
clearO(n) plus the policy's clear
deleteExpiredO(n) plus the policy's deleted per expired entry
keysO(1) per step, O(n) total
valuesO(1) per step, O(n) total
entriesO(1) per step, O(n) total
InputTypeGet one from
time source for expiry; nothing in the cache reads the time on its ownClockknotkit/cache
entry weight for a total-weight capacity bound(key: K, value: V) => numberthe 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

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
If you need to…Use instead
deduplicate concurrent asynchronous lookups, or compute a missing value on demanda 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 entryMap
store artifacts by the hash of their content and prove what a key returnsknotkit/cas
give different entries different lifetimes inside one cacheone cache per lifetime, each built with its own timeToLive
count how often keys occur in a stream without keeping the keysknotkit/scalar-sketch

Measured by the suite in 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.

Prompt · knotkit/cache
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/