›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Sharding in Depth: Shard Keys, Consistent Hashing, Hot Keys and Global IDs, in C# and Python

November 14, 2025 · 38 min read

Software Architecture, Design Patterns, Distributed Systems, Databases, Scalability, Sharding, C#, Python

Sharding is the move you make when one database server can't hold your data or keep up with your writes. You split the data across several servers, each holding a slice, and route every request to the slice that owns it. It works, and every big system does it somewhere. It also turns a lot of easy things into hard ones: joins, transactions, unique IDs, schema changes and "just count the rows".

This post goes through the decisions in the order you face them, with code for each mechanism in C# and Python. I'll keep coming back to one idea: the shard key decides almost everything, and it's the one choice that's very expensive to change later.

SectionThe question it answers
VocabularyPartitioning, sharding, vertical, horizontal: which is which?
Choosing a shard keyWhat makes a good key?
Hash, range and directoryHow does a request find its shard?
Consistent hashingHow do you add a server without moving everything?
ReshardingHow do you move data while the system is live?
Hot partitionsWhat do you do about one key that gets all the traffic?
Cross-shard queries and transactionsWhat happens when a query needs more than one shard?
Global IDsHow do you make unique IDs without a central counter?
Real systemsHow do Cosmos DB, Azure SQL, Citus, Vitess, MongoDB and DynamoDB do it?
When not to shardWhat should you try first?

How to run the code. C# snippets are .NET 10 file-based apps (dotnet run file.cs). The scatter-gather one uses SQLite through a #:package Microsoft.Data.Sqlite line. Python snippets use only the standard library and run with python3 (3.12). Every output block is pasted from a real run. The C# and Python outputs are identical everywhere, and the reason is worth a section of its own, so it's right below the first snippet.

Vocabulary: partitioning vs sharding

People use these words loosely, so here's how I'll use them.

  • Vertical partitioning splits by columns or by feature. The users table keeps hot columns, and the rarely read bio and preferences move to another table. Or the billing tables move to their own database. Each piece still holds every row it's responsible for.
  • Horizontal partitioning splits by rows. Orders from 2023 go in one partition, 2024 in another. Postgres declarative partitioning and SQL Server partitioned tables do this inside one server.
  • Sharding is horizontal partitioning across servers. Each shard is a separate database with its own CPU, memory, disk and failure domain. The application or a proxy routes each query to the right one.

Partitioning inside one server mostly helps with maintenance (drop an old partition instead of deleting rows) and with pruning scans. Sharding is what adds capacity, and it's also what adds the distributed systems problems.

Choosing a shard key

The shard key is the field that decides which shard a row lives on. A good one has four properties:

  1. High cardinality. Many distinct values, far more than the number of shards you'll ever have. country has about 200 values and a few of them dominate. customer_id has millions.
  2. Even distribution, of data and of traffic. Not just rows per shard but requests per shard. A key can spread rows evenly and still send most writes to one place, as the range example below shows.
  3. Matches your hottest queries. The query you run most often should include the shard key, so it goes to one shard. If the main screen is "this customer's orders", shard by customer. If you shard by order ID, that screen becomes a query to every shard.
  4. Stable. A row's key shouldn't change. Changing it means moving the row between servers.

For SaaS, the tenant ID is often the right answer. Almost every query is scoped to one tenant, tenants rarely need to join each other's data, and a tenant is a natural unit to move. The catch is that tenants aren't equal in size, which is what directory sharding (below) is for.

Composite keys help when no single field works. Cosmos DB calls these synthetic partition keys (for example tenantId-yyyy-mm), and it also supports hierarchical partition keys, so tenantId then userId can spread one big tenant across partitions while keeping queries for a tenant targeted.

Hash, range and directory routing

Three ways to turn a key into a shard number:

  • Hash sharding: shard = hash(key) mod N. Spreads keys evenly and kills hot spots from sequential keys. The price is range queries: neighboring keys land on unrelated shards.
  • Range sharding: each shard owns a contiguous range of keys. Range queries hit one or two shards, and splitting a range is easy. The price is that sequential keys (timestamps, auto-increment IDs, new signups) all land on the last range.
  • Directory sharding: a lookup table maps each key (often a tenant) to a shard. Any rule can fill it, a big tenant can get its own shard, and moving a tenant is a data copy plus a one-row update. The price is that the directory is now a critical dependency, so it gets cached heavily and replicated.

The demo routes 1,000 customers to 4 shards with hash and range, then shows where the newest 100 signups go (where the write traffic is), and which shards a range query for customers 100 to 120 touches.

import hashlib

SHARDS = 4


def stable_hash(key: str) -> int:
    # Never use hash(): Python randomizes it per process. Use a hash with a fixed definition.
    return int.from_bytes(hashlib.md5(key.encode(), usedforsecurity=False).digest()[:8], "big")


def hash_route(customer_id: int) -> int:
    return stable_hash(f"cust-{customer_id}") % SHARDS


RANGES = [(1, 250), (251, 500), (501, 750), (751, 10**9)]  # shard i owns RANGES[i]


def range_route(customer_id: int) -> int:
    return next(i for i, (lo, hi) in enumerate(RANGES) if lo <= customer_id <= hi)


class Directory:
    """A lookup table: tenant -> shard. Any rule can fill it, and moving a tenant is one row."""

    def __init__(self):
        self.table = {"acme": 4}  # the biggest tenant gets shard 4, a fifth shard of its own

    def route(self, tenant: str) -> int:
        if tenant not in self.table:
            self.table[tenant] = stable_hash(tenant) % SHARDS  # default rule, remembered
        return self.table[tenant]


def spread(route, ids):
    counts = [0] * SHARDS
    for i in ids:
        counts[route(i)] += 1
    return counts


everyone, newest = range(1, 1001), range(901, 1001)
for name, route in (("hash", hash_route), ("range", range_route)):
    touched = sorted({route(i) for i in range(100, 121)})
    print(f"{name:<6} all 1000: {spread(route, everyone)}  newest 100: {spread(route, newest)}"
          f"  ids 100-120 live on shards {touched}")

