# Cache

> Cache opted-in reads in Redis. Keys, serialization, and invalidation after writes are handled for you.

URL: https://better-drizzle.com/docs/plugins/cache

(Added in 0.3.0)

Use `better-drizzle/cache` when the same reads run often, change rarely, and every write goes through the client. It caches the reads you opt into. The plugin builds automatic keys from the final query, and observed writes invalidate declared dependencies. Inside a transaction, invalidation waits until the transaction commits. `better-drizzle/cache/redis` is the store.

> **Experimental:** The cache plugin is experimental in `0.3.x`. Its options, `$cache` API,
> store interface, and entry format can change in a patch release. Pin an
> exact version if you depend on it. See
> [stability](/docs/reference/stability#experimental-in-03x).

For how keys and invalidation work, see [cache keys and invalidation](/docs/plugins/cache-keys). To plug in another store, see [cache stores](/docs/plugins/cache-stores).

## Install

**npm**

```bash
npm install better-drizzle
```

**pnpm**

```bash
pnpm add better-drizzle
```

**yarn**

```bash
yarn add better-drizzle
```

**bun**

```bash
bun add better-drizzle
```

The Redis store drives the client your app already has, so the package adds no Redis dependency. Supported clients are Bun's `RedisClient`, `ioredis`, and `node-redis`. The store never opens or closes connections.

## Usage

```ts
import { better } from 'better-drizzle';
import { cache } from 'better-drizzle/cache';
import { redis } from 'better-drizzle/cache/redis';

import Redis from 'ioredis';

const client = better(db, {
	plugins: [cache({ store: redis({ client: new Redis(process.env.REDIS_URL!) }), ttl: '5m' })],
});
```



**better-drizzle**

```ts  
const user = await client.users.findUnique({ where: { id }, cache: true });

await client.users.update({ where: { id }, data: { name } });
// The next findUnique misses and reads the fresh row.
```

**Drizzle**

```ts  
const key = `users:${id}`;
const cached = await redis.get(key);

const user = cached
	? JSON.parse(cached) // Dates and bigints come back as strings
	: ((await db.select().from(users).where(eq(users.id, id)))[0] ?? null);

if (!cached) await redis.set(key, JSON.stringify(user), 'EX', 300);

await db.update(users).set({ name }).where(eq(users.id, id));

await redis.del(key); // and every list, count, and page that contains this user
```

## Turning caching on

Caching is off by default. A read uses the cache in one of three cases:

1. The call passes `cache` (anything except `false`).
2. Its model is enabled under `models` and the call does not pass `cache: false`.
3. The plugin has `enabled: true` and neither the model nor the call disables it.

```ts
await client.users.findMany({ cache: true }); // defaults
await client.users.findMany({ cache: { ttl: '30s', tags: ['feed'] } }); // per-call settings
await client.users.findFirst({ cache: 'newest-user', orderBy: { id: 'desc' } }); // custom key
await client.posts.findMany({ cache: false }); // opt out of a model default
```

Every read accepts `cache`: `findMany`, `findFirst`, `findOne`, `findUnique`, `count`, `exists`, `paginate`, and `cursor`. `paginate` and `cursor` cache the whole `{ data, pagination }` result, so `total` and the navigation flags come from the cache too.

## When to cache

The cache pays off when the same read runs often, its result changes rarely, and every write to its tables goes through `client`. Typical fits:

* lookups by primary key on rows that are read far more than written (users, products, settings, feature flags)
* lists and counts behind public or dashboard pages that many requests share
* reference data that almost never changes (countries, plans, categories)

## When not to cache

Leave it off, or pass `cache: false`, in these cases:

**Writes happen outside client**

Another service, a raw Drizzle call on `db`, a database trigger, a migration, or a job in another language changes the table. The plugin never sees those writes, so entries stay stale until their TTL unless you call `$cache.invalidate()`.

**The table is write-heavy**

Every write to a model invalidates every cached list, count, and page of it. When writes are as frequent as reads, lists almost never hit, and each miss adds a cache lookup and entry write on top of the query, plus version initialization when dependencies are missing.

**The read decides something that must be exact**

Balances, stock, permission checks, and rate limits should read the database, ideally inside a transaction, where the cache is always skipped. The database commit and cache invalidation are separate operations: a concurrent read can see the previous cached result after the commit, and a failed invalidation can leave it cached. TTL limits entry lifetime, not transaction consistency.

**The query rarely repeats**

Free-text search, per-user filters with many combinations, and deep pagination fill Redis with entries that are never read again.

**The query is already cheap**

A primary key lookup against a nearby database can take about as long as the Redis round trip that replaces it. Measure before caching it.

**The result depends on something outside the arguments**

This covers PostgreSQL row-level security driven by session settings, `now()`-relative data, and per-tenant databases or schemas behind the same model. The key cannot see any of these. Return them from `vary`, or don't cache the read.

**Results are large**

Anything over `maxSize` (1 MiB by default) is returned but never stored.

## Transactions

* Reads inside a transaction skip the cache and always query the database, so a transaction sees its own writes.
* Writes inside a transaction collect their invalidations. The plugin batches them per transaction client and applies them after the outermost transaction commits.
* A rollback leaves the cache untouched. A savepoint that rolls back drops only its own invalidations.
* Other requests can receive a previous cached value until invalidation completes. Commit and invalidation are not atomic, so this cache does not provide linearizable reads.

## Choosing TTLs

TTLs bound the lifetime of a stored entry; they do not guarantee consistency with the database. Unobserved writes, failed invalidation, and reads racing a commit can leave old results cached. Pick TTLs from the staleness your application can tolerate:

* `ttl` (required) applies to every entry. Numbers are seconds; strings accept `s`, `m`, `h`, and `d`.
* `negativeTtl` applies to `null` results from `findFirst`, `findOne`, and `findUnique`. It defaults to the smaller of `ttl` and 30 seconds, so a missing row is retried soon even if an outside write created it.
* Per model: `models: { plans: { ttl: '1d' } }`. Per call: `cache: { ttl: '10s' }`.
* No TTL may exceed `versionTtl` (7 days by default). Dependency versions live that long, and an entry must never outlive the versions it checks.

## Operate it in production

**Observing hits**

Client and plugin after hooks receive `annotations.cache` as `'hit'`, `'miss'`, or `'bypass'`. Reads that were never cache candidates carry no annotation. Log it from `afterQuery` to measure the hit rate per model and operation. To skip after hooks on hits, pass `afterHooksOnHit: false`, or `cache: { afterHooks: false }` on a call.

**Failures fail open**

When the store fails, reads fall back to the database and writes still succeed. Every failure reaches `onError` as a `BetterDrizzleError` with code `CACHE_STORE_ERROR`, `CACHE_SERIALIZATION_ERROR`, or `CACHE_VALUE_TOO_LARGE`, and `details.stage` set to `read`, `write`, `invalidate`, `serialize`, or `deserialize`. `CACHE_VALUE_TOO_LARGE` carries `details.size` and `details.maxSize` instead. Without `onError` they are silent, so set it in production.

**Serialization**

The default serializer keeps `Date`, `bigint`, `Buffer`, and `Uint8Array` alongside ordinary JSON values. Cycles, unsupported class instances, `undefined`, functions, symbol values, non-finite numbers, and negative zero are rejected rather than silently changed; the original result is returned and `onError` receives the serialization failure. Pass `serializer` to use another format, and change `version` when you do so that old entries are ignored.

**Memory**

Redis holds one entry per distinct read plus small version keys for model, row, tag, custom-key, and namespace dependencies established by reads or invalidations. Entries expire with their TTL. Version keys expire `versionTtl` after their last write, so give the Redis instance a memory limit and an eviction policy such as `volatile-lru`.

**Redis Cluster**

Pass `redis({ client, cluster: true })`, or an ioredis `Cluster`, to read keys one by one instead of `MGET` so they can live in different slots. For a node-redis cluster client, pass `redis({ command, cluster: true })` with a function that runs one command.

**Several instances**

Versions live in Redis, so an invalidation from one app instance is seen by every other instance on its next read. Deduplication of concurrent misses is per process.

**Not implemented**

Stale-while-revalidate and distributed locks. Two instances that miss the same key at the same time both run the query.

## Reference

| Option            | Default            | Description                                                                            |
| ----------------- | ------------------ | -------------------------------------------------------------------------------------- |
| `store`           | required           | where entries live, e.g. `redis({ client })`                                           |
| `ttl`             | required           | default entry TTL, in seconds or as `'30s'`, `'5m'`, `'1h'`, `'1d'`                    |
| `enabled`         | `false`            | cache every read unless a model or call disables it                                    |
| `models`          | `{}`               | per-model defaults: `true`, `false`, or `{ enabled, ttl, negativeTtl, tags }`          |
| `vary`            | none               | function whose return value goes into automatic keys, e.g. the tenant from `meta`      |
| `negativeTtl`     | `min(ttl, 30s)`    | TTL for `null` results from `findFirst`, `findOne`, and `findUnique`                   |
| `afterHooksOnHit` | `true`             | run client and plugin after hooks when a read is served from the cache                 |
| `namespace`       | `'better-drizzle'` | key prefix; give each app or database its own when they share a Redis                  |
| `version`         | `1`                | change it to ignore every entry written by another version, e.g. after a schema change |
| `maxSize`         | `1048576`          | largest entry in bytes; larger results are returned but not cached                     |
| `serializer`      | tagged JSON        | `{ serialize, deserialize }` to replace the default format                             |
| `versionTtl`      | `'7d'`             | lifetime of dependency versions; entry TTLs cannot exceed it                           |
| `onError`         | none               | receives store failures and values that could not be cached                            |

Per-call `cache` objects accept:

| Field                | Description                                                        |
| -------------------- | ------------------------------------------------------------------ |
| `ttl`, `negativeTtl` | override the model and plugin TTLs                                 |
| `tags`               | added to the model's tags; part of the key and of the dependencies |
| `key`                | custom key instead of the hash                                     |
| `vary`               | extra value hashed into the key                                    |
| `refresh`            | skip the stored value, run the query, and store the fresh result   |
| `afterHooks`         | run after hooks on a hit; overrides `afterHooksOnHit`              |
