Skip to main content
You can use the @cache decorator to automatically cache the results of Model or Frame methods.

Basic Usage

Simple Example

How It Works:
  1. First call: DB query β†’ Cache result
  2. Second call (within 10 minutes): Return from cache (no DB query)
  3. After 10 minutes: Query DB again β†’ Refresh cache

Decorator Options

All Options

key: Cache Key Configuration

If no key is specified, it is automatically generated.
Pattern: ModelName.methodName:serializedArgsArgument Serialization Rules:
  • Single primitive (string/number/boolean): Used as-is
  • Complex objects: Uses JSON.stringify
  • No arguments: ModelName.methodName without suffix
  • Context argument: not serialized; replaced by the Context user segment (user:"<id>" or anon)
  • Unserializable arguments (BigInt, circular references, Map/Set, functions, etc.): error (see Cache Key Generation Logic)

scope: Per-user Cache Separation

scope decides whether results for the same arguments are shared between users.
  • Per-user separation is not on by default. Set scope: "user" on methods whose result depends on the request user.
  • In auto-generated and string keys, a Context (ctx) argument is replaced by that Context’s user segment regardless of scope. A key function must handle Context arguments itself.
  • With a key function and scope: "user", :<user segment> is appended to the key the function returns.

ttl: Expiration Time

TTL (Time To Live) is the duration the cache remains valid.
Without TTL: BentoCache default value applies (typically unlimited)

grace: Stale-While-Revalidate

Grace period is a feature that returns stale cache after TTL expiration while refreshing in the background.
How It Works:
  1. 0~1 minute: Return fresh cache
  2. 1~11 minutes: Immediately return stale cache + background refresh
  3. After 11 minutes: Cache miss, recalculate
Advantages:
  • Users always get fast response (even if stale, returns immediately)
  • Refreshed in background so next user gets fresh data

tags: Tag-based Invalidation

You can use tags to invalidate related caches as a group.
Invalidation Pattern:
For more details, see Cache Invalidation.

store: Using a Specific Store

When multiple stores are configured, you can specify a particular store.

forceFresh: Ignore Cache

Use when you always want to fetch fresh data.
Use Case: Only for debugging or special cases (generally unnecessary)

Practical Examples

1. API Response Caching

2. Cache Invalidation on Data Change

3. Complex Key Generation

4. Using Stale-While-Revalidate

Scenario:
  • 0~5 minutes: Fresh cache
  • 5~65 minutes: Immediately return stale cache + background recalculation
  • After 65 minutes: Cache miss, recalculate

5. Permanent Caching for Configuration Values

Internal Method Calls and Cache Sharing

Cache is also shared when calling other methods within a Model.
How It Works:

Cache Key Generation Logic

Argument Serialization

Auto-generated and string keys serialize the method arguments with the rules below and append them as a suffix. Unserializable values are never converted to strings such as [object Object], because such keys merge calls with different arguments, and from different users, into one cache entry.

Full Key Generation

The key has the form <base key>[:<user segment>][:<argument suffix>].
  • Base key: the key string, otherwise ModelName.methodName
  • User segment: the Context argument’s user if there is one, even outside a request; otherwise the current request user, only with scope: "user" inside a request
  • Key function: the returned value is used as-is; with scope: "user", :<user segment> is appended when the rule above yields a user segment. The function handles Context arguments itself

Direct Cache Manipulation

You can also manipulate the cache directly without decorators.
Decorator vs Direct Manipulation:
  • Decorator: Concise, declarative, automatic key generation
  • Direct Manipulation: Complex logic, conditional caching, fine-grained control

Cautions

@cache Decorator Cautions:
  1. Cache Manager Initialization Required: Error if no cache configuration in sonamu.config.ts
  2. Async Methods Only: Cannot be used with synchronous methods
  3. Store Name Matching: The store option must match names defined in configuration
  4. Serializable Values Only: Functions, Symbols, etc. cannot be cached
  5. Argument Order Matters: Same values in different order result in different keys
  6. Check Authorization Outside the Cache: On a cache hit the method body does not run, so authorization checks inside the body are skipped
    Putting a user ID in the cache key only separates cache entries; it does not authorize the caller. If the result depends on the requester (for example Sonamu.getContext().user), include that user’s ID in the cache key.

Next Steps

Cache Configuration

Configure Stores and Drivers

Cache Invalidation

Tag-based cache invalidation

Cache Strategies

TTL, Grace, Namespace usage