stacks-cache

$npx mdskill add stacksjs/stacks/stacks-cache

Implement caching in Stacks with memory, Redis, and cache-aside patterns.

  • Retrieve and store values with TTL or forever using get, set, and setForever.
  • Depends on @stacksjs/cache package and config/cache.ts configuration.
  • Selects cache driver based on config and uses getOrSet for cache-aside pattern.
  • Returns cached values, stats, or TTL info via the cache API.

SKILL.md

.github/skills/stacks-cacheView on GitHub ↗
---
name: stacks-cache
description: Use when implementing caching in Stacks — memory cache, Redis cache, cache-aside pattern (getOrSet), TTL management, cache stats, or cache configuration. Covers @stacksjs/cache and config/cache.ts.
license: MIT
compatibility: Bun >= 1.3.0, TypeScript
allowed-tools: Read Edit Write Bash Grep Glob
---

# Stacks Cache

## Key Paths
- Core package: `storage/framework/core/cache/src/`
- Configuration: `config/cache.ts`
- Cache storage: `storage/framework/cache/`

## Cache API (StacksCache)

```typescript
import { cache, memory } from '@stacksjs/cache'

// Get/Set
await cache.get<string>('key')                    // T | undefined
await cache.set('key', 'value', 3600)             // TTL in seconds
await cache.setForever('key', 'value')            // no expiry
await cache.mget<string>(['key1', 'key2'])        // T[]
await cache.mset([{ key: 'k1', value: 'v1', ttl: 60 }, ...])

// Cache-aside pattern
const value = await cache.getOrSet('expensive-key', async () => {
  return await computeExpensiveValue()
}, 3600)

// Delete
await cache.del('key')
await cache.del(['key1', 'key2'])
await cache.deleteMany(['key1', 'key2'])
await cache.remove('key')

// Existence
await cache.has('key')          // boolean
await cache.missing('key')     // boolean

// Take (get and delete)
const value = await cache.take<string>('key')

// TTL management
await cache.getTtl('key')              // remaining TTL
await cache.ttl('key', 7200)           // update TTL

// Clear
await cache.clear()
await cache.flush()

// Stats
const stats = await cache.getStats()
// { hits, misses, keys, size, hitRate }

// Keys
const keys = await cache.keys('user:*')  // pattern matching

// Cleanup
await cache.close()
await cache.disconnect()
```

## Factory Functions

```typescript
import { createMemoryCache, createRedisCache, createCache } from '@stacksjs/cache'

const memCache = createMemoryCache({
  stdTTL: 3600,       // default TTL (seconds)
  checkPeriod: 120,   // eviction check interval
  maxKeys: -1,        // -1 = unlimited
  useClones: true,    // clone on get/set
  prefix: 'app:'      // key prefix
})

const redisCache = createRedisCache({
  url: 'redis://localhost:6379',
  // or individual:
  host: 'localhost',
  port: 6379,
  username: undefined,
  password: undefined,
  database: 0,
  tls: false,
  stdTTL: 3600,
  prefix: 'app:'
})

// Auto-detect from config
const cache = createCache('memory')
const cache = createCache('redis', { host: 'localhost' })
```

## config/cache.ts
```typescript
{
  driver: 'memory',     // 'memory' | 'redis'
  prefix: 'stacks',
  ttl: 3600,            // 1 hour default
  maxKeys: -1,          // unlimited
  useClones: true,
  drivers: {
    redis: { host: 'localhost', port: 6379 },
    memory: {}
  }
}
```

## Default Instance
- `cache` — default memory cache (pre-configured)
- `memory` — alias for `cache`

## Gotchas
- Default driver is `memory` — data lost on restart
- Redis driver requires a running Redis server
- `getOrSet()` is the cache-aside pattern — fetches only on miss
- `useClones: true` means mutations to retrieved objects don't affect cache
- `take()` atomically gets and deletes — useful for one-time tokens
- Cache stats track hits, misses, and hit rate — useful for tuning
- `keys()` supports glob patterns for key listing
- Framework caches (auto-imports, discovered packages) are in `storage/framework/cache/`
- Use `buddy clean` or `buddy fresh` to clear framework caches

More from stacksjs/stacks

SkillDescription
stacks-actionsUse when working with Stacks server actions — creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 80+ default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/actions/.
stacks-aiUse when integrating AI capabilities into a Stacks application — using Anthropic/OpenAI/Ollama/AWS Bedrock drivers, image generation (DALL-E), vision analysis, RAG/vector search, embeddings, MCP (Model Context Protocol) clients, text summarization, sentiment analysis, content classification, personalization, or the buddy AI assistant. Covers @stacksjs/ai and config/ai.ts.
stacks-aliasUse when working with path aliases in a Stacks project — import resolution, module aliasing, or debugging import paths. Covers @stacksjs/alias which defines 260+ path mappings for the entire framework.
stacks-analyticsUse when adding analytics to a Stacks application — configuring Fathom or self-hosted analytics, generating tracking scripts, privacy-friendly analytics setup, or the analytics configuration. Covers @stacksjs/analytics and config/analytics.ts.
stacks-apiUse when building, modifying, or debugging API endpoints in a Stacks application — defining routes, handling requests, API middleware, working with the API server, HTTP client (fetcher), API resources, or OpenAPI generation. Covers both @stacksjs/api utilities and the stacks-api server implementation.
stacks-arraysUse when working with array utilities in Stacks — statistical operations (average, median, mode, standard deviation, z-score, percentile, covariance), array manipulation (unique, flatten, partition, shuffle, sample, move), containment checks, or the Arr facade. Covers @stacksjs/arrays.
stacks-authUse when implementing authentication, authorization, passkeys, TOTP/2FA, RBAC, gates, policies, session auth, token management, email verification, password resets, or rate limiting in a Stacks application. Covers the @stacksjs/auth package, config/auth.ts, app/Gates.ts, and app/Middleware/.
stacks-auto-importsUse when working with the Stacks auto-import system — understanding how browser and server auto-imports work, configuring auto-imported functions/models/composables, the auto-import manifests, type generation, or how globals are injected. Covers the auto-import pipeline at storage/framework/auto-imports/.
stacks-brandkitUse when defining or exploring a brand identity for a Stacks project and you want premium brand-kit REFERENCE IMAGES first - logo directions, palettes, typography specimens, identity boards, and application/mockup decks. Generates IMAGES ONLY, never code. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems with intentional logo concepting, sparse type, strong symbolic meaning, and disciplined palettes a coding step can build against.
stacks-browseUse for headless browser QA on Stacks applications — navigation, screenshots, responsive testing, console/network monitoring, and accessibility snapshots. Dependency-free: drives a system browser over the Chrome DevTools Protocol using only Bun (no Playwright/Puppeteer). Invoke with /stacks-browse.