Appearance
MongoDB Scaling Strategies
Replica Sets (High Availability)
Architecture:
PRIMARY (read/write) ──┬──> SECONDARY (read replica)
│
├──> SECONDARY (read replica)
│
└──> SECONDARY (avoid arbiters: PSA sets hurt w:majority availability)Create replica set:
bash
# Tạo thư mục dữ liệu rồi chạy 3 mongod (nền)
mkdir -p /data/rs0-1 /data/rs0-2 /data/rs0-3
mongod --replSet rs0 --port 27017 --dbpath /data/rs0-1 --fork --logpath /data/rs0-1/mongod.log
mongod --replSet rs0 --port 27018 --dbpath /data/rs0-2 --fork --logpath /data/rs0-2/mongod.log
mongod --replSet rs0 --port 27019 --dbpath /data/rs0-3 --fork --logpath /data/rs0-3/mongod.logKhởi tạo replica set bằng mongosh (kết nối mongosh --port 27017):
javascript
// mongosh
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "localhost:27017" },
{ _id: 1, host: "localhost:27018" },
{ _id: 2, host: "localhost:27019" }
]
})
// Kiểm tra trạng thái
rs.status()Write Concerns (Durability vs Latency):
javascript
// mongosh
// w=1: chỉ primary ack (nhanh nhất, ít bền nhất; mặc định là w:"majority" từ MongoDB 5.0)
db.users.insertOne({ name: "An" }, { writeConcern: { w: 1 }})
// Rủi ro: primary hỏng trước khi replicate = mất ghi
// w="majority": đa số nút ack (nên dùng trên production)
db.users.insertOne({ name: "Binh" }, { writeConcern: { w: "majority" }})
// Rủi ro thấp: sống sót khi mất một nút (replica set 3 nút)
// w=3: cả 3 nút ack (bền nhất, chậm nhất)
db.users.insertOne({ name: "Chi" }, { writeConcern: { w: 3 }})
// Rủi ro khác: chỉ cần một nút chết là ghi không đủ ack, bị chặn tới wtimeout
// j=true: chờ journal ghi xuống đĩa
db.users.insertOne({ name: "Dung" }, { writeConcern: { w: "majority", j: true }})
// Độ trễ từng mức: đo trên cụm của bạn (đổi theo mạng và đĩa)Read Preferences (Availability vs Consistency):
javascript
// mongosh (chạy sau khối Write Concerns ở trên: collection users đã có dữ liệu)
// primary: Read from primary only (default, strongly consistent)
db.users.find().readPref("primary")
// Latency: Normal, Consistency: Strong
// primaryPreferred: Primary if available, else secondary
db.users.find().readPref("primaryPreferred")
// Latency: Normal, Consistency: Strong (if primary up)
// secondary: Read from secondary (eventual consistency)
db.users.find().readPref("secondary")
// Latency: Lower (if closer), Consistency: Eventual (may be stale)
// secondaryPreferred: Secondary first, then primary
db.users.find().readPref("secondaryPreferred")
// nearest: Lowest network latency (geo-distributed)
db.users.find().readPref("nearest")
// Best for: Read-heavy geo-distributed appsAutomatic Failover:
1. Primary crashes
2. Secondaries detect failure (heartbeat timeout ~10s)
3. Election (majority vote)
4. New primary elected (median typically ≤ ~12s with default settings)
5. Application reconnects automatically (driver handles it)Connection string with replica set:
text
mongodb://user:pass@host1:27017,host2:27018,host3:27019/mydb?replicaSet=rs0&readPreference=secondaryPreferredSharding (Horizontal Scalability)
When to shard:
- ✅ Working set > RAM (can't fit in memory)
- ✅ Storage > single server capacity (multi-TB)
- ✅ Throughput vượt một server (ngưỡng phụ thuộc phần cứng và workload; đo bằng benchmark của bạn)
- ❌ Don't shard prematurely (adds complexity)
Sharding architecture:
Application
↓
mongos (query router) ←──→ Config Servers (replica set)
↓ ↓
├──→ Shard 1 (replica set) ← Chunks 0-1000
├──→ Shard 2 (replica set) ← Chunks 1001-2000
└──→ Shard 3 (replica set) ← Chunks 2001-3000Shard key selection (CRITICAL):
1. Hashed shard key (even distribution)
javascript
// mongosh, chạy qua mongos (đã chạy OK: cụm 1 config + 2 shard + mongos)
sh.shardCollection("mydb.users", { userId: "hashed" })
// Pros: Even distribution, no hot shards
// Cons: No range queries (scatter-gather)2. Range shard key (range queries)
javascript
// mongosh, chạy qua mongos (đã chạy OK)
sh.shardCollection("mydb.events", { timestamp: 1, userId: 1 })
// Pros: Range queries hit 1 shard
// Cons: Hot shard (recent data on last shard)3. Compound shard key (balanced)
javascript
// mongosh, chạy qua mongos (compound hashed: đã chạy OK trên mongo:8)
sh.shardCollection("mydb.orders", { country: 1, userId: "hashed" })
// Pros: Even distribution + geo-locality
// Cons: More complexShard key characteristics:
- ✅ High cardinality: Many distinct values (not country)
- ✅ Even distribution: No hot shards
- ✅ Query isolation: Queries target 1 shard (not scatter-gather)
- ⚠️ Hard to change: refineCollectionShardKey (4.4+), full reshardCollection (5.0+)
Chunk balancing:
javascript
// mongosh, chạy qua mongos
// Chunks (ranges) default 128MB since 6.0; balancer balances by data size, not chunk count
// Balancer automatically migrates chunks between shards
// Check balancer status
sh.getBalancerState()
// Stop balancer (during maintenance)
sh.stopBalancer()
// Start balancer
sh.startBalancer()
// View chunk distribution
sh.status()Zone sharding (data locality):
javascript
// mongosh, chạy qua mongos. Thay tên shard bằng tên thật trong sh.status() (đã chạy OK với shard sh1, sh2)
// Zone cần shard key bắt đầu bằng trường country; khoá zone dùng cùng tiền tố đó
// Collection riêng cho ví dụ zone, shard theo country (khác mydb.users ở trên shard hashed theo userId)
sh.shardCollection("mydb.zones", { country: 1 })
sh.addShardToZone("shard0000", "US")
sh.addShardToZone("shard0001", "EU")
sh.updateZoneKeyRange("mydb.zones",
{ country: "US" }, { country: "US\xff" }, "US")
sh.updateZoneKeyRange("mydb.zones",
{ country: "UK" }, { country: "UK\xff" }, "EU")
// US users → shard0000 (US datacenter)
// UK users → shard0001 (EU datacenter)Phải nhớ:
- Dùng
w: "majority"cho dữ liệu quan trọng; tránh arbiter vì làm giảm khả năng ghi majority. - Đừng shard sớm; chọn shard key có cardinality cao, phân đều và khớp query (đổi sau bằng
reshardCollectiontừ 5.0, tốn tài nguyên). readPreference: secondarycó thể trả dữ liệu cũ; đo failover trên cụm của bạn (đo được 11,4 s trong Docker, mặc định election 10 s).