d = Directory()
print("directory:", {t: d.route(t) for t in ("acme", "globex", "initech", "umbrella")})
d.table["globex"] = 3  # rebalancing one tenant = copy its data, then update one row
print("after moving globex:", {t: d.route(t) for t in ("acme", "globex", "initech", "umbrella")})
hash   all 1000: [239, 225, 265, 271]  newest 100: [28, 22, 28, 22]  ids 100-120 live on shards [0, 1, 2, 3]
range  all 1000: [250, 250, 250, 250]  newest 100: [0, 0, 0, 100]  ids 100-120 live on shards [0]
directory: {'acme': 4, 'globex': 1, 'initech': 2, 'umbrella': 0}
after moving globex: {'acme': 4, 'globex': 3, 'initech': 2, 'umbrella': 0}
using System.Security.Cryptography;
using System.Text;

const int Shards = 4;

// Never use string.GetHashCode(): .NET randomizes it per process. Use a hash with a fixed definition.
static ulong StableHash(string key) =>
    System.Buffers.Binary.BinaryPrimitives.ReadUInt64BigEndian(MD5.HashData(Encoding.UTF8.GetBytes(key)));

int HashRoute(int customerId) => (int)(StableHash($"cust-{customerId}") % Shards);

(int Lo, int Hi)[] ranges = [(1, 250), (251, 500), (501, 750), (751, int.MaxValue)]; // shard i owns ranges[i]
int RangeRoute(int customerId) => Array.FindIndex(ranges, r => r.Lo <= customerId && customerId <= r.Hi);

string Spread(Func<int, int> route, IEnumerable<int> ids)
{
    var counts = new int[Shards];
    foreach (var i in ids) counts[route(i)]++;
    return $"[{string.Join(", ", counts)}]";
}

var everyone = Enumerable.Range(1, 1000);
var newest = Enumerable.Range(901, 100);
foreach (var (name, route) in new (string, Func<int, int>)[] { ("hash", HashRoute), ("range", RangeRoute) })
{
    var touched = Enumerable.Range(100, 21).Select(route).Distinct().Order();
    Console.WriteLine($"{name,-6} all 1000: {Spread(route, everyone)}  newest 100: {Spread(route, newest)}" +
                      $"  ids 100-120 live on shards [{string.Join(", ", touched)}]");
}

var d = new Directory(Shards, StableHash);
string[] tenants = ["acme", "globex", "initech", "umbrella"];
string Show() => "{" + string.Join(", ", tenants.Select(t => $"{t}: {d.Route(t)}")) + "}";
Console.WriteLine($"directory: {Show()}");
d.Table["globex"] = 3; // rebalancing one tenant = copy its data, then update one row
Console.WriteLine($"after moving globex: {Show()}");

// A lookup table: tenant -> shard. Any rule can fill it, and moving a tenant is one row.
class Directory(int shards, Func<string, ulong> hash)
{
    public Dictionary<string, int> Table { get; } = new() { ["acme"] = 4 }; // the biggest tenant gets shard 4, a fifth shard of its own

    public int Route(string tenant)
    {
        if (!Table.TryGetValue(tenant, out var shard))
            Table[tenant] = shard = (int)(hash(tenant) % (ulong)shards); // default rule, remembered
        return shard;
    }
}
hash   all 1000: [239, 225, 265, 271]  newest 100: [28, 22, 28, 22]  ids 100-120 live on shards [0, 1, 2, 3]
range  all 1000: [250, 250, 250, 250]  newest 100: [0, 0, 0, 100]  ids 100-120 live on shards [0]
directory: {acme: 4, globex: 1, initech: 2, umbrella: 0}
after moving globex: {acme: 4, globex: 3, initech: 2, umbrella: 0}

The table in that output is the whole trade-off:

  • Range has perfect balance at rest (250 each) and the worst possible write pattern: all 100 new customers on shard 3. It's also the only one where the range query hit a single shard.
  • Hash spreads the new customers well (28, 22, 28, 22) but scatters customers 100 to 120 across all four shards.
  • Hash balance at rest isn't perfect either (225 to 271). With few keys per shard, hashing is lumpy. It evens out as counts grow.
  • The directory lets acme sit on a dedicated fifth shard, and moving globex was one dictionary update after the data copy.

Why the two languages agree: never use the built-in hash

Both versions hash with MD5 and take the first 8 bytes as a big-endian number, which is why every number above matches. That isn't a detail. The obvious choices are wrong in both languages:

  • Python's hash() on a string is randomized per process (see PYTHONHASHSEED). Two app servers would route the same key to different shards.
  • .NET's string.GetHashCode() is also randomized per process in .NET Core and later, for the same reason.

A routing hash has to be stable across processes, machines, languages and versions. MD5 is fine here because nobody is relying on it for security. MurmurHash3 and xxHash are faster and common in real systems. Whatever you pick, write it down as part of the data format, because changing it later moves every key.

Consistent hashing with virtual nodes

hash(key) mod N has a nasty property: when N changes, almost every key moves. Going from 4 shards to 5 sends a key to a new shard unless h mod 4 and h mod 5 happen to agree, which is true for about 1 in 5 keys. So about 80% of the data has to move, all at once.

Consistent hashing, from the 1997 paper by Karger and colleagues, fixes this. Put both servers and keys on a ring of hash values. Each key belongs to the first server point clockwise from it. Adding a server only takes over the arcs just before its points, so only those keys move, about 1/N of the total.

