Cache
Cache opted-in reads in Redis. Keys, serialization, and invalidation after writes are handled for you.
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-drizzlepnpm add better-drizzleyarn add better-drizzlebun add better-drizzleThe 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:
- The call passes
cache(anything exceptfalse). - Its model is enabled under
modelsand the call does not passcache: false. - The plugin has
enabled: trueand 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 defaultEvery 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 accepts,m,h, andd.negativeTtlapplies tonullresults fromfindFirst,findOne, andfindUnique. It defaults to the smaller ofttland 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
| 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 |