Cache with support for:
- Stale-While-Revalidate (SWR): Serve stale data while refreshing in the background
- TTL per entry: Override TTL on a per-key basis
- Pluggable adapters: Memory, Redis (ioredis/bun-redis), or tiered caching
- Type-safe: Full TypeScript inference
Installation
Basic Usage
Cache Options
TTL (Time to Live)
How long cached values remain fresh:SWR (Stale-While-Revalidate)
After TTL expires, serve stale data while refreshing in the background:- 0-5 min: Fresh value served
- 5-15 min: Stale value served, background refresh triggered
- 15+ min: Wait for fresh value (cache expired)
Lookup Function
The function that fetches values on cache miss:- The value directly:
Value - A cache entry with custom TTL:
Cache.entry(value, { ttl, swr })
Cache Instance API
get(key)
Retrieve a value from the cache:
lookup(key) and stores the result.
invalidate(key)
Remove a single key:
invalidateAll
Clear all cached entries:
Per-Entry TTL
Override TTL and SWR for specific entries:SWR Example
Cache Adapters
By default,Cache.make() uses in-memory storage. Add persistence with adapters:
Memory Adapter (Default)
Redis Adapter
See Cache with ioredis or Cache with bun-redis.Tiered Adapter
Combine L1 (memory) and L2 (Redis) for optimal performance:- Check L1 (memory) first
- If miss, check L2 (Redis)
- On write, update both L1 and L2