# Cap a cache by entry count

> A SIEVE cache keeps at most capacity entries and returns what it evicted from every set.

**Few items**

```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
cache.set('c', 3) // [{ key: 'b', value: 2 }], what was evicted to make room
cache.peek('b') // undefined
cache.size // 2
```

**Thousands of items**

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

const cache = sieveCache<number, string>({ capacity: 1_000 })
let evicted = 0

// 100 hot keys, read again between 20,000 inserts of keys seen once.
const hot = Array.from({ length: 100 }, (_, index) => index)

for (const key of hot) {
  cache.set(key, `value-${key}`)
}

for (let index = 100; index < 20_100; index += 1) {
  cache.get(index % 100)
  evicted += cache.set(index, `value-${index}`).length
}

cache.size // 1000
evicted // 19100, every insert after the first 1,000 evicted one entry
hot.every((key) => cache.peek(key) !== undefined) // true, a read marks a key and the eviction hand skips it
cache.peek(1_000) // undefined, a key read once is gone
```

The same options also bound total weight with `weigh`, and expire entries with `timeToLive` and a clock you pass in. The module page compares SIEVE, LRU, and S3-FIFO on a scan-heavy trace.

**Modules:** [`knotkit/cache`](/modules/cache/) · [API reference](/reference/knotkit/cache/)
