System Design Part 4 Distributed data

Sharding: Choosing a Shard Key, Moving Data When You Reshard, and What You Lose Across Shards

Bill.Lin 23 min read

System Design series Part 4-2 | Previous: Replication and Replication Lag | Next: Consistent Hashing | Series map

Read first: Part 4-1 Replication and Replication Lag.

Scenario and problem

Three years into running the talk platform, sign-up data has grown to 3 billion rows and 12 TB. The moment sign-ups open for a popular talk, writes peak at 20,000 per second. The read replicas from the previous post do not help: every replica has to apply every write, so it handles as many writes as the primary.

A single primary hits its limits in three places at once:

  • Write volume: every write queues on the same machine
  • Data volume: restoring the 12 TB backup at 500 MB per second takes almost 7 hours
  • Memory: the hot indexes no longer fit in the buffer pool, and queries start reading heavily from disk
Three places one primary cannot keep up1 / 5
Three places one primary cannot keep upHot sign-upsPrimaryRead replicaDisk, backupsHot sign-upsPrimary20k writes/s3 billion rows, 12 TBPrimaryRead replicaall writes tooSame writes as primaryHot sign-upsPrimary20k writes/sEvery write queues hereDisk, backupsPrimaryRestore 500 MB/sAlmost 7 hoursPrimaryDisk, backupsHeavy disk readsHot indexes out of memory
  1. 12 TB after three yearsSign-up data has grown to 3 billion rows and 12 TB. The moment sign-ups open for a popular talk, writes peak at 20,000 per second.
  2. Read replicas do not helpA replica can take on reads but not writes: every replica has to apply every write, so it handles as many writes as the primary.
  3. Writes queue on one machineEvery write queues on the same machine, and adding replicas does not make it any faster.
  4. A restore takes almost 7 hoursRestoring the 12 TB backup at 500 MB per second takes almost 7 hours. The service can only wait during that time.
  5. Indexes no longer fit in memoryThe hot indexes no longer fit in the buffer pool, so queries start reading heavily from disk, and even reads slow down.

The simplest approach and its limits

Before you shard, make sure you have tried these simpler approaches:

  1. Vertical scaling: move to a bigger machine (Part 2)
  2. Archive cold data: move sign-up records from three years ago to cheap storage, and keep only recent data in the main database
  3. Partitioned tables (partitioning): inside one database, split a table into partitions by month. A query scans only the relevant partitions, and expired data disappears instantly with DROP PARTITION. MySQL requires every unique index (including the primary key) to include the partitioning column, which is the same limit unique constraints hit under sharding. But it is still one machine, and the ceiling on writes does not change
  4. Functional split: put sign-ups, viewing history, and in-app messages in separate databases, so each database takes only part of the writes

Only when none of these holds up do you spread the rows of one table across several databases, which is sharding. The price: cross-shard transactions, cross-shard queries, cross-shard unique constraints, resharding, and N times the operational work.

Core mechanism

Choosing a shard key

The shard key decides which shard each row lives on, and a wrong choice is almost impossible to change. In order of importance:

  1. Transaction boundary: the data one transaction modifies must land on the same shard
  2. Query patterns: the most common queries must carry the shard key, so they hit only one shard
  3. Distribution: data and traffic must be even, with no handful of shards far busier than the rest
  4. Growth: new data must not always go to the same shard

Ways to shard

Method How it works Pros Cons
Range By key range, e.g. member IDs 1 to 1,000,000 on the first server A range query touches only a few shards An increasing key sends all new data to the last server
Hash hash(key) % N Even distribution A range query hits every shard; when N changes, almost all data has to move
Lookup table (directory) Keep a separate “which shard is this key on” mapping table Each row can be moved on its own The mapping table itself must be highly available, and every query adds a lookup
Logical shards Hash to a fixed number of slots first (say 1024), then look up the physical shard Data moves one slot at a time, and the mapping table is small The number of slots caps how far you can grow later

Measured: distribution, resharding, and cross-shard queries

16 shards and 2 million sign-ups spread over 16 months. Both talk popularity and member activity follow a long-tail distribution: a few popular talks account for a large share of sign-ups.

