Skip to content
VibORM
Esc
navigateopen⌘Jpreview
On this page

MemoryCache

In-memory cache driver using JavaScript Map for development and single-instance deployments

Installation

No additional dependencies required. MemoryCache is included in the core VibORM package.

Configuration

import { createClient } from "viborm";
import { MemoryCache } from "viborm/cache/memory";

const client = createClient({
  schema: { user, post },
  driver,
  cache: new MemoryCache(),
});

The MemoryCache constructor takes no arguments.

Characteristics

Property Value
Persistence None - data lost on restart
Distribution Single instance only
TTL Handling Timer eviction at storage TTL; staleness checked at read time
Dependencies None
Performance Fastest (in-process)

Behavior

Automatic Eviction

Each entry is stored with a per-key timer that deletes it once the storage TTL elapses (the TTL alone, or TTL plus the stale window when SWR is enabled). This keeps memory bounded. The timers are unref’d, so they never keep a Node.js process alive.

Within the storage window, staleness is checked at read time:

  • Fresh entries (age < TTL) are returned immediately
  • Stale entries (past TTL, within the SWR window) are returned and revalidated in the background
  • Evicted or missing entries trigger a fresh query

Use Cases

Recommended for:

  • Local development
  • Unit and integration tests
  • Single-instance deployments with limited query diversity
  • Prototyping and demos

Not recommended for:

  • Multi-instance deployments (no cache sharing)
  • Serverless functions (cache lost between invocations)

Example

import { createClient } from "viborm";
import { MemoryCache } from "viborm/cache/memory";

const client = createClient({
  schema: { user },
  driver,
  cache: new MemoryCache(),
});

// Cache queries for 10 minutes
const cached = client.$withCache({ ttl: "10 minutes" });

// First call: cache miss, executes query
const users1 = await cached.user.findMany({ where: { active: true } });

// Second call: cache hit, returns cached data
const users2 = await cached.user.findMany({ where: { active: true } });

// Invalidate on mutation
await client.user.update({
  where: { id: "123" },
  data: { name: "Alice" },
  cache: { autoInvalidate: true },
});

Was this page helpful?