Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Core concepts · Lesson 5 of 44

Replication and sharding

How a database scales past one machine. Replicas for reads and failover, shards for writes and size, and the shard-key decisions that are very hard to undo.

ConceptCore14 min readUpdated

  • 2 architecture diagrams
  • 1 sequence flow
  • 1 data model
  • 2 code samples
  • 6 interviewer follow-ups
  • 1 decision checkpoint
  • 1 capacity calculator
  • 3 self-checks

Read first: Caching

By the end you will be able to
  • Distinguish replication (copies for reads and availability) from sharding (splitting data for write and size limits).
  • Explain replication lag and the read-your-writes problem.
  • Compare range, hash and directory sharding, and say what consistent hashing fixes.
  • Choose a shard key and name the costs: hot shards, cross-shard queries, resharding.
Interactive companion

Watch consistent hashing move keys

Add and remove nodes on a ring, compare hash mod N with a consistent hash ring, and tune virtual nodes to even out the load.

Open the interactive
Prefer to watch? · 14 min video

2 code samples (64 lines), collapsed so the explanation stays in focus.

One database server eventually runs out of something: read capacity, write capacity, disk, or the ability to survive its own failure. Two different techniques address two different problems, and mixing them up is one of the most common interview mistakes.

  • Replication keeps copies of the same data on several machines. It helps with read throughput and availability.
  • Sharding (partitioning) splits the data across machines, each holding a different part. It helps with write throughput and total data size.

Before reaching for either, exhaust the cheap options: add indexes, fix slow queries, add a cache, and scale the machine up. Many systems never need more.

Database replication

In the common leader-follower setup, all writes go to one leader. The leader streams its changes to followers, and reads can be served by any of them. In most databases that stream is the write-ahead log the leader already keeps for crash recovery (see storage engines and indexes).

Fig. Writes go to the leader; reads can use any follower
Fig. Writes go to the leader; reads can use any follower

What you gain: read capacity grows with the number of followers, and if the leader fails, a follower can be promoted. Across regions the same trade is sharper: multi-region design computes how many acknowledged writes a failover loses and what a quorum across regions costs per write.

What you pay for:

  • Replication lag. Replication is usually asynchronous, so followers are slightly behind. A user writes something, then reads from a follower that has not received it yet and sees the old value, so their own update seems lost. This is a read-your-writes violation. Fixes: read from the leader for a short time after a write, or route a user's reads to a follower that is known to be caught up.
  • Failover is risky. Promoting a follower can lose writes the old leader had not yet sent, and if the old leader comes back believing it is still in charge, you get two leaders ("split brain"). Real systems use consensus or a fencing mechanism to prevent this (see consensus, leader election and distributed locks).
  • Writes do not scale (in a single-leader setup). Every write still goes through one leader. Multi-leader and leaderless designs exist, but they trade this limit for conflict handling.

Synchronous replication waits for followers to confirm before acknowledging a write. It avoids losing data but makes writes slower and makes the leader depend on the followers' health. Many systems use a hybrid: one synchronous follower, the rest asynchronous.

Copies are not the only protection. For large, cold data, erasure coding stores parity fragments instead of full copies and survives the same number of failures for about half the space, at the price of more expensive repairs: see erasure coding, replication and durability and the object storage case study.

Replication lag in motion

Fig. A read-your-writes violation
Fig. A read-your-writes violation

Database sharding

When a single leader cannot absorb the writes or hold the data, split the data into shards, each with its own leader and replicas. A router (or the client library) decides which shard owns a given record.

Strategies

Range-based. Each shard owns a contiguous range of keys, for example A–F, G–M. Range queries are cheap because neighbouring keys live together. The risk is hotspots: if keys are timestamps or sequential IDs, all new writes land on the last shard.

Hash-based. Hash the key and use the result to choose the shard. Load spreads evenly, but range queries now touch every shard. The naive form, hash(key) mod N, has a nasty property: changing N remaps almost every key, forcing a massive data move.

Directory-based. A lookup table maps keys to shards. Maximum flexibility, but the directory becomes a critical dependency that must be fast and highly available.

Consistent hashing

Consistent hashing fixes the remapping problem. Arrange hash values in a ring and place both servers and keys on it. Each key belongs to the next server clockwise. When a server joins or leaves, only the keys between it and its neighbour move, roughly 1/N of the data instead of nearly all of it.

Plain consistent hashing can leave servers with uneven slices. The standard refinement is virtual nodes: each physical server owns many points on the ring, which smooths the distribution and lets stronger machines take more.

Before choosing how to split, check that you need to. The calculator turns daily users, write rate and retention into storage and write throughput, and shows which of the two sets the shard count. A system that fits comfortably on a few machines should be replicated, not sharded.

Try it · capacity estimatorWhen does a database need shards?

HLD

Routing a request to a shard

Fig. The shard key picks the shard
Fig. The shard key picks the shard

The router needs a small, rarely changing map from hash range to shard. It is configuration, not user data, so cache it in every router and refresh it when it changes.

shard_mapconfig store
  • shard_idsmallint

    PK
  • hash_startbigint

    inclusive

  • hash_endbigint

    exclusive

  • primary_hosttext

  • replica_hoststext

    comma separated

  • statussmallint

    active, draining, read-only

Moving data between shards means changing a row here, so the change is atomic and easy to roll back.

Choosing the shard key

This is the decision that is hardest to change later. Before the list, choose one.

Decision checkpoint · pick one

You are sharding the message table of a chat app. The main query is "show the latest messages in this conversation". Conversations range from two people to groups of thousands. Which shard key do you pick?

Commit to an answer first. The reasoning for every option appears after you pick.

A good key:

  • Has high cardinality and spreads load evenly.
  • Matches the dominant access pattern, so most queries touch one shard.
  • Does not create a hot shard (a celebrity user, a popular tenant, the latest timestamp).

Example: for a chat application whose main query is "messages in this conversation", sharding by conversation ID keeps one conversation on one shard. Sharding by message ID spreads load beautifully but makes reading a conversation a query across every shard. Geographic data follows the same rule: places and drivers are sharded by area, not by ID, so that a search around one point touches one shard, as the proximity service shows.

The costs of sharding

  • Cross-shard queries and joins become expensive or impossible. Denormalise, or accept scatter-gather queries.
  • Cross-shard transactions need distributed protocols such as two-phase commit, with real latency and availability costs (it can block if the coordinator fails at the wrong moment). Alternatives such as sagas, which undo earlier steps with compensating actions, trade atomicity for availability. Design so that operations that must be atomic live on one shard.
  • Resharding (changing the number of shards or the key) is operationally painful. Plan for it: start with more logical shards (or hash slots) than physical machines, so you can move whole shards rather than splitting them. This fixed-number-of-partitions approach is a common alternative to a classic hash ring.
  • Hot shards need special handling: split the hot key, add a cache, or isolate large tenants. The sharding hot-spot simulator shows one refusing requests while the other shards sit idle, and what each fix costs. For a cache cluster the same ideas play out differently, because a moved key is a miss, not a migration: see designing a distributed cache.
  • Unique IDs can no longer come from a single auto-increment counter.

NoSQL and "automatic" sharding

Many distributed databases shard for you and expose it as configuration. Some hash keys onto a ring (Cassandra and Dynamo-style stores), some use a fixed number of hash slots (Redis Cluster has 16,384), and some split key ranges automatically as they grow. That moves the complexity but does not remove the trade-offs: you still choose a partition key, still face hot partitions, and usually give up joins and multi-key transactions. Know what the system does under the hood so you can predict where it will hurt.

LLD

A consistent hash ring in C#

Consistent hashing is easy to describe and easy to get subtly wrong. Each node is placed on a ring at many points (virtual nodes), a key belongs to the first point at or after its hash, and the search wraps around at the end.

C# · HashRing38 lines
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public sealed class HashRing
{
    private readonly int _virtualNodes;
    private readonly SortedDictionary<ulong, string> _ring = new SortedDictionary<ulong, string>();
    private ulong[] _points = Array.Empty<ulong>();           // the ring's hashes, sorted, for binary search

    public HashRing(int virtualNodes) { _virtualNodes = virtualNodes; }

    /// <summary>A hash whose value is fixed by its definition, so every server computes the same one.</summary>
    public static ulong Hash(string text)
    {
        ulong h = 14695981039346656037UL;                     // FNV-1a, 64 bit
        foreach (byte b in Encoding.UTF8.GetBytes(text)) { h ^= b; h *= 1099511628211UL; }
        h ^= h >> 33; h *= 0xff51afd7ed558ccdUL;              // a finalizer, so similar names spread out
        h ^= h >> 33; h *= 0xc4ceb9fe1a85ec53UL;
        h ^= h >> 33;
        return h;
    }

    public void AddNode(string node)
    {
        for (int i = 0; i < _virtualNodes; i++) _ring[Hash($"{node}#{i}")] = node;
        _points = _ring.Keys.ToArray();
    }

    public string Locate(string key)
    {
        int i = Array.BinarySearch(_points, Hash(key));
        if (i < 0) i = ~i;                                    // the first point after the key
        if (i == _points.Length) i = 0;                       // past the last point: wrap to the first
        return _ring[_points[i]];
    }
}

The test checks the two properties that matter: load is spread evenly, and adding a node moves only the keys that now belong to it. For contrast, it counts how many keys hash mod N would move for the same change.

C#26 lines
using System.Diagnostics;

var ring = new HashRing(100);
foreach (var node in new[] { "a", "b", "c", "d" }) ring.AddNode(node);

var owner = new string[20000];
var share = new Dictionary<string, int>();
for (int i = 0; i < owner.Length; i++)
{
    owner[i] = ring.Locate($"key-{i}");
    share[owner[i]] = share.GetValueOrDefault(owner[i]) + 1;
}
Debug.Assert(share.Count == 4 && share.Values.All(c => c > 4000 && c < 6000));    // about 25% each

ring.AddNode("e");
int moved = 0, movedToNew = 0, modMoved = 0;
for (int i = 0; i < owner.Length; i++)
{
    string now = ring.Locate($"key-{i}");
    if (now != owner[i]) { moved++; if (now == "e") movedToNew++; }
    ulong h = HashRing.Hash($"key-{i}");
    if (h % 4 != h % 5) modMoved++;                      // the same four-to-five change with hash mod N
}
Debug.Assert(moved == movedToNew);                       // keys only ever move to the new node
Debug.Assert(moved > 3000 && moved < 5000);              // about one fifth: 20%
Debug.Assert(modMoved > 14000);                          // hash mod N reshuffles about four fifths: 80%

Do not use string.GetHashCode() to place data. Since .NET Core it is randomised per process, so two servers would disagree about which shard owns a key. The hash must be fixed by its specification: FNV-1a here, and MurmurHash3, xxHash or SHA-256 in practice.

Senior depth

What senior interviews ask about replication and sharding

Interviewer follow-upL6How do you add a shard without downtime?How to answer

Avoid placing data with hash modulo N, because changing N moves almost everything. Use consistent hashing, or create many small logical shards (say a thousand) mapped onto a few machines so that resharding means moving whole logical shards. The procedure: copy a snapshot, stream the changes made since, verify the copy, switch the shard map atomically, and only then delete the old data. Throttle the copy so it does not hurt production traffic.

Interviewer follow-upL6One shard is far hotter than the rest. What do you do?How to answer

First check the shard key: a skewed key (a celebrity account, a large tenant) matters more than the shard count. Options: cache the hot data, split the hot range into smaller ranges, move that tenant to dedicated capacity, or add a random suffix to the hot key to spread writes and merge on read. Each option has a cost in read complexity, which you should state.

Interviewer follow-upL7A transaction must update rows on two different shards. What are your options?How to answer

First try to avoid it by choosing a shard key that keeps related data together. Otherwise, two-phase commit gives atomicity but blocks while the coordinator is down and holds locks. A saga performs the steps as separate local transactions with compensating actions to undo them, which stays available but is only eventually consistent and needs idempotent steps. Choose based on how much temporary inconsistency the business tolerates.

Interviewer follow-upL6After a failover the old leader comes back and still thinks it is in charge. How do you stop it from corrupting data?How to answer

Fence it. Give each leadership epoch an increasing token and make the storage or followers reject writes carrying an older token, or use a lease the old leader cannot renew without a majority. Leader election through consensus ensures a majority agrees on exactly one leader per term.

Interviewer follow-upL6Why can you not use string.GetHashCode() to choose a shard in .NET?How to answer

Because it is not stable. In .NET Core and later, string hash codes are randomised per process, so two servers (or one server after a restart) would disagree about where a key lives, and data would go to the wrong shard. Use a hash whose output is fixed by its specification, such as FNV-1a, MurmurHash3, xxHash or SHA-256, and encode the string the same way everywhere (UTF-8).

Interviewer follow-upL6How many virtual nodes per server, and what does it cost?How to answer

Enough to even out the load. With a handful the shares vary a lot; 100 to 200 per server is a common range, and the spread shrinks roughly with the square root of the count. The cost is memory for the ring, a rebuild when membership changes, and a slightly slower lookup (a binary search over all points). Servers of different capacity get points in proportion to it.

Summary

Replication copies data for reads and survival, at the price of lag. Sharding splits data for writes and size, at the price of joins, transactions and flexibility. Choose the shard key from the access pattern, use consistent hashing so growth does not reshuffle everything, and delay sharding as long as you honestly can.

Check yourself

Try answering out loud before you reveal each answer.

QuestionWhich problem does replication solve, and which does sharding solve?Reveal answer

Replication keeps copies of the data and helps read throughput and availability. Sharding splits the data and helps write throughput and total size.

QuestionWhy is hash(key) mod N a poor way to assign shards when N changes?Reveal answer

Changing N remaps almost every key, forcing a huge data move. Consistent hashing moves only about 1/N of the keys.

QuestionYou shard a chat app by message ID instead of conversation ID. What do you give up?Reveal answer

Load spreads nicely, but reading one conversation now touches every shard (scatter-gather). The shard key should match the dominant access pattern.

Lesson 5 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 6Queues and asynchronous workWhy you decouple slow or bursty work with a queue, what at-least-once delivery really means, and how idempotency, retries and backpressure keep it safe.

Send a message

It goes straight to my inbox. I usually reply within a few days.