Simulation (java ShardingSimulation.java)
java
import java.util.Arrays;
import java.util.Random;
import java.util.function.IntUnaryOperator;

/** 16 shards: compares the data and write distribution of three shard keys, how much data moves when you add a shard, and the tail latency of cross-shard queries. */
public class ShardingSimulation {

    static final int SHARDS = 16;

    public static void main(String[] args) {
        Random random = new Random(42);
        distribution(random);
        resharding();
        scatterGather(random);
    }

    static void distribution(Random random) {
        int registrations = 2_000_000;
        int months = 16;
        double[] lectureCdf = zipfCdf(20_000, 0.9);                // a few popular talks get a large share of sign-ups
        double[] memberCdf = zipfCdf(300_000, 0.6);
        long[][] rows = new long[3][SHARDS];
        long[][] lastDay = new long[3][SHARDS];
        long dayStart = months * 30L * 24 - 24;                     // in hours: the last 24 hours
        for (int i = 0; i < registrations; i++) {
            int lecture = sample(lectureCdf, random);
            int member = sample(memberCdf, random);
            long hour = (long) (random.nextDouble() * months * 30 * 24);
            int[] shard = {
                    Math.floorMod(Long.hashCode(member * 0x9E3779B97F4A7C15L), SHARDS),
                    Math.floorMod(Long.hashCode(lecture * 0x9E3779B97F4A7C15L), SHARDS),
                    (int) (hour / (30 * 24))                         // one shard per month
            };
            for (int k = 0; k < 3; k++) {
                rows[k][shard[k]]++;
                if (hour >= dayStart) {
                    lastDay[k][shard[k]]++;
                }
            }
        }
        String[] names = {"hash(member_id)", "hash(lecture_id)", "range by creation month"};
        for (int k = 0; k < 3; k++) {
            System.out.printf("%s: largest shard holds %.2fx the average data | last-day writes %.2fx the average%n",
                    names[k], skew(rows[k]), skew(lastDay[k]));
        }
    }

    static void resharding() {
        int keys = 1_000_000;
        int[] slotOwner = new int[1024];                           // 1024 logical shards, spread evenly over 16 servers
        for (int s = 0; s < slotOwner.length; s++) {
            slotOwner[s] = s % SHARDS;
        }
        int[] newOwner = slotOwner.clone();
        int[] count = new int[SHARDS + 1];
        Arrays.fill(count, 0, SHARDS, 64);
        for (int s = 0; s < newOwner.length && count[SHARDS] < 1024 / (SHARDS + 1); s++) {
            int owner = newOwner[s];
            if (count[owner] > 1024 / (SHARDS + 1)) {              // take a few from each server for the new 17th one
                count[owner]--;
                count[SHARDS]++;
                newOwner[s] = SHARDS;
            }
        }
        System.out.println();
        report("hash % 16 → hash % 17", keys, h -> Math.floorMod(h, 16), h -> Math.floorMod(h, 17));
        report("hash % 16 → hash % 32", keys, h -> Math.floorMod(h, 16), h -> Math.floorMod(h, 32));
        report("1024 slots, 16 → 17 servers", keys,
                h -> slotOwner[Math.floorMod(h, 1024)], h -> newOwner[Math.floorMod(h, 1024)]);
    }

    static void report(String label, int keys, IntUnaryOperator before, IntUnaryOperator after) {
        int moved = 0;
        for (int key = 0; key < keys; key++) {
            int h = Long.hashCode(key * 0x9E3779B97F4A7C15L);
            moved += before.applyAsInt(h) != after.applyAsInt(h) ? 1 : 0;
        }
        System.out.printf("%-28s moves %5.1f%% of the data%n", label, 100.0 * moved / keys);
    }

