Sharding là chia ngang dữ liệu ra nhiều server, mỗi shard giữ một phần — để vượt giới hạn của một máy. Đây là giải pháp nặng đô, chỉ dùng khi thật sự cần.
Quyết định quan trọng nhất là chọn shard key, vì chọn sai gây hot spot (một shard ôm phần lớn traffic):
- Hash theo user_id: phân bố đều, nhưng query theo khoảng kém hiệu quả.
- Range (user 1-1M ở shard 1...): query khoảng tốt nhưng dễ hot spot.
- Lấy timestamp làm key cho time-series: mọi ghi dồn vào shard mới nhất → hotspot tuần tự; khắc phục bằng thêm hậu tố ngẫu nhiên hoặc hash.
Mặt khó: thêm shard phải phân bố lại dữ liệu (tốn thời gian, rủi ro downtime — consistent hashing giúp giảm); JOIN xuyên shard không hỗ trợ sẵn, phải join ở tầng app (scatter-gather), chậm và phức tạp.
Điểm chốt: trước khi sharding hãy thử hết các cách rẻ hơn — nâng cấu hình máy (vertical scaling), read replica, thêm cache (Redis), partition bảng trên cùng máy, archive dữ liệu cũ. Chỉ shard khi dataset thực sự quá lớn (thường > 1-2TB hoặc throughput ghi vượt một master.
Sharding splits data horizontally across multiple servers, with each shard holding a portion — to go beyond a single machine's limit. It's a heavyweight solution, used only when truly needed.
The most important decision is choosing the shard key, because a bad choice causes a hot spot (one shard takes most of the traffic):
- Hash by user_id: even distribution, but range queries are inefficient.
- Range (users 1-1M on shard 1...): good for range queries but prone to hot spots.
- Using a timestamp as the key for time-series: all writes pile onto the newest shard → a sequential hotspot; fix with a random suffix or hashing.
Hard parts: adding a shard means redistributing data (slow, downtime risk — consistent hashing reduces this); cross-shard JOINs aren't native, so you join in the app layer (scatter-gather), which is slow and complex.
Key point: before sharding, exhaust the cheaper options — a bigger machine (vertical scaling), read replicas, a cache (Redis), table partitioning on the same machine, archiving old data. Only shard when the dataset is genuinely too large (typically > 1-2TB or write throughput exceeds a single master).