How systems work

Sharding and consistent hashing.

Sharding splits one big dataset across many machines, so each machine holds and serves only part of it. Every row has a shard key, such as a user id, and a rule turns that key into the machine that owns it.

The rule is the whole game. A bad one sends all new writes to one machine, or moves almost all your data when you add a machine. A good one spreads the work, moves little and keeps related rows together. This page shows each rule working on real keys, then the problems that no rule fixes.

In the labs after the walkthrough, every small square is one key, such as a user or an order, in a simulation running in your browser. Its colour is the node it was first stored on: A, B, C, D. So when a key moves, you see a square of the wrong colour in its new home. Keys that just moved get a thick outline for a moment. Click any key to follow it and see what happened to it.

00 The life of one key

Before the live labs, follow a single key, user 42, from the moment it is written to the day a new node joins. Step through at your own pace, or press Play all.

Sign-up serviceThe app: sends reads and writesRouterDecides which node gets each keyhash(key) = ?Shard map12%node A10.0.0.138%node B10.0.0.266%node C10.0.0.388%node D10.0.0.425%75%ABCDHash ring0 at the top, rising clockwiseNode A10.0.0.1Database serverNode B10.0.0.2Database serverNode C10.0.0.3Database serverNode D10.0.0.4Database serveruser 7Kofiuser 12Meiuser 63Lenauser 19Raviuser 88Omaruser 30Inesuser 51TomA token: node A’s point on theringA stored key, drawn at itshash

Step 1 of 10

Meet the pieces

Four pieces work together. The app sends reads and writes. The router decides where each one goes, using the hash ring as its rule. The nodes are database servers, and each one holds some of the rows.

01 Why shard

A single database server has three limits that do not move: how much it can store on disk, how much of its working set fits in memory, and how many writes a second it can make durable. Read replicas help with reads, but every copy still holds all the data and takes every write.

When one of those limits gets close, you can buy a bigger machine (scaling up) until there is no bigger machine to buy, or split the data so each machine holds a part (scaling out). Splitting is sharding, and each part is a shard.

New keysYour app, 4 writes a secondNode A0Database serverDisk 0% full
Keys stored
0
Writes rejected
0

Click any key to follow it and see what happens to it.