    /** Latency of one shard: median 4 ms; 1% of requests hit a GC pause or a slow query and take 50 to 200 ms. */
    static void scatterGather(Random random) {
        System.out.println();
        int trials = 200_000;
        for (int fanOut : new int[] {1, 4, 16, 64}) {
            double[] latency = new double[trials];
            for (int t = 0; t < trials; t++) {
                double slowest = 0;
                for (int s = 0; s < fanOut; s++) {
                    double ms = random.nextDouble() < 0.01
                            ? 50 + random.nextDouble() * 150
                            : 4 * Math.exp(0.5 * random.nextGaussian());
                    slowest = Math.max(slowest, ms);                // wait for the slowest shard to answer
                }
                latency[t] = slowest;
            }
            Arrays.sort(latency);
            System.out.printf("fan-out %2d: p50 %6.1f ms | p99 %6.1f ms | chance at least one shard is slow %4.1f%%%n",
                    fanOut, latency[trials / 2], latency[trials * 99 / 100],
                    100 * (1 - Math.pow(0.99, fanOut)));
        }
    }

    static double skew(long[] counts) {
        long max = Arrays.stream(counts).max().orElseThrow();
        double avg = Arrays.stream(counts).average().orElseThrow();
        return max / avg;
    }

    static double[] zipfCdf(int n, double s) {
        double[] cdf = new double[n];
        double sum = 0;
        for (int k = 1; k <= n; k++) {
            sum += 1 / Math.pow(k, s);
            cdf[k - 1] = sum;
        }
        for (int k = 0; k < n; k++) {
            cdf[k] /= sum;
        }
        return cdf;
    }

    static int sample(double[] cdf, Random random) {
        int i = Arrays.binarySearch(cdf, random.nextDouble());
        return i >= 0 ? i : -i - 1;
    }
}
text
hash(member_id): largest shard holds 1.03x the average data | last-day writes 1.11x the average
hash(lecture_id): largest shard holds 1.74x the average data | last-day writes 1.97x the average
range by creation month: largest shard holds 1.00x the average data | last-day writes 16.00x the average

hash % 16 → hash % 17        moves  94.1% of the data
hash % 16 → hash % 32        moves  50.0% of the data
1024 slots, 16 → 17 servers  moves   5.9% of the data

fan-out  1: p50    4.0 ms | p99   24.2 ms | chance at least one shard is slow  1.0%
fan-out  4: p50    6.7 ms | p99  162.4 ms | chance at least one shard is slow  3.9%
fan-out 16: p50   10.1 ms | p99  190.9 ms | chance at least one shard is slow 14.9%
fan-out 64: p50   19.3 ms | p99  197.6 ms | chance at least one shard is slow 47.4%

Distribution:

  • hash(member_id) is the most even, because even the most active member makes up only a small part of all sign-ups
  • hash(lecture_id): the largest shard holds 1.74 times the average. On the shard that holds the most popular talk, that one talk is worth several ordinary talks. Hashing can spread out only different keys; all the traffic for one key always goes to the same shard
  • Range by creation month: the data volume is perfectly even, but all of the last day’s writes land on the newest shard, 16 times the average. The other 15 servers sit idle while the newest one takes every write

Resharding:

  • Changing hash % 16 to hash % 17 moves 94% of the data to another server, close to a full rebuild
  • Doubling from 16 to 32 servers moves 50%
  • With 1024 logical shards, the new 17th server takes a few slots from each server, and only 5.9% of the data moves. That is 1/17, the theoretical minimum for an even distribution. Consistent hashing, in the next post, is another way to get the same result

Tail latency of cross-shard queries: the p99 for one shard is 24 ms; querying 16 shards pushes the p99 to 191 ms. A query has to wait for the slowest shard, and the chance that “at least one shard is slow” is 1 − 0.99^N, which is 15% for 16 shards. This is the fan-out that amplifies tail latency, from the Latency post.

What you lose after sharding

  • Cross-shard transactions: a database transaction is valid only within one machine. Across shards you need 2PC or a saga (Part 7), and both are far more complex than a local transaction. That is why the first rule for a shard key is to keep transactions inside one shard
  • Unique constraints: a unique index is checked only within one shard. If email is not the shard key, “email must be unique” does not hold: two shards can each store a row with the same email. The fix is a separate mapping table sharded by email, where you claim the email first
  • Secondary indexes: once sign-ups are sharded by talk, “which talks did this member sign up for” has to query every shard. The fix is a separate index table sharded by member, updated asynchronously through an outbox or CDC, at the cost of eventual consistency
  • JOINs and aggregates: cross-shard JOIN, COUNT(*), and ORDER BY ... LIMIT all have to be merged in the application

