better-drizzle
Plugins

Cache

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

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.

For how keys and invalidation work, see cache keys and invalidation. To plug in another store, see cache stores.

Install

npm install better-drizzle
pnpm add better-drizzle
yarn add better-drizzle
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

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' })],
});
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.

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.
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:

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

Reference

OptionDefaultDescription
storerequiredwhere entries live, e.g. redis({ client })
ttlrequireddefault entry TTL, in seconds or as '30s', '5m', '1h', '1d'
enabledfalsecache every read unless a model or call disables it
models{}per-model defaults: true, false, or { enabled, ttl, negativeTtl, tags }
varynonefunction whose return value goes into automatic keys, e.g. the tenant from meta
negativeTtlmin(ttl, 30s)TTL for null results from findFirst, findOne, and findUnique
afterHooksOnHittruerun 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
version1change it to ignore every entry written by another version, e.g. after a schema change
maxSize1048576largest entry in bytes; larger results are returned but not cached
serializertagged JSON{ serialize, deserialize } to replace the default format
versionTtl'7d'lifetime of dependency versions; entry TTLs cannot exceed it
onErrornonereceives store failures and values that could not be cached

Per-call cache objects accept:

FieldDescription
ttl, negativeTtloverride the model and plugin TTLs
tagsadded to the model's tags; part of the key and of the dependencies
keycustom key instead of the hash
varyextra value hashed into the key
refreshskip the stored value, run the query, and store the fresh result
afterHooksrun after hooks on a hit; overrides afterHooksOnHit

On this page