What Is Database Sharding? Partitioning Explained

By Published 10 min read

What Is Database Sharding? Partitioning Explained

Introduction:

Imagine a library with one librarian and one huge shelf. When the library is small, everything works. But as it grows to millions of books and thousands of visitors a day, the single shelf overflows and the queue in front of the one librarian goes out the door. Buying a bigger shelf and hiring a faster librarian only helps for so long.

The real fix is to split the library: books A to F in one room with its own librarian, G to M in another, and so on. Each room is smaller, faster, and can serve visitors at the same time as the others.

Databases face exactly the same problem. A single database server has a limit on how much data it can store, how many queries it can answer per second, and how many writes it can handle. Partitioning and sharding are the techniques for splitting the data so that no single piece has to do everything.

In this lesson we will learn the difference between partitioning and sharding, the main sharding strategies (range, hash, consistent hashing and directory-based), how to choose a shard key, and the real costs: cross-shard queries, transactions and resharding. It builds on our lessons on load balancers, caching, the CAP theorem and hash tables.

The SQL examples were run on PostgreSQL 16, and the JavaScript simulations were run with Node.js. The comments show the real output.

Part 1: The Basics

1. Scaling Up vs Scaling Out:

When a database gets slow, the first option is vertical scaling (scaling up): buy a bigger machine with more CPU, RAM and faster disks. It is simple and needs no code changes, and you should always try it first. But it has a ceiling, the price grows very quickly near the top, and it is still one machine that can fail.

The second option is horizontal scaling (scaling out): use more machines. For read-heavy apps, the first step is usually read replicas: copies of the database that serve reads, while one primary handles all writes. But replicas don’t help when:

  • the data is too big for one machine, or
  • there are too many writes for one primary to handle.

That is when you need to split the data itself.

2. Partitioning vs Sharding:

These two words are often used loosely, so let’s be precise:

  • Partitioning means splitting one big table into smaller pieces called partitions. Often they all live on the same database server.
  • Sharding means putting those pieces on different database servers, called shards. Each shard holds part of the data and runs independently.

So sharding is horizontal partitioning across machines. Every shard has the same table structure (schema), but different rows.

There are also two directions you can split a table:

  • Horizontal partitioning splits by rows. Users 1 to 1 million in one piece, the rest in another. This is what sharding uses.
  • Vertical partitioning splits by columns. For example, keep id, name, email in a users table and move the large, rarely-read bio and profile_photo columns to a user_profiles table. This keeps the hot table small and fast.

Part 2: Partitioning in One Database

3. Range Partitioning in PostgreSQL:

Before reaching for multiple servers, it’s worth knowing that modern databases can partition a table for you. Here, an orders table is split by year:

CREATE TABLE orders (
  id         bigint,
  user_id    bigint NOT NULL,
  amount     numeric(10,2),
  created_at date NOT NULL
) PARTITION BY RANGE (created_at);

CREATE TABLE orders_2025 PARTITION OF orders
  FOR VALUES FROM ('2025-01-01') TO ('2026-01-01');
CREATE TABLE orders_2026 PARTITION OF orders
  FOR VALUES FROM ('2026-01-01') TO ('2027-01-01');

INSERT INTO orders VALUES
  (1, 10, 499.00, '2025-03-14'),
  (2, 11, 120.50, '2025-11-02'),
  (3, 10, 999.00, '2026-02-20'),
  (4, 12,  75.25, '2026-11-29');

Your application still reads and writes the single orders table. PostgreSQL decides which partition each row goes into:

SELECT tableoid::regclass AS partition, id, created_at FROM orders ORDER BY id;

--   partition  | id | created_at
-- -------------+----+------------
--  orders_2025 |  1 | 2025-03-14
--  orders_2025 |  2 | 2025-11-02
--  orders_2026 |  3 | 2026-02-20
--  orders_2026 |  4 | 2026-11-29

The big benefit is partition pruning. When a query filters on the partition key, PostgreSQL skips the partitions that can’t contain matching rows:

EXPLAIN (COSTS OFF) SELECT * FROM orders WHERE created_at >= '2026-01-01';

--  Seq Scan on orders_2026 orders
--    Filter: (created_at >= '2026-01-01'::date)

Only orders_2026 is scanned. With ten years of data, that’s a tenth of the work. Old data is also easy to manage: archiving 2025 means detaching or dropping one partition, which is far faster than deleting millions of rows.

One thing to plan for: a row that fits no partition is rejected.

INSERT INTO orders VALUES (5, 13, 10.00, '2027-01-05');
-- ERROR:  no partition of relation "orders" found for row
-- DETAIL:  Partition key of the failing row contains (created_at) = (2027-01-05).

You must create future partitions ahead of time (usually with a scheduled job), or add a DEFAULT partition to catch everything else.

Partitioning on one server makes big tables easier to manage and query, but the data, the CPU and the writes are still on one machine. For that, we need sharding.

Part 3: Sharding Strategies