A single hot spot that sharding cannot fix

When sign-ups open for a popular talk, 20,000 requests all fight over the remaining seats in the same row. No matter how many shards you split into, that row lives on one shard. The problem is lock contention on a single row, not shard capacity. Common ways to ease it:

  • Split the counter: split 1,000 seats into 10 rows of 100 each, and have each request pick a row at random to decrement, which cuts contention to a tenth. The 10 rows use the same shard key, so they stay on the same shard and the transaction is still local
  • Queue in front of the database: use a queue or Redis to filter out requests beyond the number of seats first, and let only requests that can still succeed reach the database (Part 5, Part 9)

Comparing options

Which shard key for sign-up data

member_id lecture_id
“My sign-ups” Query one shard Query every shard, or build a separate index table
“Sign-up list for this talk” Query every shard, or build a separate index table Query one shard
Sign-up transaction (take a seat + write the sign-up) The seats are on the talk’s shard: cross-shard Same shard, a local transaction
Distribution Even Popular talks cause skew

Pick lecture_id: the transaction boundary is the first rule. The skew can be handled with logical shards, by moving the slots that hold popular talks to dedicated machines; “My sign-ups” uses an index table sharded by member.

Build it yourself, or use a middleware layer

Application-side routing Middleware layer (Vitess, ShardingSphere, Citus)
How it works Your code decides which shard each query goes to The application sees one database; the middleware rewrites and routes the SQL
Pros Transparent behavior, no extra component Tools for cross-shard queries and resharding are already built
Cons You build resharding and cross-shard queries yourself One more component and more to learn; some SQL is not supported

Vitess is for MySQL, Citus is a PostgreSQL extension, and Apache ShardingSphere comes in two forms, a JDBC driver and a proxy. When you have many shards and the team has no room to build its own resharding tools, a middleware layer usually pays off.

In Java

1. Routing: logical shards

java
package sharding;

/** A key is first hashed to one of 1024 logical shards (slots), then a table lookup finds the physical shard. Adding a server only moves some slots and updates this table. */
public class ShardRouter {

    static final int SLOTS = 1024;

    private final int[] slotOwner;

    public ShardRouter(int[] slotOwner) {
        if (slotOwner.length != SLOTS) {
            throw new IllegalArgumentException("slot table must have " + SLOTS + " entries");
        }
        this.slotOwner = slotOwner.clone();
    }

    public static ShardRouter evenlySpread(int shards) {
        int[] owner = new int[SLOTS];
        for (int slot = 0; slot < SLOTS; slot++) {
            owner[slot] = slot % shards;
        }
        return new ShardRouter(owner);
    }

    public int shardOf(long key) {
        return slotOwner[slotOf(key)];
    }

    /** Once the hash function is in production it cannot change; changing it reshards all the data. */
    static int slotOf(long key) {
        long h = key * 0x9E3779B97F4A7C15L;
        return Math.floorMod((int) (h ^ (h >>> 32)), SLOTS);
    }
}

2. Sign-ups sharded by talk

The sign-up transaction completes inside the talk’s shard. The same transaction writes to the outbox, and a background job relays it to the index table on the member’s shard (Outbox Pattern):

java
package sharding;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/** Sign-ups are sharded by lecture_id: the seats and the sign-up records are on the same shard, so a sign-up is one local transaction. */
public class ShardedRegistrations {

    public record Registration(long lectureId, long memberId, LocalDateTime createdAt) {}

    record OutboxEvent(long id, long lectureId, long memberId, LocalDateTime createdAt) {}

    private final ShardRouter router;
    private final List<JdbcClient> shards;
    private final List<TransactionTemplate> transactions;

    public ShardedRegistrations(ShardRouter router, List<DataSource> dataSources) {
        this.router = router;
        this.shards = dataSources.stream().map(JdbcClient::create).toList();
        this.transactions = dataSources.stream()
                .map(ds -> new TransactionTemplate(new DataSourceTransactionManager(ds)))
                .toList();
    }

