Why Invalidation is Needed
Caching improves performance, but can return stale data.Invalidation Methods
1. Delete Specific Key
The most basic method.2. Tag-based Invalidation (Recommended)
Using tags, you can delete related caches as a group.findById() and findAll() caches are deleted
3. Delete Multiple Keys
4. Clear All Cache
Tag Strategies
Hierarchical Tag Design
Selective Invalidation
Dynamic Tags
Dynamically create tags that only affect specific entities.@cache decorator only supports static tags. For dynamic tags, you need to manipulate the cache directly:
Practical Examples
1. Post + Comment Invalidation
2. User + Permission Invalidation
3. Category Hierarchy
4. Aggregate Data Invalidation
Isolation with Namespace
Using Namespace, you can isolate cache per user, per tenant.Per-User Cache
Multi-Tenant
Invalidation Strategies
1. Eager Invalidation (Immediate Invalidation)
Delete cache immediately when data changes.- Simple and clear
- No stale data
- Reduced hit rate due to frequent cache deletion
2. Lazy Invalidation (Delayed Invalidation)
Rely on TTL for automatic expiration.- High cache hit rate
- Simple code
- Potentially stale data for up to 5 minutes
3. Hybrid
Immediate invalidation for important changes, TTL for minor changes:4. Write-Through (Update on Write)
Update cache instead of deleting.- Cache always up-to-date
- High hit rate
- Complex cache key management
- Write performance degradation
Invalidation in Distributed Environment
Synchronization with Bus
When you have multiple servers, using Bus propagates invalidation to all servers.Using Without Bus
Without Bus, each server’s L1 is independent:- Add Bus (recommended)
- Use only L2 without L1 (slower)
- Use short TTL (accept stale data)