Databases & System Design•Part 5: Real-Time Architecture, Replication & Scale (51 - 60)
Database Sharding:
In Simple Words: Distributing data horizontally across multiple database servers by Hashing, Ranges, or Directory lookup.
typescript
// Hash-based shard routing function:
function getDatabaseShard(userId: string, totalShards = 4): string {
const hash = crypto.createHash('md5').update(userId).digest('hex');
const shardIndex = parseInt(hash.slice(0, 4), 16) % totalShards;
return `postgres://shard-${shardIndex}.internal:5432/app_db`;
}