With sharding, every row must go to exactly one shard, and later we must be able to find it again. The column used to decide is called the shard key (or partition key). The strategy is the rule that turns a shard key into a shard.

4. Range-Based Sharding:

The simplest rule is to split by ranges of the key, like the library rooms A to F, G to M:

function rangeShard(userId) {
  if (userId <= 25000) return 0;
  if (userId <= 50000) return 1;
  if (userId <= 75000) return 2;
  return 3;
}

Range sharding is easy to understand and makes range queries cheap. “All users with IDs 1,000 to 2,000” lives on one shard.

But it has a serious weakness: hotspots. IDs usually grow over time, so all new users land on the last shard. We simulated 10,000 new signups (users 90,001 to 100,000):

// writes per shard for new signups
range sharding: [ 0, 0, 0, 10000 ]

Shard 3 receives every new write while the other three sit idle. The same thing happens if you shard by date: today’s shard does all the work. Range sharding works best when access is spread evenly across the ranges, such as sharding by country or by the first letter of a username.

5. Hash-Based Sharding:

To spread data evenly, hash the shard key and use the remainder to pick a shard. A good hash function turns similar keys (like 41, 42, 43) into completely different numbers:

const crypto = require("node:crypto");

function hash(key) {
  return crypto.createHash("md5").update(String(key)).digest().readUInt32BE(0);
}

function shardFor(userId, shardCount) {
  return hash(userId) % shardCount;
}

console.log(shardFor(42, 4), shardFor(1001, 4), shardFor(7, 4));   // 0 3 3

We placed 100,000 users and then the same 10,000 new signups:

all users per shard:   [ 25077, 25249, 24728, 24946 ]
new signups per shard: [ 2567, 2632, 2373, 2428 ]

Both the data and the new writes are now spread almost perfectly evenly. This is why hash sharding is the most common default.

The trade-off: range queries become expensive. Users 1,000 to 2,000 are now scattered across all shards, so a range query must ask every shard.

6. The Resharding Problem:

Hash sharding with hash % shardCount hides a nasty surprise. What happens when the four shards fill up and we add a fifth?

let moved = 0;
for (let id = 1; id <= 100000; id++) {
  if (shardFor(id, 4) !== shardFor(id, 5)) moved++;
}
console.log(moved);   // 79820  (79.8%)

Changing % 4 to % 5 changes the answer for almost 80% of the users. That means moving four-fifths of all your data between servers, while the app is running, just to add one machine. In general, going from N to N+1 shards moves about N/(N+1) of the keys.

7. Consistent Hashing:

Consistent hashing solves this. Imagine the hash values arranged on a ring. Each shard is placed at several points on the ring (called virtual nodes), and each key belongs to the first shard point found going clockwise from the key’s own hash:

class HashRing {
  constructor(vnodes = 100) {
    this.vnodes = vnodes;
    this.ring = [];                   // sorted list of { pos, name }
  }

  addShard(name) {
    for (let i = 0; i < this.vnodes; i++) {
      this.ring.push({ pos: hash(`${name}#${i}`), name });
    }
    this.ring.sort((a, b) => a.pos - b.pos);
  }

  removeShard(name) {
    this.ring = this.ring.filter((p) => p.name !== name);
  }

  shardFor(key) {
    const h = hash(key);
    // binary search for the first point at or after h
    let lo = 0, hi = this.ring.length;
    while (lo < hi) {
      const mid = (lo + hi) >> 1;
      if (this.ring[mid].pos < h) lo = mid + 1;
      else hi = mid;
    }
    return this.ring[lo % this.ring.length].name;   // wrap around the ring
  }
}

With four shards and 100,000 users, the data is still well balanced:

{ 'shard-D': 25402, 'shard-C': 26146, 'shard-B': 24080, 'shard-A': 24372 }

Now we add a fifth shard and count how many users change shard:

ring.addShard("shard-E");
// moved: 20549 (20.5%), and every one of them moved to shard-E

Only about one fifth of the users moved, which is the minimum possible (shard-E needs its fair share), and all of them moved to the new shard. No data was shuffled between the old shards. Compare that with 79.8% using plain modulo.

The virtual nodes are important. With only one point per shard, the gaps on the ring would be uneven and one shard could get twice as much data as another. A hundred points per shard smooths that out. They also let you give a more powerful server more points, so it takes more data.

Consistent hashing is used by Amazon DynamoDB, Apache Cassandra, Riak, many caching layers, and CDNs.

8. Directory-Based Sharding:

The last strategy keeps an explicit lookup table that says where each key lives. It is common in multi-tenant SaaS apps, where each customer (tenant) is assigned to a shard:

const tenantShard = new Map([
  ["acme", "shard-1"],
  ["globex", "shard-1"],
  ["bigcorp", "shard-2"],
]);

function shardForTenant(tenant) {
  const shard = tenantShard.get(tenant);
  if (!shard) throw new Error(`Unknown tenant: ${tenant}`);
  return shard;
}

console.log(shardForTenant("acme"), shardForTenant("bigcorp"));  // shard-1 shard-2

