Skip to main content

Memory Cache Driver

The memory cache driver stores data in memory. All cached data is lost when the application restarts.

When to Use

  • Local development
  • Caching data for the duration of a process
  • Fastest possible cache (no disk or network I/O)

Best For

  • Temporary data
  • Caching API responses, user sessions, or computed values

Limitations

  • Data is lost on restart
  • Not shared between processes or servers
  • No eviction policy (see LRU Memory Cache Driver for that)

Alternatives

Configuration

src/config/cache.ts
import { env } from "@mongez/dotenv";
import { CacheConfigurations, MemoryCacheDriver } from "@warlock.js/core";

const cacheConfigurations: CacheConfigurations = {
drivers: {
memory: MemoryCacheDriver,
},
default: env("CACHE_DRIVER", "memory"),
options: {
memory: {
globalPrefix: "dev-app",
ttl: 60 * 60, // 1 hour
},
},
};

export default cacheConfigurations;

Options

OptionTypeDefaultDescription
globalPrefixstring | FunctionundefinedGlobal prefix for all cache keys
ttlnumberInfinityDefault TTL in seconds

Global Prefix

{
globalPrefix: "myapp", // Static prefix
// OR
globalPrefix: () => `app-${environment()}`, // Dynamic prefix
}

TTL Configuration

{
ttl: Infinity, // Never expire (default)
// OR
ttl: 3600, // 1 hour
// OR
ttl: 60 * 60 * 24, // 24 hours
}

Example Usage

Storing and Retrieving Data

import { cache } from "@warlock.js/core";

await cache.set("user:1", { name: "Alice" }, 3600);
const user = await cache.get("user:1");

Memory Management

The memory driver uses a simple Map to store data in memory. Key points:

  • No size limits: The cache can grow indefinitely
  • No eviction: Items are only removed when they expire or are manually deleted
  • Fast access: O(1) average time complexity for get/set operations
  • Process isolation: Each Node.js process has its own cache instance

Troubleshooting

  • Data disappears after restart: This is expected. Use File or Redis drivers for persistence.
  • Cache not shared between processes: Use Redis for distributed cache.
  • Memory usage growing: Consider using LRU Memory Cache Driver for automatic eviction.
note

Please note that the Memory Cache Drier implements all methods in Cache Driver Interface so you can use it directly as a cache driver.