Belajar
← All lessons

How database sharding works

Route a row to its shard

App
Router
Shards

router.js

// the router picks a shard from the key aloneconst shardFor = (userId) => shards[murmur3(userId) % shards.length]; async function insertUser(user) {  const db = shardFor(user.id);  await db.query("INSERT INTO users VALUES ($1, $2)", [user.id, user.name]);} async function getUser(id) {  return shardFor(id).query("SELECT * FROM users WHERE id = $1", [id]);} // no shard key: ask everyone, merge the answersasync function findByName(name) {  const parts = await Promise.all(shards.map((db) =>    db.query("SELECT * FROM users WHERE name = $1", [name])));  return parts.flatMap((p) => p.rows);}

Range vs hash insert rows, watch where they land

Shard user_id byrangehash
Shards3
Rows per shard

shard.js

// range: 50 ids per shard, the last one takes the restfunction rangeShard(id, shards) {  return Math.min(Math.floor((id - 1) / 50), shards - 1);} // hash: scramble the id, then take it modulo the shard countfunction hashShard(id, shards) {  return murmur3(id) % shards;}

One shard or all of them cross-shard queries

Query on users, sharded by user_id across 4 shardsby idby namenewest 10with orders

queries.sql

-- has the shard key: one shardSELECT * FROM users WHERE id = 7; -- no shard key: every shardSELECT * FROM users WHERE name = 'Dewi';SELECT * FROM users ORDER BY created_at DESC LIMIT 10; -- orders sharded by user_id too: still one shardSELECT * FROM users u JOIN orders o ON o.user_id = u.idWHERE u.id = 7;

Topics

Next: How connection pooling works

Open lesson