@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
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.- 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
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: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
- 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