Skip to lesson

Sharding and partitioning (concept)

ShopLite's orders table is huge and one server cannot take all the writes. Replicas do not help writes, so the data itself must be split, which is powerful and costly.

Your turn: split the orders

ShopLite now has 60 million orders and the primary has reached its write limit. You decide to split the orders over 4 servers. Think about three questions:

  • What would you split by, so that "my orders" touches only one server?
  • With the rule "user id mod 4", what happens to the rows when a fifth server is added?
  • Which ShopLite question would now have to ask every server?

Partitioning vs sharding

Sharding splits one dataset across several database servers called shards, each holding part of the data, so storage and write capacity grow with the number of servers.

Partitioning splits a table inside one server. This SQL creates monthly partitions and drops the oldest month.

SQL
CREATE TABLE order_archive (  order_id    INT      NOT NULL,  customer_id INT      NOT NULL,  ordered_at  DATETIME NOT NULL,  PRIMARY KEY (order_id, ordered_at)   -- the partition column must be in every unique key)PARTITION BY RANGE COLUMNS (ordered_at) (  PARTITION p2026_09 VALUES LESS THAN ('2026-10-01'),  PARTITION p2026_10 VALUES LESS THAN ('2026-11-01'),  PARTITION pmax     VALUES LESS THAN (MAXVALUE));ALTER TABLE order_archive DROP PARTITION p2026_09;   -- removes a month at once

Example 1 · Monthly partitions: read one month, drop one month

