Skip to content

Cache

@veloxts/cache provides a unified caching API with memory (LRU) and Redis drivers, cache tags, and distributed locks.

Terminal window
pnpm add @veloxts/cache
# For Redis (production)
pnpm add ioredis
import { cachePlugin } from '@veloxts/cache';
app.register(cachePlugin({
driver: 'memory',
config: { maxSize: 1000 },
}));
// Set value with TTL
await ctx.cache.put('user:123', user, '30m');
// Get value
const user = await ctx.cache.get('user:123');
// Remember pattern (cache-aside)
const data = await ctx.cache.remember('expensive:query', '1h', async () => {
return await fetchExpensiveData();
});
// Check existence
if (await ctx.cache.has('user:123')) { ... }
// Delete
await ctx.cache.forget('user:123');
'30s' // 30 seconds
'5m' // 5 minutes
'1h' // 1 hour
'1d' // 1 day
'1w' // 1 week
3600 // 3600 seconds (number)
// Set with tags
await ctx.cache.tags(['users']).put('user:123', user);
await ctx.cache.tags(['users']).put('user:456', user);
// Flush all tagged entries
await ctx.cache.tags(['users']).flush();
await ctx.cache.lockAndRun('payment:process', '30s', async () => {
// Only one instance runs this at a time
await processPayment();
});
await ctx.cache.increment('views:post:123');
await ctx.cache.decrement('stock:item:456');

Memory

LRU cache for development and single-instance deployments.

Redis

Shared cache for production with distributed locks.

FeatureMemoryRedis
Shared across instancesNoYes
Persists across restartsNoYes
Distributed locksNoYes
Memory managementLimitedExternal
src/index.ts
app.register(cachePlugin({
driver: 'redis',
config: {
url: process.env.REDIS_URL,
keyPrefix: 'myapp:cache:',
defaultTtl: '1h',
},
}));
.env
REDIS_URL=redis://user:password@your-redis-host:6379
ProviderBest For
UpstashServerless, pay-per-request
Redis CloudManaged Redis clusters
RailwaySimple Redis add-on