Usage Examples
Explore practical examples of how to use @humanspeak/memory-cache in real-world scenarios.
Basic Patterns
API Response Caching
Cache API responses to reduce network requests and improve response times.
Session Storage
Store user sessions with automatic expiration for secure session management.
Configuration Cache
Cache configuration that rarely changes for faster application startup.
Advanced Patterns
Database Query Caching
Cache expensive database queries with the @cached decorator.
Computed Value Caching
Cache expensive computations to avoid redundant processing.
Multi-Tenant Invalidation
Use prefix and wildcard deletion for multi-tenant applications.
Async Fetching
Handle async data fetching with automatic caching.
Async Decorator
Use @cached for async methods with single-flight calls and retry-safe errors.
Monitoring & Operations
Full Examples
Quick Reference
| Use Case | Recommended TTL | Max Size | Key Pattern |
|---|---|---|---|
| API responses | 1-5 minutes | 500-1000 | api:{endpoint} |
| User sessions | 30-60 minutes | 10000+ | session:{id} |
| Database queries | 30s-5 minutes | 100-500 | query:{table}:{id} |
| Computed values | 0 (no expiration) | 1000+ | compute:{input} |
| Rate limiting | 1 minute | 100000+ | ratelimit:{clientId} |
| Configuration | 5-10 minutes | 100 | config:{env} |
Best Practices
Choose appropriate TTLs
Balance freshness vs performance
Use meaningful key patterns
Makes debugging and invalidation easier
Consider cache size
Monitor memory usage in production
Use hooks for observability
Track hit rates and performance
Handle cache misses
Always have a fallback strategy