cacheLife Function
The cacheLife
function allows you to control how long a cache entry should live before it's automatically invalidated. This is useful for managing cache freshness and memory usage.
Basic Usage
async function fetchWeatherData(city: string) {
'use cache';
// Cache for 30 minutes
cacheLife('30m');
const weather = await weatherAPI.getForecast(city);
return weather;
}
Time Formats
You can specify the cache duration in multiple formats:
String Format
async function exampleWithStringTTL() {
'use cache';
// Common time units
cacheLife('5s'); // 5 seconds
cacheLife('1m'); // 1 minute
cacheLife('2h'); // 2 hours
cacheLife('1d'); // 1 day
return await fetchData();
}
Milliseconds
async function exampleWithMillisecondsTTL() {
'use cache';
// Direct milliseconds
cacheLife(60000); // 1 minute
cacheLife(3600000); // 1 hour
return await fetchData();
}
Example Use Cases
Short-lived Data
async function fetchLiveStats() {
'use cache';
// Cache for 5 seconds since data changes frequently
cacheLife('5s');
return await getLiveStats();
}
Long-lived Data
async function fetchStaticContent() {
'use cache';
// Cache for 1 day since content rarely changes
cacheLife('1d');
return await getStaticContent();
}
Dynamic TTL
async function fetchData(type: 'frequent' | 'rare') {
'use cache';
// Set TTL based on data type
cacheLife(type === 'frequent' ? '5m' : '1h');
return await getData(type);
}
Best Practices
-
Choose Appropriate Duration:
- Use shorter TTL for frequently changing data
- Use longer TTL for static content
- Consider your data update patterns
-
Balance Freshness and Performance:
- Don't cache too long if data changes often
- Don't cache too short if data is static
- Consider your application's needs
-
Monitor Cache Behavior:
- Watch for stale data issues
- Adjust TTL based on usage patterns
- Consider memory usage
Common Patterns
API Data
async function fetchWeatherData() {
'use cache';
// Weather data (changes every 30 minutes)
cacheLife('30m');
return await weatherAPI.getForecast();
}
async function fetchNewsData() {
'use cache';
// News data (changes every hour)
cacheLife('1h');
return await newsAPI.getLatest();
}
async function fetchStaticAPIData() {
'use cache';
// Static API data (changes daily)
cacheLife('1d');
return await staticAPI.getData();
}
Database Queries
async function fetchUserPreferences(userId: string) {
'use cache';
// User preferences (changes occasionally)
cacheLife('1h');
return await db.users.getPreferences(userId);
}
async function fetchGuildSettings(guildId: string) {
'use cache';
// Guild settings (changes rarely)
cacheLife('1d');
return await db.guilds.getSettings(guildId);
}
async function fetchSystemConfig() {
'use cache';
// System configuration (changes very rarely)
cacheLife('7d');
return await db.system.getConfig();
}