Cache Invalidation
Vấn đề
Khi dữ liệu gốc thay đổi (ví dụ: user cập nhật profile), cache vẫn giữ dữ liệu cũ. Cache invalidation xóa các entries cũ để giữ cache đồng bộ với database.
"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
Cách hoạt động
1. Database thay đổi → User cập nhật profile
2. Ứng dụng thông báo cache → Invalidate "user:123"
3. Cache xóa entry cũ
4. Lần đọc tiếp → Cache miss → Lấy từ DB → Cập nhật cacheInvalidationManager
InvalidationManager cung cấp invalidation dựa trên sự kiện:
typescript
import { InvalidationManager } from "distributed-cache";
const invalidator = new InvalidationManager();
// Set TTL cho key (tự hết hạn sau 60 giây)
invalidator.setTTL("user:123", 60000);
// Kiểm tra key còn hợp lệ không
const isValid = invalidator.checkTTL("user:123"); // true hoặc false
// Xóa thủ công key
invalidator.invalidate("user:123");Invalidation dựa trên sự kiện
Theo dõi các sự kiện invalidation:
typescript
import { InvalidationManager } from "distributed-cache";
const invalidator = new InvalidationManager();
// Đăng ký sự kiện
invalidator.subscribe((event) => {
console.log(`Cache invalidated: ${event.type} - ${event.key}`);
// Các loại: KEY_UPDATED, KEY_DELETED, KEY_EXPIRED
});
// Khi database thay đổi
invalidator.onDatabaseChange({
type: "KEY_DELETED",
key: "user:123",
timestamp: Date.now(),
});Wildcard Invalidation
Xóa nhiều key cùng lúc:
typescript
// Xóa tất cả user sessions
node.delete("session:user:1001");
node.delete("session:user:1002");
node.delete("session:user:1003");
// Hoặc dùng pattern matching
const keys = node.getKeys();
keys
.filter((k) => k.startsWith("session:"))
.forEach((k) => node.delete(k));Tích hợp với CacheNode
typescript
import { CacheNode } from "distributed-cache";
const node = new CacheNode("node-1", {
maxSize: 10000,
onEvicted: (key) => {
// Gọi khi entry bị evict (LRU/LFU/FIFO)
console.log(`Entry evicted: ${key}`);
},
});
// Lưu với TTL
node.set("user:123", userData, 60000); // hết hạn sau 60s
// Xóa thủ công
node.delete("user:123");
// Xóa tất cả entries
node.clear();Thực hành tốt nhất
| Thực hành | Tại sao |
|---|---|
| Set TTL cho tất cả entries | Ngăn dữ liệu cũ tồn tại quá lâu |
| Dùng invalidation dựa trên sự kiện | Đồng bộ real-time với database |
| Invalidate khi ghi qua cache | Cập nhật cache khi DB thay đổi |
| Batch invalidation | Giảm overhead network |
| Theo dõi hit rate | Hit rate thấp = quá nhiều invalidation |