---
title: Caching
description: What the key cache saves and what it doesn't
---

The cache remembers which key id a key hash belongs to. `verify` still reads the key by id on every call, so a key revoked or disabled on any server stops working at once, never after the cache expires.

Because of that re-read, the cache only helps in one setup: the in-memory cache (`cache: true`) with Redis storage, where it saves the hash-index round trip. A Redis cache costs the same round trip it saves, and with a SQL database finding a key by hash costs the same as finding it by id, so in those setups leave it off. Caching is off by default.

## Turn it on

```ts
import { createKeys } from 'keypal'
import Redis from 'ioredis'

const keys = createKeys({
  storage: 'redis',
  redis: new Redis(),
  cache: true,  // in-memory, per process
  cacheTtl: 60, // seconds, the default
})
```

`cache` also takes `'redis'` (stored in the `redis` client) or any object with `get`, `set`, and `del`.

The cache needs a way to read keys by id. With a [lookup for your own table](/docs/getting-started/quick-start), add `findById` to it; without one, keypal skips the cache.

## How a verify uses it

1. **Valid key**: after a key verifies, its hash → id is cached.
2. **Cache hit**: the next verify reads the key by that id and checks it again: revoked, expired, disabled, and that the stored hash still matches.
3. **Cache miss or mismatch**: verify looks the key up by hash and caches the result.
4. **Failed check**: the entry is removed, so failures are never cached.
5. **TTL**: entries expire after `cacheTtl` seconds.

`revoke`, `rotate`, `enable`, and `disable` also remove the key's entry, and an entry that can't be parsed is removed when read. To remove one yourself, call `keys.invalidateCache(keyHash)`. To bypass the cache for one call, pass `{ skipCache: true }` to `verify`.

## Size the in-memory cache

`cache: true` holds up to 10,000 entries. When it is full, the entry added first is dropped, and expired entries are cleared every 60 seconds. To change either, pass your own `MemoryCache`:

```ts
import { createKeys, MemoryCache } from 'keypal'
import Redis from 'ioredis'

const redis = new Redis()
const cache = new MemoryCache({
  maxSize: 50_000,          // entries
  cleanupInterval: 30_000,  // milliseconds
})

const keys = createKeys({ storage: 'redis', redis, cache })

// On shutdown, stop the cleanup timer.
cache.dispose()
```

The cleanup timer doesn't keep Node.js running on its own, so `dispose()` matters mostly in tests and hot-reloading servers that create many caches.
