MasterRecord

Query Caching

Serve repeat reads from cache — in-memory by default, Redis for scale.

Frequently-run read queries can be cached so identical reads skip the database. MasterRecord ships an in-memory cache out of the box and a Redis-backed cache for multi-instance deployments.

Caching a query#

Add .cache() to a read chain, optionally with a TTL (seconds):

cache.js
// Cache for 60 seconds
const roles = await db.Role.where((r) => r.active == true).cache(60).toList();

// Cache with the default TTL
const config = await db.Setting.cache().toList();

In-memory cache#

The default cache lives in the process — perfect for a single instance. It’s automatically invalidated when you write to the affected table.

QueryCache
import QueryCache from 'masterrecord/Cache/QueryCache';
// Configured automatically; tune size/TTL via the context if needed.

Redis cache for horizontal scaling#

Running multiple backend instances? Point the cache at Redis so they share results and invalidations:

RedisQueryCache
import RedisQueryCache from 'masterrecord/Cache/RedisQueryCache';

// Provide an ioredis-compatible client; all instances now share the cache.
const cache = new RedisQueryCache({ host: '127.0.0.1', port: 6379 });
Cache only what's safe
Cache stable, read-heavy data (lookups, config, public listings). Avoid caching per-user or rapidly-changing data unless you set a short TTL and understand the staleness window.