Caching

Redis-backed caching for improved query performance

Enable Caching

enable-caching.tstypescript
import { Stabilize, DBType } from "stabilize-orm";
const orm = new Stabilize(
{
type: DBType.Postgres,
connectionString: process.env.DATABASE_URL,
},
{
enabled: true,
ttl: 60, // Cache for 60 seconds
redisUrl: process.env.REDIS_URL,
cachePrefix: "myapp:",
strategy: "cache-aside", // or "write-through"
}
);

Cache Strategies

Stabilize supports two caching strategies:

  • cache-aside - Read from cache first, query database on miss
  • write-through - Update cache immediately after database writes

Cache Statistics

cache-stats.tstypescript
const stats = await orm.cache.getStats();
console.log(`Cache Hits: ${stats.hits}`);
console.log(`Cache Misses: ${stats.misses}`);
console.log(`Total Keys: ${stats.keys}`);

Manual Cache Control

manual-cache.tstypescript
// Invalidate specific keys
await orm.cache.invalidate(['user:1', 'all_users']);
// Invalidate by pattern
await orm.cache.invalidatePattern('user:*');
// Set custom TTL
await orm.cache.set('user:1', userData, 3600); // 1 hour