Event-Based Invalidation
What you'll learn: How to use events or message queues to notify caches when data changes, enabling coordinated invalidation across distributed systems.
The Core Idea
Event-based invalidation uses a publish-subscribe messaging system to broadcast data change notifications. When data is updated in your database, you publish an event (like "User 123 updated") to a message queue or event bus. All cache layers that might store that data subscribe to these events and automatically invalidate their cached copies when they receive the notification.
This differs from active invalidation on write (which you learned previously) because the application doesn't directly call each cache—instead, it publishes one event, and caches listen independently.
How It Works
- Writer updates data in the database
- Writer publishes event to message queue (e.g., "product:456:updated")
- Cache subscribers receive event across different services or regions
- Each cache invalidates its local copy of product 456
- Next read fetches fresh data from the database
Real-World Analogy
Think of a fire alarm system. When smoke is detected (data change), one alarm triggers, and all speakers throughout the building (caches) hear it simultaneously and respond. The smoke detector doesn't need to know where every speaker is—it just broadcasts the alert.
Benefits and Tradeoffs
Advantages:
- Decouples cache invalidation from write logic
- Scales to many cache nodes without coordination
- Works across service boundaries
Challenges:
- Requires message queue infrastructure
- Events might be delayed or lost
- Eventual consistency (brief staleness possible)
Key Takeaway: Event-based invalidation uses message queues to broadcast data change notifications, allowing distributed caches to invalidate independently without tight coupling between writers and cache layers.