---
title: MemoryCache
description: 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

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

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

`new MemoryCache({ maxEntries })` keeps at most `maxEntries` entries (1024
by default) and drops the least recently used past it. `maxEntries` is a
positive safe integer and the only option: anything else is refused with a
`CacheConfigurationError` (`MemoryCache options must contain a positive
safe-integer maxEntries only.`).

## Characteristics

| Property | Value |
|----------|-------|
| Persistence | None - data lost on restart |
| Distribution | Single instance only |
| TTL Handling | Expired entries deleted on read and by a sweep, at least once a minute; staleness checked at read time |
| Dependencies | None |
| Performance | Fastest (in-process) |

## Behavior

### Automatic Eviction

Each entry is stored until its storage TTL elapses (the TTL alone, or TTL plus the stale window when SWR is enabled). A read of an expired entry deletes it, and one timer deletes every expired entry, at least once a minute while the store holds entries. With `maxEntries`, this keeps memory bounded. The timer is `unref`'d, so it never keeps 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

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

const client = createClient({ schema: { user }, driver }).$extends(
  cache({ driver: 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 },
});
```