    /** Take a seat, write the sign-up record, write the outbox: all on the talk's shard. A duplicate sign-up is stopped by the primary key, and the whole transaction rolls back. */
    public boolean register(long lectureId, long memberId, LocalDateTime now) {
        int shard = router.shardOf(lectureId);
        JdbcClient jdbc = shards.get(shard);
        return Boolean.TRUE.equals(transactions.get(shard).execute(status -> {
            int taken = jdbc.sql("""
                    UPDATE lecture_seat SET remaining = remaining - 1
                     WHERE lecture_id = :lectureId AND remaining > 0""")
                    .param("lectureId", lectureId)
                    .update();
            if (taken == 0) {
                return false;
            }
            Registration registration = new Registration(lectureId, memberId, now);
            jdbc.sql("INSERT INTO registration (lecture_id, member_id, created_at) VALUES (:lectureId, :memberId, :createdAt)")
                    .paramSource(registration)
                    .update();
            jdbc.sql("INSERT INTO outbox (lecture_id, member_id, created_at) VALUES (:lectureId, :memberId, :createdAt)")
                    .paramSource(registration)
                    .update();
            return true;
        }));
    }

    /** Background job: writes outbox events to the index table on the member's shard. Safe to resend; the primary key blocks duplicates. */
    public int relayOutbox() {
        int relayed = 0;
        for (JdbcClient source : shards) {
            List<OutboxEvent> events = source
                    .sql("SELECT id, lecture_id, member_id, created_at FROM outbox WHERE sent = FALSE ORDER BY id LIMIT 100")
                    .query(OutboxEvent.class)
                    .list();
            for (OutboxEvent event : events) {
                try {
                    shards.get(router.shardOf(event.memberId()))
                            .sql("INSERT INTO member_registration (member_id, lecture_id, created_at) VALUES (:memberId, :lectureId, :createdAt)")
                            .paramSource(event)
                            .update();
                } catch (DuplicateKeyException alreadyRelayed) {
                    // the last write succeeded but marking it sent failed; this is a resend
                }
                source.sql("UPDATE outbox SET sent = TRUE WHERE id = :id").param("id", event.id()).update();
                relayed++;
            }
        }
        return relayed;
    }

    public List<Registration> findByLecture(long lectureId) {
        return shards.get(router.shardOf(lectureId))
                .sql("SELECT lecture_id, member_id, created_at FROM registration WHERE lecture_id = :lectureId ORDER BY created_at")
                .param("lectureId", lectureId)
                .query(Registration.class)
                .list();
    }

    /** Reads the index table on the member's shard: an eventually consistent result, complete only after the outbox relay. */
    public List<Registration> findByMember(long memberId) {
        return shards.get(router.shardOf(memberId))
                .sql("SELECT lecture_id, member_id, created_at FROM member_registration WHERE member_id = :memberId ORDER BY created_at")
                .param("memberId", memberId)
                .query(Registration.class)
                .list();
    }

    /** A query without the shard key: take the first limit rows from each shard, then merge. If any one shard times out, the whole query fails. */
    public List<Registration> latest(int limit) {
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<CompletableFuture<List<Registration>>> perShard = shards.stream()
                    .map(jdbc -> CompletableFuture.supplyAsync(() -> jdbc
                                    .sql("SELECT lecture_id, member_id, created_at FROM registration ORDER BY created_at DESC LIMIT :limit")
                                    .param("limit", limit)
                                    .query(Registration.class)
                                    .list(), executor)
                            .orTimeout(500, TimeUnit.MILLISECONDS))
                    .toList();
            return perShard.stream()
                    .flatMap(future -> future.join().stream())
                    .sorted(Comparator.comparing(Registration::createdAt).reversed())
                    .limit(limit)
                    .toList();
        }
    }
}

Running it for real, with 4 H2 databases playing 4 shards:

