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
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.
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.
, 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.
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.
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) // []
constcache: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.
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
constcache: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.
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.
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.
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.
. 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
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)
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
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.
leastRecentlyUsedCache12 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
sieveCache12 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
s3FifoCache12 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
customCache12 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
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/