PartitionByMonthDemo.javaJava
import java.time.LocalDate;import java.time.YearMonth;import java.util.ArrayList;import java.util.List;import java.util.TreeMap;
public class PartitionByMonthDemo {    record Order(int id, LocalDate orderedOn, int amount) { }
    public static void main(String[] args) {        // One table, split into monthly partitions inside the same database        TreeMap<YearMonth, List<Order>> partitions = new TreeMap<>();        LocalDate day = LocalDate.of(2026, 1, 1);        for (int id = 1; id <= 3_650; id++) {            Order o = new Order(id, day.plusDays(id / 12), 500 + id % 900);            partitions.computeIfAbsent(YearMonth.from(o.orderedOn()), k -> new ArrayList<>()).add(o);        }        System.out.println("Partitions: " + partitions.size() + " (" + partitions.firstKey() + " to " + partitions.lastKey() + ")");
        // WHERE ordered_on BETWEEN '2026-10-01' AND '2026-10-31' -> only one partition is read        List<Order> october = partitions.get(YearMonth.of(2026, 10));        System.out.println("October report reads 1 partition: " + october.size() + " rows, not all 3650");
        // Removing a whole old month is one cheap step, not millions of DELETEs        List<Order> dropped = partitions.remove(YearMonth.of(2026, 1));        System.out.println("Dropped partition 2026-01 with " + dropped.size() + " rows; " + partitions.size() + " left");    }}
Output
Partitions: 11 (2026-01 to 2026-11)
October report reads 1 partition: 372 rows, not all 3650
Dropped partition 2026-01 with 371 rows; 10 left

What this code does

  • Each order goes into the partition for its month, like PARTITION BY RANGE COLUMNS (ordered_at).
  • The October report reads only October's 372 rows. Dropping January removes 371 rows in one step instead of 371 DELETEs.

Partitioning splits one table into parts inside the same MySQL server, here one partition per month of ordered_at. Queries that filter on the partition column read only the matching parts (partition pruning), and old months can be dropped in one quick step. It is still one server, so it adds no CPU, memory or write capacity.

Sharding splits the data across separate servers; each shard holds some of the users and all of their orders. The shards together have more storage and write capacity than any one machine. The price is that the application (or a proxy such as Vitess) must know which shard holds which row.

Predict the output

Partitioning or sharding?

Pick the technique that fits each situation.

Round 1 of 2

A log table holds 2 TB on one server.
The team must delete the oldest month every night, fast.
MySQL does not allow foreign keys on partitioned InnoDB tables, which is one reason partitioning is used mostly for large append-only tables such as logs and archives.

Choosing a shard key: hash vs range, and hot shards

A shard key is the column whose value decides which shard a row lives on, such as customer_id for ShopLite orders.

Range sharding gives each shard a block of ids; hash sharding spreads ids by their hash. This program places 20,000 new users with both rules.

Example 2 · Range key vs hash key for today's new users

ShardKeyDemo.javaJava
import java.util.Arrays;
public class ShardKeyDemo {    static final int SHARDS = 4;
    static int hash(String key) {        int h = 0x811C9DC5;        for (char c : key.toCharArray()) {            h ^= c;            h *= 0x01000193;        }        h ^= h >>> 16;        h *= 0x85EBCA6B;        h ^= h >>> 13;        h *= 0xC2B2AE35;        h ^= h >>> 16;        return h;    }
    static int rangeShard(int userId) {        return Math.min((userId - 1) / 250_000, SHARDS - 1);    }
    static int hashShard(int userId) {        return Math.floorMod(hash("user:" + userId), SHARDS);    }
    public static void main(String[] args) {        int[] byRange = new int[SHARDS];        int[] byHash = new int[SHARDS];        for (int id = 980_001; id <= 1_000_000; id++) {            byRange[rangeShard(id)]++;            byHash[hashShard(id)]++;        }        System.out.println("New users per shard, range key: " + Arrays.toString(byRange));        System.out.println("New users per shard, hash key:  " + Arrays.toString(byHash));    }}
Output
New users per shard, range key: [0, 0, 0, 20000]
New users per shard, hash key:  [4946, 5007, 5046, 5001]

What this code does

  • With range sharding, all 20,000 sign-ups have the newest ids and land on the last shard: a hot shard.
  • With hash sharding, the same users spread almost evenly. The hash method is FNV-1a with a final mixing step, chosen so the output is the same on every JVM.

For ShopLite orders, customer_id is a good key: "my orders" and "place order" both touch a single customer, so they hit one shard, and there are millions of customers to spread.

Range sharding gives each shard a range of keys (users 1 to 250,000 on shard 1, and so on). It keeps neighbours together, but all new users land on the last shard. Hash sharding puts each key where its hash points, which spreads keys evenly but makes range queries across keys touch every shard. A hot shard is one that gets far more traffic than the rest: from a range key that keeps growing, a skewed key such as status, or one huge customer.

hash(userId) % N and the re-mapping problem

Hash sharding picks the shard with shard = hash(key) % N, where N is the number of shards: it spreads keys evenly, but changing N changes the answer for most keys.

Change N from 4 to 5 and see how many of 100,000 users get a new shard.

Example 3 · How many users move when N changes

ModuloRemapDemo.javaJava
public class ModuloRemapDemo {    static int hash(String key) {                       // FNV-1a plus mixing, same on every JVM        int h = 0x811C9DC5;        for (char c : key.toCharArray()) {            h ^= c;            h *= 0x01000193;        }        h ^= h >>> 16;                                  // final mixing step (from MurmurHash3)        h *= 0x85EBCA6B;        h ^= h >>> 13;        h *= 0xC2B2AE35;        h ^= h >>> 16;        return h;    }
    static int shardFor(int userId, int shards) {        return Math.floorMod(hash("user:" + userId), shards);    }
    public static void main(String[] args) {        int users = 100_000;        int[][] changes = {{4, 5}, {4, 8}, {10, 11}};        for (int[] c : changes) {            int moved = 0;            for (int id = 1; id <= users; id++) {                if (shardFor(id, c[0]) != shardFor(id, c[1])) {                    moved++;                }            }            System.out.printf("%2d -> %2d shards: %5d of %d users move (%d%%)%n",                    c[0], c[1], moved, users, moved * 100 / users);        }    }}
Output
 4 ->  5 shards: 79969 of 100000 users move (79%)
 4 ->  8 shards: 50058 of 100000 users move (50%)
10 -> 11 shards: 90984 of 100000 users move (90%)

What this code does

  • From 4 to 5 shards, about 80% of 100,000 users get a different shard under hash % N.
  • Doubling to 8 moves about half, and 10 to 11 moves about 90%. Each move means copying that user's rows between servers.

Every moved user means copying their rows to another server while the shop is running. Doubling from 4 to 8 moves about half; going from 10 to 11 moves about 90%.

That is why real systems avoid plain modulo, or create many small logical shards up front and move whole logical shards between servers.

Predict the output

Who moves?

Users are placed with userId % shards. Which users change shard?

Round 1 of 2

user 12: 12 % 4 = 0 and 12 % 5 = 2
Does user 12 stay on the same shard after going from 4 to 5 shards?

Consistent hashing with virtual nodes

Consistent hashing puts shards and keys on the same circle of hash values (a ring); a key belongs to the first shard point clockwise from its hash, so adding a shard moves only a small part of the keys.

This program builds a ring with 200 points per shard in a TreeMap, then adds a fifth shard and counts who moves.

A circle of hash values with points for shards 1 to 4 in the order A, B, C, D. A user's hash lands on the circle and belongs to the next shard point clockwise. A new shard E is added between B and C and takes over only the arc just before its point; every other arc stays.

Example 4 · A consistent hashing ring with TreeMap

ConsistentHashDemo.javaJava
import java.util.Map;import java.util.SortedMap;import java.util.TreeMap;
class HashRing {    private final TreeMap<Integer, String> ring = new TreeMap<>();    private final int virtualNodes;
    HashRing(int virtualNodes) {        this.virtualNodes = virtualNodes;    }
    static int hash(String key) {        int h = 0x811C9DC5;        for (char c : key.toCharArray()) {            h ^= c;            h *= 0x01000193;        }        h ^= h >>> 16;        h *= 0x85EBCA6B;        h ^= h >>> 13;        h *= 0xC2B2AE35;        h ^= h >>> 16;        return h;    }
    void addShard(String shard) {        for (int v = 0; v < virtualNodes; v++) {            ring.put(hash(shard + "#" + v), shard);        }    }
    String shardFor(String key) {        Map.Entry<Integer, String> e = ring.ceilingEntry(hash(key));        return e != null ? e.getValue() : ring.firstEntry().getValue();    }}
public class ConsistentHashDemo {    static void printCounts(String title, HashRing ring, int users) {        SortedMap<String, Integer> counts = new TreeMap<>();        for (int id = 1; id <= users; id++) {            counts.merge(ring.shardFor("user:" + id), 1, Integer::sum);        }        System.out.println(title + counts);    }
    public static void main(String[] args) {        int users = 100_000;        HashRing ring = new HashRing(200);        for (String s : new String[] {"shard-1", "shard-2", "shard-3", "shard-4"}) {            ring.addShard(s);        }        String[] before = new String[users + 1];        for (int id = 1; id <= users; id++) {            before[id] = ring.shardFor("user:" + id);        }        printCounts("4 shards: ", ring, users);
        ring.addShard("shard-5");        int moved = 0;        for (int id = 1; id <= users; id++) {            if (!ring.shardFor("user:" + id).equals(before[id])) {                moved++;            }        }        printCounts("5 shards: ", ring, users);        System.out.println("Users moved: " + moved + " (" + moved * 100 / users + "%), all of them to shard-5");    }}
Output
4 shards: {shard-1=22950, shard-2=24448, shard-3=25462, shard-4=27140}
5 shards: {shard-1=18593, shard-2=18930, shard-3=20916, shard-4=21563, shard-5=19998}
Users moved: 19998 (19%), all of them to shard-5

What this code does

  • Each shard puts 200 virtual nodes on the ring, so the four shards get roughly equal shares of 100,000 users.
  • Adding shard-5 moves about 20% of users, and every one of them moves to the new shard; no user moves between old shards.

Adding a shard takes over only the keys just before its points; every other key stays where it was. With one point per shard the ring is uneven, so each shard gets many virtual nodes: points such as shard-1#0 to shard-1#199.

In Java, a TreeMap<Integer, String> from point to shard is a complete ring: ceilingEntry(hash(key)) finds the next point, and firstEntry() wraps around at the end. Going from 4 to 5 shards then moves about 1/5 of the keys, all to the new shard.

Find the bug

Find the ring bug

Tap the line that breaks the ring.

Find the shard for a key.

Round 1 of 3

What sharding costs

Scatter-gather is a query that does not use the shard key: the app asks every shard, then merges the partial results into one answer.

A query with the shard key asks one shard; a query without it asks them all. This program runs one of each over 4 shards.

Example 5 · One-shard query vs scatter-gather

CrossShardQueryDemo.javaJava
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class CrossShardQueryDemo {    record Order(int id, int userId, String day, int amount) { }
    static final int SHARDS = 4;    static final List<List<Order>> shards = new ArrayList<>();    static int shardQueries = 0;
    static int shardOf(int userId) {        return userId % SHARDS;                         // orders live on their user's shard    }
    public static void main(String[] args) {        for (int s = 0; s < SHARDS; s++) {            shards.add(new ArrayList<>());        }        int id = 1;        for (int user = 1; user <= 40; user++) {            for (int k = 0; k < 3; k++) {                String day = "2026-10-0" + (1 + (user + k) % 3);                shards.get(shardOf(user)).add(new Order(id++, user, day, 300 + (user * 37 + k * 101) % 5000));            }        }
        // 1. By shard key: exactly one shard is asked        shardQueries = 0;        List<Order> mine = shards.get(shardOf(7)).stream().filter(o -> o.userId() == 7).toList();        shardQueries++;        System.out.println("Orders of user 7: " + mine.size() + " rows, shards asked: " + shardQueries);
        // 2. Not by shard key: scatter to every shard, then gather and merge        shardQueries = 0;        List<Order> best = new ArrayList<>();        for (List<Order> shard : shards) {            shardQueries++;            shard.stream().filter(o -> o.day().equals("2026-10-02"))                    .sorted(Comparator.comparingInt(Order::amount).reversed()).limit(3).forEach(best::add);        }        best.sort(Comparator.comparingInt(Order::amount).reversed());        System.out.println("Top 3 orders on 2026-10-02: " + best.subList(0, 3).stream().map(o -> "#" + o.id() + " Rs " + o.amount()).toList()                + ", shards asked: " + shardQueries);    }}
Output
Orders of user 7: 3 rows, shards asked: 1
Top 3 orders on 2026-10-02: [#114 Rs 1908, #116 Rs 1844, #105 Rs 1797], shards asked: 4

What this code does

  • "Orders of user 7" uses the shard key, so one shard answers.
  • "Top orders on 2 October" has no shard key: all 4 shards are asked, each returns its own top 3, and the app merges them.

Sharding is the last step on the scaling path because it makes many things harder.

  • Cross-shard queries: anything not filtered by the shard key ("all orders on 2 October", admin reports) must ask every shard and merge the results.
  • Joins: tables on different shards cannot be joined by the database; the app joins, or small tables such as categories are copied to every shard.
  • Transactions: one ACID transaction cannot span two shards in plain MySQL; cross-shard changes need sagas or two-phase commit.
  • Operations: backups, schema migrations, resharding and monitoring all happen N times.

Order of execution

Top orders across 4 shards

Put the scatter-gather steps in order.

Next step

Check your understanding

12 quick questions