Verification program (ShardingDemo.java)
java
package sharding;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class ShardingDemo {

    public static void main(String[] args) {
        ShardRouter router = ShardRouter.evenlySpread(4);
        List<DataSource> dataSources = new ArrayList<>();
        for (int shard = 0; shard < 4; shard++) {
            DataSource ds = new DriverManagerDataSource("jdbc:h2:mem:shard" + shard + ";DB_CLOSE_DELAY=-1", "sa", "");
            JdbcClient jdbc = JdbcClient.create(ds);
            jdbc.sql("CREATE TABLE lecture_seat (lecture_id BIGINT PRIMARY KEY, remaining INT NOT NULL)").update();
            jdbc.sql("CREATE TABLE registration (lecture_id BIGINT, member_id BIGINT, created_at TIMESTAMP, PRIMARY KEY (lecture_id, member_id))").update();
            jdbc.sql("CREATE TABLE member_registration (member_id BIGINT, lecture_id BIGINT, created_at TIMESTAMP, PRIMARY KEY (member_id, lecture_id))").update();
            jdbc.sql("CREATE TABLE outbox (id BIGINT AUTO_INCREMENT PRIMARY KEY, lecture_id BIGINT, member_id BIGINT, created_at TIMESTAMP, sent BOOLEAN DEFAULT FALSE NOT NULL)").update();
            dataSources.add(ds);
        }
        long[] lectures = {101, 102, 103, 104};
        for (long lecture : lectures) {
            JdbcClient.create(dataSources.get(router.shardOf(lecture)))
                    .sql("INSERT INTO lecture_seat VALUES (:id, :seats)")
                    .param("id", lecture).param("seats", lecture == 104 ? 1 : 30).update();
            System.out.printf("talk %d → shard %d%n", lecture, router.shardOf(lecture));
        }
        System.out.printf("member 7 → shard %d%n%n", router.shardOf(7));

        ShardedRegistrations registrations = new ShardedRegistrations(router, dataSources);
        LocalDateTime base = LocalDateTime.of(2026, 11, 22, 9, 0);
        long[][] requests = {{101, 7}, {102, 8}, {103, 7}, {104, 9}, {104, 7}, {101, 9}};
        for (int i = 0; i < requests.length; i++) {
            System.out.printf("talk %d, member %d signs up: %s%n", requests[i][0], requests[i][1],
                    registrations.register(requests[i][0], requests[i][1], base.plusMinutes(i)) ? "ok" : "full");
        }
        try {
            registrations.register(101, 7, base.plusMinutes(10));
        } catch (DuplicateKeyException e) {
            System.out.println("talk 101, member 7 signs up again: blocked by the primary key");
        }
        System.out.println("talk 101 seats left: " + JdbcClient.create(dataSources.get(router.shardOf(101)))
                .sql("SELECT remaining FROM lecture_seat WHERE lecture_id = 101").query(Integer.class).single() + " (30 seats, 2 sign-ups succeeded)");

        System.out.println();
        System.out.println("sign-ups for talk 101 (1 shard): " + registrations.findByLecture(101).stream().map(r -> "member " + r.memberId()).toList());
        System.out.println("member 7's sign-ups, before the outbox relay: " + registrations.findByMember(7).stream().map(r -> "talk " + r.lectureId()).toList());
        System.out.println("outbox relay: " + registrations.relayOutbox() + " events");
        System.out.println("member 7's sign-ups, after the outbox relay: " + registrations.findByMember(7).stream().map(r -> "talk " + r.lectureId()).toList());
        System.out.println("latest 3 sign-ups (4 shards queried, then merged): " + registrations.latest(3).stream()
                .map(r -> r.createdAt().toLocalTime() + " talk " + r.lectureId()).toList());
    }
}
text
talk 101 → shard 2
talk 102 → shard 2
talk 103 → shard 1
talk 104 → shard 3
member 7 → shard 1

talk 101, member 7 signs up: ok
talk 102, member 8 signs up: ok
talk 103, member 7 signs up: ok
talk 104, member 9 signs up: ok
talk 104, member 7 signs up: full
talk 101, member 9 signs up: ok
talk 101, member 7 signs up again: blocked by the primary key
talk 101 seats left: 28 (30 seats, 2 sign-ups succeeded)

