@cache decorator to automatically cache the results of Model or Frame methods.
Basic Usage
Simple Example
- First call: DB query → Cache result
- Second call (within 10 minutes): Return from cache (no DB query)
- 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.- Auto-generated (Default)
- String Key
- Function Key
ModelName.methodName:serializedArgsArgument Serialization Rules:- Single primitive (string/number/boolean): Used as-is
- Complex objects: Uses JSON.stringify
- No arguments:
ModelName.methodNamewithout suffix
ttl: Expiration Time
TTL (Time To Live) is the duration the cache remains valid.grace: Stale-While-Revalidate
Grace period is a feature that returns stale cache after TTL expiration while refreshing in the background.- 0~1 minute: Return fresh cache
- 1~11 minutes: Immediately return stale cache + background refresh
- After 11 minutes: Cache miss, recalculate
- 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.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.Practical Examples
1. API Response Caching
2. Cache Invalidation on Data Change
3. Complex Key Generation
4. Using Stale-While-Revalidate
- 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.Cache Key Generation Logic
Argument Serialization
Full Key Generation
Direct Cache Manipulation
You can also manipulate the cache directly without decorators.- Decorator: Concise, declarative, automatic key generation
- Direct Manipulation: Complex logic, conditional caching, fine-grained control