New users arrive at 4 a second. Each node can store 30 and take 3 writes a second. Red marks are writes that were turned away.
    Try this. Watch one node reject writes that come too fast, then reject everything once its disk is full. Move nodes to 2: existing keys spread out, and both limits now cover the load. Raise the rate and add nodes to keep up.

    Shard when one machine cannot hold or write your data, not before. Every section below is a cost you take on in exchange.

    02 Choosing a shard key, and range sharding

    The shard key decides everything else. A good one has three properties:

    • Many distinct values, so it can be spread thinly. Country is a poor key; user id is a good one.
    • Even traffic, so no single value is much busier than the rest.
    • It is in most queries, so most requests can go straight to one shard (section 07).

    The simplest rule is range sharding: each shard owns a range of key values, like a phone book split into A to F, G to M and so on. Range scans are cheap, because neighbouring keys live together. But if the key only ever grows, such as an order id or a timestamp, every new row lands past the last boundary: on the last shard.

    New keysYour app, 2 writes a secondNode A10Database server1,000–1,009Node B10Database server1,010–1,019Node C10Database server1,020–1,029Node D10Database server1,030 and up
    Keys stored
    40
    New writes on one shard
    –

    Click any key to follow it and see what happens to it.

    Four shards split the order ids that already exist into equal ranges. New orders keep coming.
      Try this. Watch every new order fly to node D while A, B and C get nothing, and see “New writes on one shard” sit at 100%. Tick the box to shard by random user id instead: new keys now land on all four.

      Range sharding suits keys that arrive in random order and queries that scan ranges. For ids and timestamps that only grow, hash the key first.

      03 Hash sharding, and why mod N hurts

      Hashing turns any key into a number that looks random, so even neighbouring ids like 1041 and 1042 land far apart. The obvious rule is hash(key) % N, where N is the number of nodes. It spreads keys evenly and needs no lookup table.

      The trouble starts when N changes. A key stays put only if its hash gives the same remainder for N and for N + 1. For almost every key it does not, so adding one node moves nearly everything, all at once, while the system is serving traffic.

      Node A14Database server29% of keysNode B11Database server23% of keysNode C13Database server27% of keysNode D10Database server21% of keys
      Moved by last change
      –
      Share that moved
      –
      User 5380 lives on
      Node B

      Following user 5380, now on node B.

      1. 0.0s Stored on node B: hash % 4 = 1.
      48 users on four nodes by hash(key) % N. The marked key is the one followed in the stats.
        Try this. Add a node. Squares fly between every pair of nodes and each box becomes a patchwork of colours: 42 of 48 keys moved to make room for one new node. Remove it again and they all fly back.

        With mod N, growing by one node means moving about N/(N + 1) of your data. That is the problem consistent hashing solves.

        04 Consistent hashing: the ring

        Picture every possible hash value on a circle, from 0 at the top round to the largest value just before it. Each node is hashed onto the circle too, at a point called its token. To find a key’s node, hash the key and walk clockwise until you reach a token. That node owns it.

        So each node owns the arc that ends at its token. Adding a node drops one new token on the ring: it takes over part of one arc, and only the keys in that part move, all to the new node. Removing a node hands its arc to the next token clockwise. Every other key stays exactly where it was.

        ABCDuser 67Hash ring0 at the top, rising clockwise4 nodes · 1 token eachNodes: share of the ringNode A29% · 18 keysNode B23% · 9 keysNode C27% · 8 keysNode D21% · 13 keysThe thin line on each bar is a fair share.
        Moved by last change
        –
        Share that moved
        –
        User 67 lives on
        Node A

        Following user 67, now on node A.

        1. 0.0s Stored on node A: first token clockwise from 20.3% round the ring.
        The coloured band shows which node owns each arc. Dots are keys at their hash; the dashed arrow walks one key clockwise to its owner.
          Try this. Add a node. A new colour takes over one stretch of the ring, the dots in that stretch keep their old colour, and only about one key in five moved. Remove it again: only those same keys move back.

          With a ring, adding or removing a node moves only about 1/N of the keys, and only between the nodes next to the change.

          05 Virtual nodes: smoothing the arcs

          One token per node has two flaws. Random tokens make uneven arcs, so one node can own half the ring while another owns a sliver. And when a node joins or leaves, all the moving keys come from, or go to, a single neighbour, which takes the whole load of the move.

          The fix is to give every node many tokens, called virtual nodes. Each node now owns many small arcs scattered round the ring. Their sizes average out, and a new node takes a little from everyone instead of a lot from one node. A bigger machine can simply get more tokens. Cassandra and the original Amazon Dynamo design both work this way.

          ABCDHash ring0 at the top, rising clockwise4 nodes · 1 token eachNodes: share of the ringNode A9% · 9 keysNode B3% · 2 keysNode C18% · 20 keysNode D71% · 89 keysThe thin line on each bar is a fair share.
          Biggest node holds
          71%
          Fair share
          25%
          Moved by last change
          –

          Click any key to follow it and see what happens to it.

          Four nodes and 120 keys. The bars show how much of the ring each node owns.
            Try this. With one token each, node D owns about 70% of the ring and node B about 3%. Slide tokens per node up to 64: every bar settles near the fair-share line. Then add a node and see keys leave every node, not just one.

            Use many tokens per node, or a fixed number of slots that are handed out to nodes. Both give even arcs and spread out the work of a move.

            The fixed-slot version is common: Redis Cluster hashes every key into one of 16,384 slots, and Citus and Kafka fix the number of shards or partitions up front. The key-to-slot rule never changes, so moving data means moving whole slots between nodes.

            06 Hot keys: what no hash can spread

            Hashing spreads different keys. It cannot spread one key. If a celebrity account gets half of all reads, every one of those reads goes to the node that owns that key, however many nodes you add. That node melts while the others idle.

            The usual fixes:

            • Cache it in front of the shards, so most reads never reach them.
            • Split the key into sub-keys such as celebrity#0 to celebrity#7, each with its own hash. Writes go to one sub-key; reads either pick one at random (for copies) or gather all of them (for a counter split in parts).
            • Add read replicas for the hot shard only.
            ClientsYour users, 24 reads a secondCacheCopy in memory, offNode A9Database server0 reads/s, limit 10Node B6Database server0 reads/s, limit 10Node C ★6Database server0 reads/s, limit 10Node D3Database server0 reads/s, limit 10
            Busiest node
            0/s
            Timed out, last 5 s
            0
            Served by cache
            0

            Click any key to follow it and see what happens to it.

            24 reads a second. Each node can serve 10. Half the reads are for the celebrity (the star); gold dots are those reads, red ones timed out.
              Try this. Raise nodes to 6: the star’s node is still red. Now split the celebrity into 4 keys and see the stars spread over several nodes and the timeouts nearly stop. Or switch the split off and turn on the cache: gold reads stop at the cache.

              Look for hot keys before you shard, and plan for them. Adding nodes fixes uneven key counts, not one popular key.

              07 Cross-shard queries

              A router (or a smart client) knows which node owns which key. A query that includes the shard key goes straight to one node. A query that does not, such as “all orders for this product” when orders are sharded by user, must ask every node and merge the answers. This is scatter-gather, and it is as slow as the slowest node, and it gets slower as you add nodes.

              • Joins work inside one shard. Store rows that are joined together under the same shard key (all of a user’s orders with the user) so the join stays local.
              • Global uniqueness, such as “no two users share an email”, cannot be checked on one shard unless email is the shard key. The usual fix is a second lookup table sharded by email.
              • Counts and sorts across everything need every shard, so they usually move to an analytics copy.
              RouterKnows which node owns which keyNode A12Database serverAnswers in 19 msNode B6Database serverAnswers in 19 msNode C7Database serverAnswers in 46 msNode D7Database serverAnswers in 20 ms
              Nodes asked
              –
              Time to answer
              –

              Click any key to follow it and see what happens to it.

              Orders sharded by user id. Each node answers at its own speed; node C is slow. Dots are requests going out and answers coming back.
                Try this. Get one user’s orders: one node is asked, and the answer comes back as fast as that node is. Then find orders for a product: every node is asked, and the router waits for slow node C before it can answer.

                Pick the shard key from your most common queries, and keep rows that are read together under the same key.

                08 Transactions across shards

                A transaction on one shard is an ordinary database transaction. A transfer between two users on different shards is not: each shard can commit on its own, and you need both to commit or neither.

                The classic protocol is two-phase commit. A coordinator asks every shard involved to prepare: write the change, lock the rows and promise it can commit. When all have said yes, it tells them to commit. That costs an extra round trip, and rows stay locked across both. Worse, if the coordinator dies after the prepare, the shards cannot decide on their own. Their rows stay locked, in doubt, until it comes back.

                RouterKnows which node owns which keyNode A12Database serverAnswers in 19 msNode B6Database serverAnswers in 19 msNode C7Database serverAnswers in 46 msNode D7Database serverAnswers in 20 ms
                Nodes asked
                –
                Round trips
                –
                Time to answer
                –
                Rows locked
                0

                Click any key to follow it and see what happens to it.

                Black dots are prepare, orange dots are commit, green are replies. Rows locked by a transaction have a red outline.
                  Try this. Transfer on one shard: one node, one round trip. Transfer across shards: two nodes, two round trips. Now crash the coordinator mid-way: two rows stay locked for seconds and nothing else can change them.

                  Design so most transactions stay on one shard. When they cannot, use the database’s distributed transactions, or break the work into steps that can be retried or undone (a saga).

                  09 Rebalancing while the system runs

                  The moves in the earlier labs were instant. Real ones copy data while users keep writing to it. The usual shape: copy a key (or a whole slot) to its new node, keep it in sync, then cut over so the new node becomes the owner.

                  The dangerous moment is between the copy and the cut-over. A write that lands on the old node after its key was copied never reaches the new one, and is lost when the old copy is dropped. So during a move, writes must reach both copies, or be replayed from a change log, or be paused for a moment while the key cuts over.

                  Node A27Database server56% of keysNode B10Database server21% of keysNode C11Database server23% of keys
                  Keys still to move
                  0
                  Writes sent to both
                  0
                  Lost writes
                  0

                  Click any key to follow it and see what happens to it.

                  Users update their keys 10 times a second. Dashed keys are waiting to move; a key crossing between boxes is being copied. Orange outlines are writes landing.
                    Try this. Add a node and watch keys travel one at a time, with lost writes ticking up whenever an update hits a key mid-copy. Tick “Send writes to both nodes”, press Reset, add a node again: the same writes now reach both copies and none is lost.

                    Rebalancing is slow on purpose and must handle writes in flight. Tools like Vitess, Citus and MongoDB’s balancer exist largely to do this part safely.

                    10 Each shard needs its own replicas

                    Sharding splits the data; it does not copy it. With 10 shards on 10 machines, any one failure takes a tenth of your users offline, and with more machines a failure somewhere becomes routine. So each shard is usually a small replica set: a primary that takes writes and one or more replicas that can take over.

                    How replicas stay in sync, and what you can lose when one is promoted, is the subject of the database lesson. Here, the point is the shape: shards multiply your capacity, replicas multiply your copies, and you need both.

                    ClientsYour users, 8 reads a secondNode A18 (+1)Database server50% of keysNode B10Database server28% of keysNode C8Database server22% of keys
                    Copies stored
                    36
                    Keys unavailable
                    0
                    Failed reads
                    0

                    Click any key to follow it and see what happens to it.

                    Three shards and 8 reads a second. Faded squares are replica copies of the same keys.
                      Try this. With no replicas, kill a primary: a third of the keys go dark and reads to them fail until you bring it back. Set replicas to 1 and kill it again: after a short failover the keys jump to the replica and reads succeed. Copies stored doubles.

                      Plan copies per shard: three copies of each shard is a common default, across separate machines or zones.

                      11 How real systems shard

                      Each product below makes the choices above in its own way. A rough map:

                      SystemHow keys map to shardsMoving dataCross-shard work
                      Vitess (MySQL)A vindex turns the key into a keyspace id (often a hash); each shard owns a range of keyspace idsOnline resharding by splitting rangesRouter plans scatter queries; atomic cross-shard transactions are an option
                      Citus (Postgres)Hash of a distribution column into a fixed number of shards, placed on worker nodesShard rebalancer moves whole shardsJoins are fast on co-located tables; distributed transactions supported
                      MongoDBShard key, ranged or hashed, split into chunksA balancer migrates chunks between shardsQueries without the shard key go to every shard; multi-document transactions supported
                      Cassandra, DynamoDBPartition key hashed; Cassandra uses a token ring with virtual nodes, DynamoDB splits partitions for youCassandra streams token ranges; DynamoDB does it behind the scenesDesigned around single-partition queries; model tables per query
                      Redis ClusterCRC16 of the key into one of 16,384 slots, slots assigned to primariesSlots migrate key by key; clients follow redirectsMulti-key commands only within one slot; hash tags like {user42} force keys together

                      Check the current docs before you choose: these systems change between versions, and managed offerings differ from self-hosted ones.

                      12 Check yourself

                      1. You shard orders by order id, using ranges. Order ids only ever grow. What happens to writes?

                      2. You use hash(key) % N with 10 nodes and add an eleventh. Roughly how many keys move?

                      3. On a consistent hash ring with 10 nodes, you add an eleventh. Which keys move?

                      4. One user with 50 million followers gets a third of all reads. You add more shards. What happens to that user’s shard?

                      5. Users are sharded by user id. Signup must check that an email is not already used. What is the problem?

                      Next partRetries and circuit breakers