@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 insonamu.config.ts to use caching.
Without cache configuration, using
@cache will cause an error.Options
ttl
Specifies cache validity time.key
Specifies the cache key. Default:"{ModelName}.{methodName}:{serializedArgs}"
- Auto-generated (Default)
- Fixed Key
- Function Generator
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"
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.- 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
How Cache Works
1. Cache Hit
2. Cache Miss
3. Cache Refresh
Precautions
1. CacheManager Initialization Required
cache configuration in sonamu.config.ts
2. Argument Serialization
Complex objects are automatically JSON serialized: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.
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
- API Response Caching
- User Profile
- Aggregate Data
- Search Results
Next Steps
@api
Create API endpoints
@transactional
Use transactions
BentoCache
BentoCache official documentation
Performance Optimization
Performance optimization guide