Best practice là dùng dấu hai chấm : làm separator để tạo namespace hierarchy, ví dụ: user:1001:profile, user:1001:session, product:sku:ABC123:stock.
- Các rule quan trọng: dùng tên có ý nghĩa và mô tả rõ object type + identifier + attribute (ví dụ:
order:order_id:status); tránh key quá dài (mỗi key đều tốn memory cho metadata overhead); tránh key quá ngắn khó đọc; thống nhất format trong toàn team và document lại. - Dùng
SCANthay vìKEYS *khi cần tìm key theo pattern vì KEYS block Redis;SCANiteration không block. - Đối với hot key (một key được access cực nhiều), có thể dùng local cache hoặc key sharding (
user:1001:profile:shard:3). - Một pattern hay là thêm version vào key namespace để dễ cache invalidation hàng loạt:
v2:user:1001:profile— khi cần invalidate tất cả, chỉ cần tăng version prefix.
The best practice is to use colons : as separators to create a namespace hierarchy, e.g., user:1001:profile, user:1001:session, product:sku:ABC123:stock.
- Key rules: use descriptive names that clearly indicate object type + identifier + attribute (e.g.,
order:order_id:status); avoid overly long keys (every key incurs memory overhead for metadata); avoid overly short keys that are hard to read; agree on a consistent format across the team and document it. - Use
SCANinstead ofKEYS *when searching for keys by pattern, sinceKEYSblocks Redis;SCANis iterative and non-blocking. - For hot keys (accessed extremely frequently), consider local caching or key sharding (
user:1001:profile:shard:3). - A useful pattern is adding a version to the namespace for bulk cache invalidation:
v2:user:1001:profile— to invalidate everything, simply increment the version prefix.