sign-ups for talk 101 (1 shard): [member 7, member 9]
member 7's sign-ups, before the outbox relay: []
outbox relay: 5 events
member 7's sign-ups, after the outbox relay: [talk 101, talk 103]
latest 3 sign-ups (4 shards queried, then merged): [09:05 talk 101, 09:03 talk 104, 09:02 talk 103]
  • A sign-up is a local transaction: the duplicate sign-up is blocked by the primary key of registration, the whole transaction rolls back, and no seat is taken. The unique constraint works only because the primary key (lecture_id, member_id) includes the shard key
  • The index table is eventually consistent: before the outbox relay, “My sign-ups” is empty. The sign-up success page cannot rely on the index table; it should show the result of this sign-up directly
  • Cross-shard queries: “latest 3 sign-ups” queried 4 shards, took 3 rows from each, and merged them. For page 100 (10 rows per page), every shard has to return its first 1,000 rows, 4,000 rows across the 4 shards, just to return 10. Cross-shard lists in back-office tools should use keyset pagination (Index post), or be handed to a search engine instead (Full-text search post)

3. The resharding process

Move data online, one slot at a time:

  1. Create the same tables on the new shard, and copy this slot’s existing data
  2. Use CDC to keep applying the new writes made during the copy, until it has almost caught up
  3. Briefly stop writes to this slot, and wait for the last changes to be applied
  4. Update the slot mapping table, and switch every application to the new table
  5. Resume writes; once everything checks out, delete the data on the old shard

The write pause covers only one slot and lasts only a few seconds. Step 4 has to make sure every application gets the new mapping table: a server still using the old one will write data back to the old shard.

Pitfalls and gotchas

  • Each shard with its own AUTO_INCREMENT: different shards generate the same IDs. Use distributed IDs
  • Changing the hash function: this reshards all the data. Keep the function fixed, and services written in different languages must compute the same result
  • No timeout on cross-shard queries: one stuck shard stalls every cross-shard query. Set a timeout, and decide whether a timeout returns partial results or fails the whole query
  • Schema changes have to reach every shard: some shards may succeed and others fail, so the code must work with both the old and the new schema at the same time
  • Each shard’s backup is from a different point in time: after a restore from backup, data across shards is inconsistent, for example the sign-ups are restored but the index table is not yet
  • Using sharding to fix a single hot row: see “A single hot spot that sharding cannot fix” above. First confirm whether the bottleneck is the whole machine or one row of data
  • Sharding too early: with many shards from the start, operating cost doubles right away. Start with logical shards, map the slots onto a few physical databases, and move them when you need to

Security

  • Isolation levels for multi-tenancy: B2B enterprise customers can share shards (each row carries a tenant_id), or get their own shard or database. A dedicated shard limits the blast radius of an incident, and a large customer’s traffic does not slow down anyone else. But a shard is not authorization: every query still has to carry the tenant condition, and routing to the right shard does not mean this user has permission to read the row (BOLA in Part 8)
  • Cross-shard admin queries carry the highest risk: a normal API touches only one shard, while a back-office “query all shards” reads every tenant’s data at once. These queries need their own permissions and audit logs
  • A hot spot can also be an attack: an attacker floods one key with requests and brings down the whole shard, and the other tenants on that shard go down with it. Rate-limit per key, and be able to move the attacked slot to an isolated machine
  • Data residency: when regulations require a region’s data to be stored in that region, shard by region; the slot mapping table then becomes a compliance control point, and every change to it has to be reviewed and logged
  • Deletion has to cover every copy: when you delete a member’s personal data, cover not only the main shard but also the index tables on other shards, the outbox, and backups

When to use it, and when not to

  • Use sharding: when write volume or data volume exceeds one host, and you have already tried vertical scaling, archiving, partitioned tables, and functional splits
  • Don’t use it: when reads are the bottleneck (use replicas and caching); when the data volume is still within what one host can handle; when your most important queries and transactions cannot map to the same shard key
  • Consider distributed SQL: when you need many cross-shard transactions, databases such as Spanner, CockroachDB, and TiDB handle sharding and cross-shard transactions inside the database, at the cost of an extra round of cross-node coordination on every write

References

Comments