MongoDB & NoSQL (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
Shard Key Selection: Avoiding Hotspots.
senior LevelmongodbAdvanced Internals
In Simple Words: The Shard Key determines which shard stores a document:
- Monotonically Increasing Keys (e.g.
_idortimestamp) (Anti-pattern): All new writes go exclusively to the highest shard chunk, creating a massive single-shard bottleneck! - Hashed Shard Key (
{ _id: 'hashed' }): Distributes writes randomly and evenly across all shards, though range queries must fan-out to all shards. - Compound Shard Key (
{ tenant_id: 1, created_at: 1 }): Optimal pattern for multi-tenant SaaS applications.