Skip to main content
To manage caches effectively, you need to invalidate them at appropriate times. Sonamu provides various invalidation methods.

Why Invalidation is Needed

Caching improves performance, but can return stale data.
Solution: Invalidate related cache when data changes

Invalidation Methods

1. Delete Specific Key

The most basic method.
Problem: Must know the exact key and delete all related caches individually Using tags, you can delete related caches as a group.
Result: Both findById() and findAll() caches are deleted

3. Delete Multiple Keys

4. Clear All Cache

Caution: Use carefully in production

Tag Strategies

Hierarchical Tag Design

Selective Invalidation

Dynamic Tags

Dynamically create tags that only affect specific entities.
Note: BentoCache’s @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.
Advantages:
  • Simple and clear
  • No stale data
Disadvantages:
  • Reduced hit rate due to frequent cache deletion

2. Lazy Invalidation (Delayed Invalidation)

Rely on TTL for automatic expiration.
Advantages:
  • High cache hit rate
  • Simple code
Disadvantages:
  • 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.
Advantages:
  • Cache always up-to-date
  • High hit rate
Disadvantages:
  • 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.
How It Works:

Using Without Bus

Without Bus, each server’s L1 is independent:
Problem:
Solutions:
  1. Add Bus (recommended)
  2. Use only L2 without L1 (slower)
  3. Use short TTL (accept stale data)

Monitoring

Check Cache Key

Check Before Tag Invalidation

You cannot check affected keys before invalidation, but consistent tag usage makes it predictable.

Cautions

Cache Invalidation Cautions:
  1. Avoid Excessive Invalidation: Too frequent invalidation reduces cache effectiveness
  2. Maintain Tag Consistency: Consistent tag usage ensures accurate invalidation
  3. Prevent Circular Invalidation: If A invalidates B and B invalidates A, infinite loop occurs
  4. Bus Required in Distributed Environment: Operating multiple servers without Bus causes inconsistency

Next Steps

Cache Configuration

Configure Stores and Drivers

@cache Decorator

Apply caching to methods

Cache Strategies

TTL, Grace, Namespace usage