Skip to content
Warlock.js v4

Memory Extended Cache Driver

In-memory storage with sliding expiration: TTL resets on each access, keeping frequently used data alive.

  • You want cache entries to stay alive as long as they’re being used
  • Session-like or frequently accessed data
  • User sessions
  • Frequently accessed, but not permanent, data
src/config/cache.ts
import { MemoryExtendedCacheDriver } from "@warlock.js/cache";
const cacheConfigurations = {
drivers: {
memoryExtended: MemoryExtendedCacheDriver,
},
default: "memoryExtended",
options: {
memoryExtended: {
globalPrefix: "sessions",
ttl: 600, // 10 minutes
},
},
};
OptionTypeDefaultDescription
globalPrefixstring | FunctionundefinedGlobal prefix for all cache keys
ttlnumberInfinityDefault TTL in seconds
{
globalPrefix: "sessions", // Static prefix
// OR
globalPrefix: () => `app-${environment()}`, // Dynamic prefix
}
{
ttl: 600, // 10 minutes
// OR
ttl: 3600, // 1 hour
// OR
ttl: Infinity, // Never expire (default)
}
import { cache } from "@warlock.js/cache";
await cache.set("users.42.profile", { userId: 42, name: "Alice" }, CACHE_FOR.HALF_HOUR);
const profile = await cache.get("users.42.profile"); // TTL resets to 30 minutes

Unlike the regular Memory Cache Driver, the Memory Extended Driver implements sliding expiration:

  1. Initial Set: When you set a value with TTL, it’s stored with an expiration time
  2. Access Resets TTL: Every time you access the value, the TTL is reset to the original duration
  3. Continuous Access: As long as the value is accessed within the TTL window, it never expires
  4. Inactivity Expiration: Only when the value is not accessed for the full TTL duration does it expire
import { cache, CACHE_FOR } from "@warlock.js/cache";
// TTL: 30 minutes
await cache.set("cart.session-xyz", cartData, CACHE_FOR.HALF_HOUR);
// After 15 minutes
await cache.get("cart.session-xyz"); // TTL resets to 30 minutes
// After another 20 minutes (35 minutes total)
await cache.get("cart.session-xyz"); // TTL resets to 30 minutes again
// If not accessed for 30 minutes, it expires
  • User Sessions: Keep sessions alive as long as users are active
  • API Rate Limiting: Reset counters on each request
  • Frequently Accessed Data: Keep hot data in cache longer
  • Temporary State: Maintain state that should persist during activity
  • Data disappears after restart: This is expected. Use File or Redis for persistence.
  • Cache not shared between processes: Use Redis for distributed cache.
  • Items expiring too quickly: Increase the ttl value or access them more frequently.

Supported (brute force). Inherits the memory driver’s similarity behavior — O(N) cosine scan, dev-only at scale.