With one point per server, the arcs are random lengths, so the load is badly uneven. Virtual nodes fix that: give each server many points (node-a#0, node-a#1, and so on), and the arcs average out. The demo measures both effects on 10,000 keys.

import bisect
import hashlib


def h(key: str) -> int:
    return int.from_bytes(hashlib.md5(key.encode(), usedforsecurity=False).digest()[:8], "big")


class Ring:
    """Consistent hashing: each node owns the arc that ends at each of its points on the ring."""

    def __init__(self, nodes, vnodes):
        self.vnodes, self.points, self.owner = vnodes, [], {}
        for node in nodes:
            self.add(node)

    def add(self, node):
        for v in range(self.vnodes):
            point = h(f"{node}#{v}")       # each vnode is just another point for the same node
            bisect.insort(self.points, point)
            self.owner[point] = node

    def route(self, key):
        i = bisect.bisect(self.points, h(key)) % len(self.points)  # first point clockwise, wrapping
        return self.owner[self.points[i]]


keys = [f"key-{i}" for i in range(10_000)]
nodes = ["node-a", "node-b", "node-c", "node-d"]


def report(label, before, after):
    moved = sum(1 for k in keys if before(k) != after(k))
    load = {}
    for k in keys:
        load[before(k)] = load.get(before(k), 0) + 1
    print(f"{label:<17} load on 4 nodes min {min(load.values()):>4} max {max(load.values()):>4}"
          f"  | add a 5th: {moved / len(keys):6.1%} of keys move")


report("mod N", lambda k: nodes[h(k) % 4], lambda k: (nodes + ["node-e"])[h(k) % 5])
for vnodes in (1, 10, 100):
    ring, bigger = Ring(nodes, vnodes), Ring(nodes, vnodes)
    bigger.add("node-e")
    report(f"ring, {vnodes} vnode{'s' if vnodes > 1 else ''}", ring.route, bigger.route)
mod N             load on 4 nodes min 2430 max 2584  | add a 5th:  80.1% of keys move
ring, 1 vnode     load on 4 nodes min   76 max 4558  | add a 5th:   9.3% of keys move
ring, 10 vnodes   load on 4 nodes min 1690 max 4220  | add a 5th:  18.0% of keys move
ring, 100 vnodes  load on 4 nodes min 2349 max 2601  | add a 5th:  21.1% of keys move
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;

static ulong H(string key) => BinaryPrimitives.ReadUInt64BigEndian(MD5.HashData(Encoding.UTF8.GetBytes(key)));

var keys = Enumerable.Range(0, 10_000).Select(i => $"key-{i}").ToArray();
string[] nodes = ["node-a", "node-b", "node-c", "node-d"];
string[] five = [.. nodes, "node-e"];

void Report(string label, Func<string, string> before, Func<string, string> after)
{
    var moved = keys.Count(k => before(k) != after(k));
    var load = keys.GroupBy(before).Select(g => g.Count()).ToList();
    Console.WriteLine($"{label,-17} load on 4 nodes min {load.Min(),4} max {load.Max(),4}" +
                      $"  | add a 5th: {(double)moved / keys.Length,6:P1} of keys move");
}

Report("mod N", k => nodes[H(k) % 4], k => five[H(k) % 5]);
foreach (var vnodes in new[] { 1, 10, 100 })
{
    var ring = new Ring(nodes, vnodes);
    var bigger = new Ring(nodes, vnodes);
    bigger.Add("node-e");
    Report($"ring, {vnodes} vnode{(vnodes > 1 ? "s" : "")}", ring.Route, bigger.Route);
}

// Consistent hashing: each node owns the arc that ends at each of its points on the ring.
class Ring
{
    private readonly int _vnodes;
    private readonly List<ulong> _points = [];
    private readonly Dictionary<ulong, string> _owner = [];

    public Ring(IEnumerable<string> nodes, int vnodes)
    {
        _vnodes = vnodes;
        foreach (var n in nodes) Add(n);
    }

    public void Add(string node)
    {
        for (var v = 0; v < _vnodes; v++)
        {
            var point = H($"{node}#{v}");      // each vnode is just another point for the same node
            var i = _points.BinarySearch(point);
            _points.Insert(i < 0 ? ~i : i, point);
            _owner[point] = node;
        }
    }

    public string Route(string key)
    {
        var i = _points.BinarySearch(H(key));
        i = i < 0 ? ~i : i + 1;                 // first point clockwise (strictly after, like bisect_right)
        return _owner[_points[i % _points.Count]];
    }

    private static ulong H(string key) =>
        BinaryPrimitives.ReadUInt64BigEndian(MD5.HashData(Encoding.UTF8.GetBytes(key)));
}
mod N             load on 4 nodes min 2430 max 2584  | add a 5th:  80.1% of keys move
ring, 1 vnode     load on 4 nodes min   76 max 4558  | add a 5th:   9.3% of keys move
ring, 10 vnodes   load on 4 nodes min 1690 max 4220  | add a 5th:  18.0% of keys move
ring, 100 vnodes  load on 4 nodes min 2349 max 2601  | add a 5th:  21.1% of keys move

How to read it:

  • mod N: good balance, but adding a fifth node moved 80.1% of the keys. That matches the 4 in 5 estimate.
  • Ring, 1 vnode: only 9.3% moved, which sounds great until you see the load. One node had 76 keys and another had 4,558. The new node also happened to land on a short arc, so it only took 9.3% instead of its fair 20%. With one point per node, luck decides everything.
  • Ring, 100 vnodes: load between 2,349 and 2,601, and 21.1% moved, close to the ideal 20%. This is the setting you want.

The C# version uses List.BinarySearch and treats an exact match as "go one past it", which matches Python's bisect.bisect (bisect right). Without that, a key that hashed exactly onto a node's point would route differently in the two languages.

Consistent hashing is how Cassandra, DynamoDB's ancestor Dynamo, and many caches place data. Many databases take a simpler route with the same effect: create far more fixed partitions than servers (say 1,024 logical shards on 8 servers) and move whole partitions when servers are added. Cosmos DB physical partitions, Citus shards, Vitess keyspace ID ranges and Couchbase vBuckets all work roughly this way. Google's jump consistent hash is another option when shards are numbered and you only add at the end.

Rebalancing and resharding without downtime

At some point you'll move data: a shard is full, a tenant outgrew its neighbors, or the original key was wrong. Moving it while the system takes writes follows the same steps nearly everywhere:

StepWhat happensReads come fromWrites go to
1. Double-writeNew writes go to the old and the new locationOldBoth
2. BackfillCopy existing rows from old to new, in batches, without overwriting newer double-written rowsOldBoth
3. VerifyCompare counts and checksums, or shadow-read from the new location and compare resultsOld (shadow new)Both
4. Cut over readsFlip the router so reads use the new locationNewBoth
5. Stop old writesRemove the double-write once you're confidentNewNew
6. Clean upDelete the moved data from the old location, laterNewNew

Things that go wrong:

  • The double-write isn't atomic. One write succeeds and the other fails. You either need a reconciliation job, or you replace step 1 with change data capture from the old location, which is what Vitess VReplication and most online migration tools do. The transactional outbox covers the general dual-write problem.
  • The backfill overwrites newer data. Copy with "insert if not exists" or compare a version or timestamp, so a backfilled old row never replaces a double-written new one.
  • No way back. Keep the old location writable until you're sure. Steps 4 and 5 are separate on purpose, so you can flip reads back.
  • Caches and routers disagree. If routing is cached in app servers, the cutover isn't instant. Version the routing table and make old versions fail loudly.

If you can avoid needing this, do. The cheap insurance is to start with many more logical shards than physical servers. Then growth is "move partition 517 to the new server", never "change the hash function".

Hot partitions and celebrity keys

A good shard key can still fail on one value. A celebrity's post gets a million likes. One tenant runs a load test. All traffic for that key goes to one partition, and that partition hits its limit while the others sit idle. In Cosmos DB a single logical partition can't exceed 10,000 RU/s or 20 GB. DynamoDB partitions have per-partition throughput limits too.

The standard fix is key salting (DynamoDB's docs call it write sharding). For known hot keys, add a suffix (celebrity#0 to celebrity#7) so writes spread over several partitions. The cost moves to reads: reading the key now means reading every suffix and merging. So you salt only keys you've identified as hot, and you keep the list somewhere both writers and readers can see.

The demo sends 10,000 writes, half of them to one key, and tries no salting, 8 salts and 32 salts.

import hashlib

SHARDS = 4
HOT_KEYS = {"celebrity"}  # found from metrics, not guessed


def shard_of(key: str) -> int:
    return int.from_bytes(hashlib.md5(key.encode(), usedforsecurity=False).digest()[:8], "big") % SHARDS


class SaltedKeys:
    def __init__(self, salts):
        self.salts, self.next = salts, {}

    def write_key(self, key: str) -> str:
        # Hot keys get a suffix, so their writes land on several partitions. Cold keys stay as they are.
        if key not in HOT_KEYS or self.salts == 1:
            return key
        n = self.next[key] = self.next.get(key, -1) + 1  # round-robin; a random pick works too
        return f"{key}#{n % self.salts}"

    def read_keys(self, key: str) -> list[str]:
        # The price: reading a hot key means reading every salted sub-key and merging.
        if key not in HOT_KEYS or self.salts == 1:
            return [key]
        return [f"{key}#{s}" for s in range(self.salts)]


# 10,000 writes: every other one is a like on the celebrity's post.
workload = ["celebrity" if i % 2 == 0 else f"user-{i}" for i in range(10_000)]

for salts in (1, 8, 32):
    keys, load, counts = SaltedKeys(salts), [0] * SHARDS, {}
    for key in workload:
        k = keys.write_key(key)
        load[shard_of(k)] += 1
        counts[k] = counts.get(k, 0) + 1
    subkeys = keys.read_keys("celebrity")
    total = sum(counts[k] for k in subkeys)
    print(f"{salts:>2} salt(s): writes per shard {load}  reading 'celebrity' = {len(subkeys):>2} reads, total {total}")
 1 salt(s): writes per shard [1222, 6227, 1295, 1256]  reading 'celebrity' =  1 reads, total 5000
 8 salt(s): writes per shard [3722, 1852, 3170, 1256]  reading 'celebrity' =  8 reads, total 5000
32 salt(s): writes per shard [2630, 2476, 2858, 2036]  reading 'celebrity' = 32 reads, total 5000
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;

const int Shards = 4;

static int ShardOf(string key) =>
    (int)(BinaryPrimitives.ReadUInt64BigEndian(MD5.HashData(Encoding.UTF8.GetBytes(key))) % Shards);

// 10,000 writes: every other one is a like on the celebrity's post.
var workload = Enumerable.Range(0, 10_000).Select(i => i % 2 == 0 ? "celebrity" : $"user-{i}").ToArray();

foreach (var salts in new[] { 1, 8, 32 })
{
    var keys = new SaltedKeys(salts, ["celebrity"]); // hot keys are found from metrics, not guessed
    var load = new int[Shards];
    var counts = new Dictionary<string, int>();
    foreach (var key in workload)
    {
        var k = keys.WriteKey(key);
        load[ShardOf(k)]++;
        counts[k] = counts.GetValueOrDefault(k) + 1;
    }
    var subkeys = keys.ReadKeys("celebrity");
    var total = subkeys.Sum(k => counts[k]);
    Console.WriteLine($"{salts,2} salt(s): writes per shard [{string.Join(", ", load)}]  " +
                      $"reading 'celebrity' = {subkeys.Length,2} reads, total {total}");
}

class SaltedKeys(int salts, HashSet<string> hotKeys)
{
    private readonly Dictionary<string, int> _next = [];

    // Hot keys get a suffix, so their writes land on several partitions. Cold keys stay as they are.
    public string WriteKey(string key)
    {
        if (!hotKeys.Contains(key) || salts == 1) return key;
        var n = _next[key] = _next.GetValueOrDefault(key, -1) + 1; // round-robin; a random pick works too
        return $"{key}#{n % salts}";
    }

    // The price: reading a hot key means reading every salted sub-key and merging.
    public string[] ReadKeys(string key) =>
        !hotKeys.Contains(key) || salts == 1 ? [key] : [.. Enumerable.Range(0, salts).Select(s => $"{key}#{s}")];
}
 1 salt(s): writes per shard [1222, 6227, 1295, 1256]  reading 'celebrity' =  1 reads, total 5000
 8 salt(s): writes per shard [3722, 1852, 3170, 1256]  reading 'celebrity' =  8 reads, total 5000
32 salt(s): writes per shard [2630, 2476, 2858, 2036]  reading 'celebrity' = 32 reads, total 5000

Without salting, shard 1 took 6,227 of 10,000 writes. With 8 salts the hottest shard dropped to 3,722, but it's still lumpy: 8 sub-keys hashed onto 4 shards don't land evenly, and none of them landed on shard 3. With 32 salts the load is fairly even (2,036 to 2,858), at the cost of 32 reads for every read of the celebrity's count.

Two lessons from that output. First, the number of salts should be several times the number of partitions, because the salted keys are hashed like any other key. Second, salting is a trade of write heat for read fan-out, so pair it with a cache or a precomputed total for the read side. A like counter usually doesn't need to be exact to the millisecond.

Other fixes for hot keys: cache reads in front of the database, buffer and batch writes (count likes in memory, flush every second), or give the hot tenant its own shard through the directory.

Cross-shard queries: scatter-gather

When a query doesn't include the shard key, the router can't pick a shard. It has to send the query to all of them and merge the results. That's scatter-gather. It works, with three costs: every shard does work for every such query, the slowest shard sets the latency, and some operations can't be merged naively.

The demo puts 40 orders on 4 SQLite shards by customer, then runs three queries: one targeted by customer, a global top 3, and a global average.

import hashlib
import heapq
import sqlite3
from concurrent.futures import ThreadPoolExecutor

SHARDS = 4


def shard_of(key: str) -> int:
    return int.from_bytes(hashlib.md5(key.encode(), usedforsecurity=False).digest()[:8], "big") % SHARDS


shards = [sqlite3.connect(":memory:", check_same_thread=False) for _ in range(SHARDS)]
for db in shards:
    db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, amount INTEGER)")
for order_id in range(1, 41):
    customer, amount = f"c{order_id % 10}", order_id * 37 % 100 + 1  # deterministic amounts, all distinct
    shards[shard_of(customer)].execute("INSERT INTO orders VALUES (?, ?, ?)", (order_id, customer, amount))


def scatter(sql):
    # Fan out to every shard at once; the slowest shard sets the latency of the whole query.
    with ThreadPoolExecutor(SHARDS) as pool:
        return list(pool.map(lambda db: db.execute(sql).fetchall(), shards))


# Single-shard query: the shard key is in the WHERE clause, so the router sends it to one place.
print(f"orders for c3 -> only shard {shard_of('c3')}:",
      [r[0] for r in shards[shard_of("c3")].execute("SELECT id FROM orders WHERE customer = 'c3'")])

# Top 3 overall: each shard sends its own top 3, the coordinator merges. Never pull every row.
per_shard = scatter("SELECT amount, id FROM orders ORDER BY amount DESC LIMIT 3")
print("top 3 overall:", heapq.nlargest(3, (row for rows in per_shard for row in rows)))

# Average: shards must return SUM and COUNT. Averaging the averages is wrong when shard sizes differ.
parts = [rows[0] for rows in scatter("SELECT SUM(amount), COUNT(*), AVG(amount) FROM orders")]
print("rows per shard:", [c for _, c, _ in parts])
print(f"avg of averages (wrong): {sum(a for *_, a in parts) / SHARDS:.2f}")
print(f"sum / count     (right): {sum(s for s, *_ in parts) / sum(c for _, c, _ in parts):.2f}")
orders for c3 -> only shard 0: [3, 13, 23, 33]
top 3 overall: [(100, 27), (97, 8), (96, 35)]
rows per shard: [24, 4, 4, 8]
avg of averages (wrong): 47.33
sum / count     (right): 52.00
#:package Microsoft.Data.Sqlite@10.0.13
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Data.Sqlite;

const int Shards = 4;
static int ShardOf(string key) =>
    (int)(BinaryPrimitives.ReadUInt64BigEndian(MD5.HashData(Encoding.UTF8.GetBytes(key))) % Shards);

var shards = Enumerable.Range(0, Shards).Select(_ =>
{
    var db = new SqliteConnection("Data Source=:memory:");
    db.Open();
    Exec(db, "CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT, amount INTEGER)");
    return db;
}).ToArray();
for (var orderId = 1; orderId <= 40; orderId++)
{
    var (customer, amount) = ($"c{orderId % 10}", orderId * 37 % 100 + 1); // deterministic amounts, all distinct
    Exec(shards[ShardOf(customer)], $"INSERT INTO orders VALUES ({orderId}, '{customer}', {amount})");
}

// Fan out to every shard at once; the slowest shard sets the latency of the whole query.
async Task<List<object[]>[]> Scatter(string sql) =>
    await Task.WhenAll(shards.Select(db => Task.Run(() => Query(db, sql))));

// Single-shard query: the shard key is in the WHERE clause, so the router sends it to one place.
var ids = Query(shards[ShardOf("c3")], "SELECT id FROM orders WHERE customer = 'c3'").Select(r => r[0]);
Console.WriteLine($"orders for c3 -> only shard {ShardOf("c3")}: [{string.Join(", ", ids)}]");

// Top 3 overall: each shard sends its own top 3, the coordinator merges. Never pull every row.
var perShard = await Scatter("SELECT amount, id FROM orders ORDER BY amount DESC LIMIT 3");
var top = perShard.SelectMany(rows => rows).OrderByDescending(r => (long)r[0]).Take(3).Select(r => $"({r[0]}, {r[1]})");
Console.WriteLine($"top 3 overall: [{string.Join(", ", top)}]");

// Average: shards must return SUM and COUNT. Averaging the averages is wrong when shard sizes differ.
var parts = (await Scatter("SELECT SUM(amount), COUNT(*), AVG(amount) FROM orders")).Select(rows => rows[0]).ToList();
Console.WriteLine($"rows per shard: [{string.Join(", ", parts.Select(p => p[1]))}]");
Console.WriteLine($"avg of averages (wrong): {parts.Average(p => (double)p[2]):F2}");
Console.WriteLine($"sum / count     (right): {(double)parts.Sum(p => (long)p[0]) / parts.Sum(p => (long)p[1]):F2}");

static void Exec(SqliteConnection db, string sql) { var c = db.CreateCommand(); c.CommandText = sql; c.ExecuteNonQuery(); }

static List<object[]> Query(SqliteConnection db, string sql)
{
    var c = db.CreateCommand();
    c.CommandText = sql;
    using var r = c.ExecuteReader();
    var rows = new List<object[]>();
    while (r.Read()) { var row = new object[r.FieldCount]; r.GetValues(row); rows.Add(row); }
    return rows;
}
orders for c3 -> only shard 0: [3, 13, 23, 33]
top 3 overall: [(100, 27), (97, 8), (96, 35)]
rows per shard: [24, 4, 4, 8]
avg of averages (wrong): 47.33
sum / count     (right): 52.00

What it shows:

  • The targeted query went to shard 0 only, because it included the shard key.
  • Top N pushes the limit down. Each shard returned its own top 3, and the coordinator took the top 3 of those 12 rows. The global top 3 must be in some shard's local top 3, so this is exact, and no shard sent more than 3 rows.
  • Averages don't merge. The shards held 24, 4, 4 and 8 rows. Averaging the four averages gave 47.33. The real average is 52.00. Shards have to return sums and counts, and the coordinator divides. The same trap applies to medians and percentiles, which need sketches like t-digest or a second pass. COUNT(DISTINCT) needs HyperLogLog or a full merge of the distinct sets.

In production, add a timeout per shard and decide up front whether a partial result is acceptable. A search page can show results from three of four shards with a warning. An invoice total can't.

Fan-out queries are fine for admin screens and reports. If a user-facing query has to scatter on every request, either the shard key is wrong for that query, or the query needs its own read model, built from events or change data capture and keyed for that access pattern. That's the same CQRS move the event sourcing deep dive uses for projections.

Cross-shard transactions: avoid them

A transaction that spans shards needs a distributed commit protocol. Two-phase commit exists and some systems offer it (Citus uses 2PC for multi-shard writes, Vitess has an atomic distributed transaction mode, and Spanner-style databases are built around it), but it costs latency, and a stuck coordinator can hold locks on several shards.

The better path is to design so you rarely need one:

  1. Pick the shard key so a transaction's rows live together. If an order and its lines share customer_id as the key, they're on the same shard, and a normal local transaction works. Citus calls this co-location.
  2. Duplicate small reference data (countries, plans, product catalog) to every shard, so joins against it stay local. Citus calls these reference tables.
  3. For a real cross-shard business process, use a saga. Each step is a local transaction on one shard, and failures run compensating steps. The saga deep dive covers orchestration and choreography, and Saga Orchestration from the earlier series covers the Azure side.

Global IDs: Snowflake and UUIDv7

Auto-increment IDs need one counter, which sharding just removed. You have three options.

  • Random UUIDs (v4) are unique without coordination, but they're random, so inserts land all over a B-tree index. That hurts write performance and cache use on large tables.
  • Snowflake-style IDs pack a timestamp, a worker ID and a per-millisecond sequence into 64 bits. Twitter published the original Snowflake design in 2010. The IDs are roughly time-ordered, fit in a bigint, and need no coordination beyond giving each worker a unique number.
  • UUIDv7 (RFC 9562) puts a millisecond timestamp in the high bits of a UUID and fills the rest with random bits. You get time ordering without assigning worker IDs. .NET 9 and later have Guid.CreateVersion7(), and Python adds uuid.uuid7() in 3.14.

The demo is a Snowflake generator with a fake clock: 41 bits of milliseconds since a custom epoch, 10 bits of worker ID (1,024 workers), 12 bits of sequence (4,096 IDs per millisecond per worker).

EPOCH_MS = 1_577_836_800_000          # 2020-01-01T00:00:00Z, our custom epoch
WORKER_BITS, SEQ_BITS = 10, 12        # 41 bits of time | 10 bits of worker | 12 bits of sequence
MAX_SEQ = (1 << SEQ_BITS) - 1


class FakeClock:
    def __init__(self, ms):
        self.ms = ms

    def now(self):
        return self.ms


class Snowflake:
    def __init__(self, worker_id, clock):
        assert 0 <= worker_id < (1 << WORKER_BITS)
        self.worker, self.clock, self.last_ms, self.seq = worker_id, clock, -1, 0

    def next_id(self):
        ms = self.clock.now()
        if ms < self.last_ms:
            raise RuntimeError(f"clock moved back {self.last_ms - ms} ms; refusing to risk duplicate IDs")
        if ms == self.last_ms:
            self.seq = (self.seq + 1) & MAX_SEQ
            if self.seq == 0:                 # 4,096 IDs used in this millisecond: wait for the next one
                while ms <= self.last_ms:
                    self.clock.ms += 1        # a real clock just moves on; the fake one needs a nudge
                    ms = self.clock.now()
        else:
            self.seq = 0
        self.last_ms = ms
        return ((ms - EPOCH_MS) << (WORKER_BITS + SEQ_BITS)) | (self.worker << SEQ_BITS) | self.seq


def decode(id_):
    return {"ms": (id_ >> (WORKER_BITS + SEQ_BITS)) + EPOCH_MS,
            "worker": (id_ >> SEQ_BITS) & ((1 << WORKER_BITS) - 1), "seq": id_ & MAX_SEQ}


clock = FakeClock(1_762_819_200_000)   # 2025-11-11T00:00:00Z
a, b = Snowflake(7, clock), Snowflake(8, clock)
ids = [a.next_id(), a.next_id(), b.next_id()]
clock.ms += 1
ids += [b.next_id(), a.next_id()]
for i in ids:
    print(i, decode(i))
ordered = sorted(ids)
print("sorting by value keeps time order:", all(decode(x)["ms"] <= decode(y)["ms"] for x, y in zip(ordered, ordered[1:])))

burst = [a.next_id() for _ in range(4097)]  # one more than fits in a millisecond
print("burst of 4097: last one", decode(burst[-1]))

clock.ms -= 5                               # NTP steps the clock back
try:
    a.next_id()
except RuntimeError as e:
    print("error:", e)
775872420249628672 {'ms': 1762819200000, 'worker': 7, 'seq': 0}
775872420249628673 {'ms': 1762819200000, 'worker': 7, 'seq': 1}
775872420249632768 {'ms': 1762819200000, 'worker': 8, 'seq': 0}
775872420253827072 {'ms': 1762819200001, 'worker': 8, 'seq': 0}
775872420253822976 {'ms': 1762819200001, 'worker': 7, 'seq': 0}
sorting by value keeps time order: True
burst of 4097: last one {'ms': 1762819200002, 'worker': 7, 'seq': 1}
error: clock moved back 5 ms; refusing to risk duplicate IDs
using static Layout;

var clock = new FakeClock { Ms = 1_762_819_200_000 }; // 2025-11-11T00:00:00Z
var a = new Snowflake(7, clock);
var b = new Snowflake(8, clock);
var ids = new List<long> { a.NextId(), a.NextId(), b.NextId() };
clock.Ms += 1;
ids.AddRange([b.NextId(), a.NextId()]);
foreach (var id in ids) Console.WriteLine($"{id} {Decode(id)}");
var ordered = ids.Order().ToList();
Console.WriteLine($"sorting by value keeps time order: {ordered.Zip(ordered.Skip(1)).All(p => Decode(p.First).Ms <= Decode(p.Second).Ms)}");

var burst = Enumerable.Range(0, 4097).Select(_ => a.NextId()).ToList(); // one more than fits in a millisecond
Console.WriteLine($"burst of 4097: last one {Decode(burst[^1])}");

clock.Ms -= 5; // NTP steps the clock back
try { a.NextId(); }
catch (InvalidOperationException e) { Console.WriteLine($"error: {e.Message}"); }

static Parts Decode(long id) =>
    new((id >> (WorkerBits + SeqBits)) + EpochMs, (id >> SeqBits) & ((1 << WorkerBits) - 1), id & MaxSeq);

static class Layout
{
    public const long EpochMs = 1_577_836_800_000;   // 2020-01-01T00:00:00Z, our custom epoch
    public const int WorkerBits = 10, SeqBits = 12;  // 41 bits of time | 10 bits of worker | 12 bits of sequence
    public const long MaxSeq = (1L << SeqBits) - 1;
}

record Parts(long Ms, long Worker, long Seq);

class FakeClock { public long Ms { get; set; } }

class Snowflake
{
    private readonly long _worker;
    private readonly FakeClock _clock;
    private long _lastMs = -1, _seq;

    public Snowflake(long workerId, FakeClock clock)
    {
        ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(workerId, 1L << WorkerBits);
        (_worker, _clock) = (workerId, clock);
    }

    public long NextId()
    {
        var ms = _clock.Ms;
        if (ms < _lastMs)
            throw new InvalidOperationException($"clock moved back {_lastMs - ms} ms; refusing to risk duplicate IDs");
        if (ms == _lastMs)
        {
            _seq = (_seq + 1) & MaxSeq;
            if (_seq == 0)                   // 4,096 IDs used in this millisecond: wait for the next one
                while (ms <= _lastMs) { _clock.Ms += 1; ms = _clock.Ms; } // a real clock just moves on
        }
        else _seq = 0;
        _lastMs = ms;
        return ((ms - EpochMs) << (WorkerBits + SeqBits)) | (_worker << SeqBits) | _seq;
    }
}
775872420249628672 Parts { Ms = 1762819200000, Worker = 7, Seq = 0 }
775872420249628673 Parts { Ms = 1762819200000, Worker = 7, Seq = 1 }
775872420249632768 Parts { Ms = 1762819200000, Worker = 8, Seq = 0 }
775872420253827072 Parts { Ms = 1762819200001, Worker = 8, Seq = 0 }
775872420253822976 Parts { Ms = 1762819200001, Worker = 7, Seq = 0 }
sorting by value keeps time order: True
burst of 4097: last one Parts { Ms = 1762819200002, Worker = 7, Seq = 1 }
error: clock moved back 5 ms; refusing to risk duplicate IDs

Things to notice:

  • Time order across workers. Sorting the IDs by value kept them in millisecond order, even though two workers made them. Inside one millisecond they're ordered by worker, not by real time, which is why these are called k-sorted rather than strictly ordered.
  • Sequence overflow waits. The burst of 4,097 IDs used up the rest of one millisecond and rolled over to the next. A real generator spins or sleeps until the clock moves. The fake one nudges itself.
  • A clock going backwards is refused. If NTP steps the clock back, a naive generator would reuse timestamps and could produce duplicates. Refusing (or waiting until the clock catches up) is the safe choice.
  • 41 bits of milliseconds is about 69 years from your custom epoch, and the epoch is part of the ID format forever.

One gotcha with UUIDv7 on SQL Server: uniqueidentifier sorts by its byte groups in an unusual order, starting with the last six bytes, so a v7 GUID stored there doesn't sort by its timestamp. If ordering matters on SQL Server, store a Snowflake-style bigint instead, or check how your library lays out the bytes. Postgres uuid columns sort v7 values in time order.

Real systems

SystemKey conceptRoutingRebalancing
Azure Cosmos DBPartition key per container. Logical partitions (one key value, up to 20 GB) live on physical partitions (up to 10,000 RU/s)Hash of the partition key, managed for youAutomatic physical splits. You can't change a container's partition key in place, so plan to copy to a new container. Hierarchical partition keys allow up to three levels.
Azure SQL elastic database toolsShard map manager with list or range shard mapsData-dependent routing in the client librarySplit-merge tool moves shardlets between databases. Elastic query and the multi-shard query library handle fan-out.
Citus (Postgres extension)create_distributed_table with a distribution column. Co-located and reference tables.Hash into a fixed set of shards, placed on worker nodesShard rebalancer moves shards online
Vitess (MySQL)Keyspaces, a VSchema, and vindexes that map a row to a keyspace IDVTGate proxy routes by keyspace ID rangeReshard workflows with VReplication, then switch reads and writes
MongoDBShard key per collection, data in chunksmongos routes by ranged or hashed shard key. Zones pin ranges to shards.Balancer migrates chunks. reshardCollection changes the key online (5.0 and later).
Amazon DynamoDBPartition key, optionally with a sort keyHash of the partition keyAutomatic partition splits plus adaptive capacity. The docs recommend write sharding for hot keys.

The common thread: every one of them uses a fixed or managed set of partitions that's larger than the number of machines, and every one of them makes you choose the key. None of them can choose it for you.

When not to shard

Sharding is close to a one-way door. Before you walk through it, try the cheaper doors, roughly in this order:

  1. Fix the queries. Missing indexes, N+1 queries and unbounded scans cause more "we need to shard" conversations than data size does.
  2. Scale up. A single modern database server with lots of cores, a few hundred GB of RAM and fast NVMe storage handles a surprising amount. It's boring and it's often the cheapest option, counting engineering time.
  3. Add read replicas if reads dominate. Most apps read far more than they write. Replicas add read capacity with no change to the data model, at the cost of replication lag.
  4. Cache hot reads in Redis or in memory.
  5. Archive or partition old data. If 90% of the rows are from past years and rarely read, move them to cheaper storage or a separate partition, and the hot set shrinks.
  6. Split by feature (vertical partitioning). Billing, analytics and search often don't need to live in the main database at all.
  7. Use a database that shards for you. Cosmos DB, DynamoDB, Citus, Vitess and distributed SQL databases hide the routing and rebalancing, though you still own the shard key.

Shard when writes or data size really do outgrow one primary, after those steps. When you do, start with many logical shards, pick a key that matches your main access pattern, and build the routing as a layer you can change.

Check yourself: questions and answers

1. What's the difference between partitioning and sharding?

Partitioning splits a table into pieces, which can all live on one server. Sharding is horizontal partitioning across separate servers, so each piece has its own resources and failure domain. Sharding adds capacity. Partitioning on one server mostly helps maintenance and query pruning.

2. What makes a good shard key?

High cardinality, even spread of both data and traffic, present in your most frequent queries, and stable for the life of the row. For multi-tenant SaaS, tenant ID is often the right starting point.

3. You shard by created_at range. What happens?

All new writes go to the newest range, so one shard takes all the write load while the others hold cold data. Range sharding is good for range queries and terrible for sequential keys. Hash the key, or use a composite key, if writes are the bottleneck.

4. Why use consistent hashing instead of hash mod N, and why virtual nodes?

With mod N, changing N moves most keys (80% going from 4 to 5 nodes in the demo). With a hash ring, adding a node moves only about 1/N of the keys. Virtual nodes give each server many points on the ring, which evens out the load. With one point per server, the load and the share a new node takes are both down to luck.

5. How do you move data to a new shard without downtime?

Double-write (or stream changes with CDC) to old and new, backfill existing rows without overwriting newer ones, verify, switch reads, then stop writing to the old location, and clean up later. Keep the steps separate so you can roll back reads.

6. One key gets most of the traffic. What are your options?

Cache its reads, batch its writes, give it a dedicated shard through a directory, or salt it into several sub-keys so writes spread out. Salting makes reads fan out to every sub-key, so use enough salts relative to partitions and only for keys you know are hot.

7. Why can't you average the averages from each shard?

Because shards hold different numbers of rows. Each shard must return a sum and a count, and the coordinator divides. In the demo the average of averages was 47.33 and the true average was 52.00.

8. How do you generate unique, sortable IDs without a central counter?

Use Snowflake-style 64-bit IDs (timestamp, worker ID, sequence) or UUIDv7. Both are roughly time-ordered, so B-tree inserts stay at the end of the index. Snowflake needs unique worker IDs and a guard against clocks going backwards. UUIDv7 needs neither, but takes 128 bits.

Further reading

  • Microsoft Learn, Sharding pattern and Data partitioning guidance
  • Microsoft Learn, Partitioning and horizontal scaling in Azure Cosmos DB and Hierarchical partition keys
  • Microsoft Learn, Scaling out with Azure SQL Database (elastic database tools)
  • Karger et al., Consistent Hashing and Random Trees (STOC 1997), and Lamping and Veach, A Fast, Minimal Memory, Consistent Hash Algorithm (jump hash)
  • Citus documentation and Vitess documentation
  • MongoDB, Sharding
  • AWS, Best practices for designing and using partition keys effectively (DynamoDB)
  • RFC 9562: Universally Unique IDentifiers (UUIDv7) and Twitter's original Snowflake
  • Martin Kleppmann, Designing Data-Intensive Applications, chapter 6 on partitioning
  • From this blog: Event Sourcing in Depth, The Saga Pattern in Depth, The Transactional Outbox in Depth
← Previous

Building OwlPlot: A Weather-Aware Companion for Photographers

Next →

Event Sourcing in Depth: Expected Versions, Projections, Snapshots and Upcasting, in C# and Python

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.