Trung BìnhRedis iconRedis

Key naming conventions trong Redis: best practices để tổ chức namespace?

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 SCAN thay vì KEYS * khi cần tìm key theo pattern vì KEYS block Redis; SCAN iteration 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.

Xem toàn bộ Redis cùng filter theo level & chủ đề con.

Mở danh sách Redis