// bigcorp grew huge, so give it a shard of its own
tenantShard.set("bigcorp", "shard-3");
console.log(shardForTenant("bigcorp"));                          // shard-3

This is the most flexible strategy: you can place any key anywhere, move a single big customer to its own server, and rebalance one tenant at a time. The cost is that the directory itself must be stored somewhere fast and reliable, is read on every request (so it is usually cached), and becomes a critical component: if it is wrong or unavailable, nothing can be found.

Part 4: Living with Shards

9. Choosing a Shard Key:

The shard key is the most important decision in a sharded system, and it is very hard to change later. A good shard key:

  • Has many distinct values (high cardinality). Sharding by country gives you at most ~200 shards, and one country might hold half your users. user_id gives millions of values.
  • Spreads load evenly. Avoid keys that concentrate traffic, like a timestamp or an auto-increment ID with range sharding, or a celebrity’s ID in a social network.
  • Matches your most common queries. If almost every query is “for this user”, sharding by user_id means each query touches exactly one shard. If you shard orders by order_id instead, “show this user’s orders” must ask every shard.
  • Keeps related data together. Store a user’s orders, addresses and cart on the same shard as the user (all sharded by user_id), so you can join them locally.

10. Cross-Shard Queries (Scatter-Gather):

Queries that include the shard key are fast and simple. Here are six orders sharded by userId:

const shards = [[], [], [], []];
for (const o of orders) shards[shardFor(o.userId, 4)].push(o);
console.log(shards.map((s) => s.map((o) => o.id)));
// [ [ 1, 4, 5 ], [], [ 6 ], [ 2, 3 ] ]

const ordersForUser = (userId) =>
  shards[shardFor(userId, 4)].filter((o) => o.userId === userId);

console.log(ordersForUser(42));
// [ { id: 1, userId: 42, amount: 499 }, { id: 4, userId: 42, amount: 75 } ]

Only one shard was asked. But a query like “the three biggest orders across the whole shop” has no shard key, so we must ask every shard and merge the results. This is called scatter-gather:

async function topOrders(n) {
  // scatter: each shard returns its own top n (in parallel)
  const partial = await Promise.all(
    shards.map(async (s) => [...s].sort((a, b) => b.amount - a.amount).slice(0, n))
  );
  // gather: merge and take the overall top n
  return partial.flat().sort((a, b) => b.amount - a.amount).slice(0, n);
}

topOrders(3).then((r) => console.log(r.map((o) => `#${o.id} ₹${o.amount}`)));
// [ '#3 ₹999', '#6 ₹640', '#1 ₹499' ]

Notice that each shard only sends its top 3, not all its rows. Even so, scatter-gather is as slow as the slowest shard, and its cost grows with the number of shards. For reporting and analytics, most companies copy data from all shards into a separate data warehouse instead of querying the shards directly.

11. The Hard Parts:

Sharding solves scale problems but creates new ones. Know them before you start:

  • Joins across shards are no longer done by the database. You either keep related data on the same shard, denormalise (copy) some data, or join in application code.
  • Transactions across shards lose the simple ACID guarantees of one database. Moving money between two users on different shards needs patterns like two-phase commit or sagas, which are complex and slower.
  • Unique IDs can’t come from one auto-increment counter any more. Systems use UUIDs or ID generators like Twitter’s Snowflake, which build a unique ID from a timestamp, a machine ID and a counter.
  • Resharding (adding shards or moving data) must happen while the app is live, usually by copying data in the background, writing to both places for a while, and then switching reads over.
  • Operations multiply. Ten shards means ten databases to back up, monitor, upgrade and keep replicated. Each shard normally has its own replicas for high availability.

12. When Should You Shard?:

Sharding is powerful but should usually be the last step, not the first. A sensible order is:

  • Optimise first: add the right indexes, fix slow queries, and remove N+1 query patterns.
  • Cache hot reads in Redis or a CDN.
  • Scale up to a bigger database server.
  • Add read replicas for read-heavy traffic.
  • Partition large tables inside one database for easier management.
  • Shard when the data or the write traffic truly no longer fits on one primary.

Many very large products ran on a single well-tuned primary database with replicas for years. When you do need sharding, consider databases that do it for you, such as Vitess and Citus (for MySQL and PostgreSQL), MongoDB, Cassandra, DynamoDB, CockroachDB, YugabyteDB or Google Spanner, before building it yourself.

Conclusion:

Partitioning splits a big table into smaller pieces, and sharding puts those pieces on different servers so you can grow beyond one machine. We saw PostgreSQL range partitioning with partition pruning, then compared sharding strategies: range sharding is simple but creates hotspots, hash sharding spreads load evenly but moved 79.8% of keys when adding one shard, consistent hashing cut that to 20.5%, and directory-based sharding gives full control at the cost of a lookup service. We also learned how to choose a shard key and what sharding costs in cross-shard queries, transactions and operations.

In the next system design lesson we will put these ideas together and design a URL shortener like bit.ly, from the API to the database and caching.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume