Keeping a cache fresh against frequently changing source data requires a deliberate invalidation strategy, typically combining event-driven refresh with a time-to-live fallback so stale data never lingers indefinitely.
Key Points: • Event-driven invalidation refreshes or evicts a cache entry as soon as the underlying data changes, keeping reads accurate. • A time-to-live (TTL) policy acts as a safety net, expiring entries even if an invalidation event is missed. • Cache-aside patterns re-populate the cache lazily on the next read after eviction, spreading out load. • Write-through caching updates the cache and database together, avoiding a window of staleness entirely. • Choosing between these strategies balances data freshness against the added latency and complexity of tighter synchronization.
Example: An inventory service publishes a "stock updated" event whenever a database write occurs; a listener evicts the corresponding cache key immediately, while a five-minute TTL on all entries guards against any event that's dropped.
Interview Tip: A concise interview answer is:
"I'd combine event-driven cache invalidation, where a data update publishes an event that evicts the stale entry, with a TTL as a safety net in case an event is missed. That balances freshness with performance and avoids serving badly stale data to users."