Skip to main content
The @cache decorator caches method execution results to improve performance. Based on BentoCache, it supports various storage options including memory, Redis, and DynamoDB.

Basic Usage

Configuration (sonamu.config.ts)

Cache configuration is required in sonamu.config.ts to use caching.
Without cache configuration, using @cache will cause an error.

Options

ttl

Specifies cache validity time.
String format is more readable: "10s", "5m", "1h", "1d"

key

Specifies the cache key. Default: "{ModelName}.{methodName}:{serializedArgs}"

store

Specifies the cache store to use. Default: default store from sonamu.config.ts

tags

Specifies cache tags. Used for bulk cache invalidation by tag.

grace

Advanced options like grace and timeouts are provided by BentoCache’s RawCommonOptions. See BentoCache documentation for details.
Grace period that returns the previous value (Stale) for a certain time after cache expires (Stale-While-Revalidate pattern).
How it works:
  • Within TTL: Return fresh cache
  • Within grace period after TTL: Return stale cache immediately, refresh in background
  • After grace period: Cache miss
Stale-While-Revalidate provides fast responses to users (even if stale), while refreshing in the background so the next user gets fresh data.

timeouts

Sets timeouts for cache operations.

Cache Invalidation

Invalidate by Tag

Invalidate by Key

Clear All

Using with Other Decorators

With @api

With @transactional

Decorator order: @api@cache@transactional

How Cache Works

1. Cache Hit

2. Cache Miss

3. Cache Refresh

Precautions

1. CacheManager Initialization Required

Solution: Add cache configuration in sonamu.config.ts

2. Argument Serialization

Complex objects are automatically JSON serialized:
For objects that are difficult to serialize, use the key function to generate keys directly.

3. Caching null/undefined

null and undefined are also cached:

4. Methods with Side Effects

Use cache only for pure functions:

Performance Optimization

Multi-tier Caching

Fast memory cache + persistent Redis cache:

Cache Warmup

Pre-populate cache:

Logging

To log cache hits/misses, use BentoCache configuration:

Examples

Next Steps

@api

Create API endpoints

@transactional

Use transactions

BentoCache

BentoCache official documentation

Performance Optimization

Performance optimization guide