Cache invalidation là bài toán khó nổi tiếng (Phil Karlton: 'there are only two hard things in Computer Science: cache invalidation and naming things').
- Các chiến lược: TTL-based expiration: đơn giản nhất — set TTL phù hợp, data stale tối đa TTL seconds.
- Phù hợp cho data có freshness requirement rõ ràng. Event-driven invalidation: khi data trong DB thay đổi, publish event → subscriber DEL cache key tương ứng ngay.
- Dùng Debezium CDC hoặc domain events.
- Chính xác hơn TTL nhưng phức tạp hơn. Write-through invalidation: khi write DB, đồng thời DELETE hoặc SET cache mới. Versioned keys: thêm version vào cache key (
product:123:v5), khi update thì tăng version — key cũ tự expire theo TTL; không cần explicit invalidation. Cache tags (advanced): nhóm nhiều cache key theo tag (tag:category:electronics), khi category thay đổi thì invalidate tất cả key có tag đó — Redis không native support, cần implement bằng Set lưu list key per tag. - Thực tế: kết hợp short TTL (30-60s) + event invalidation để balance freshness và complexity.