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}"
Key functions receive the method arguments as unknown[], so annotating parameter types does not compile. Leave parameters untyped when you only put them in a string, and assert the method’s argument types, as in const [params] = args as [SearchParams], when you need their properties.

scope

Decides whether results for the same arguments are shared between users. Default: "global"
Set scope: "user" when the result depends on the request user rather than the arguments, for example through Sonamu.getContext().user. Auto-generated and string keys replace Context arguments with that user’s segment regardless of scope, while a key function gets the user segment only with scope: "user". See @cache Decorator for the full key rules.

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, timeout, and hardTimeout 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.

timeout / hardTimeout

Limit how long a caller waits for the factory (the decorated method).
timeout only applies when a stale value is available through grace; the factory keeps running in the background and refreshes the cache.

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:
Context arguments are not serialized; they are replaced by that user’s segment. Arguments that cannot be serialized, such as BigInt, circular references, Map/Set, and functions, throw CacheKeySerializationError (a TypeError subclass) before the cache lookup and method call. You can import this error from sonamu or sonamu/cache.
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:

5. Check Authorization Outside the Cache

On a cache hit, the @cache method body does not run, so login and ownership checks inside it are skipped. Check authorization in an @api method or guard that runs on every call, then call the cached internal method. scope: "user" and user IDs in keys only separate cache entries; they do not authorize the caller. See @cache Decorator for an example.

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