Skip to content

Sharding: Splitting Data Across Nodes by Key

How to shard a database by key: choosing the shard key, handling hot tenants, and resharding live with a bucket map and a short write freeze.

20 min readSystem pattern

Spread data and write load across N independent database nodes by routing every row through a shard key. Keep the routing indirect, using key to bucket to node, so you can move data between nodes without rehashing everything or changing application code.

Sharding splits one logical dataset across several database nodes. Each row lives on exactly one shard, and a shard key decides which one. You use it when a single primary can no longer absorb your writes or hold your data, and read replicas no longer help. This guide follows one invented service from a single overloaded Postgres to 32 shards. It covers the three decisions interviewers probe: which key to shard on, what to do when one key is far hotter than the rest, and how to add shards without taking the product down. The core mechanism is a small router that maps keys to buckets and buckets to physical shards. That one level of indirection is what makes resharding manageable.

The problem

A situation where the obvious design starts to hurt.

Fieldbook is a SaaS for field-service companies such as plumbers, electricians and HVAC installers. Technicians open jobs, log parts and time, attach photo metadata and collect signatures. About 11,000 companies use it. Everything lived in one Postgres primary with two read replicas.

By last winter the primary held 6 TB. Weekday peaks reached around 9,000 writes per second between 7 and 9 am, when technicians start their first jobs. Read replicas had already taken the dashboards, so the remaining load was writes, and every write has to land on the primary. Autovacuum on the job_events table ran for more than a day. Replication lag on the replicas passed 40 seconds at peak. A rehearsed failover took 35 minutes because a new replica needed hours to catch up. The largest instance size the team could buy was already in use.

The first sharding attempt hashed job_id. Writes spread evenly, but the most common query, "all of today's jobs for company X", now fanned out to every shard, and p99 for the dispatch board went from 80 ms to 900 ms. A second idea, sharding by creation month, would have sent every write of the day to the newest shard.

After they settled on sharding by company, two more problems surfaced. Northgate Heating, a national chain with 2,400 technicians, produced roughly 22% of all writes and saturated whichever shard it landed on. And when the team grew from 16 to 32 shards, a plain hash % N scheme would have relocated about half of all rows at once.

The solution

What the pattern proposes.

Shard on the key that nearly every query already filters by. For Fieldbook that is company_id. A company's jobs, events, invoices and technicians all live on the same shard, so the dispatch board, job detail and invoice screens become single-shard queries. Joins and transactions inside one company keep working as before.

Do not map the key straight to a node. Hash it into a fixed number of logical buckets. Fieldbook uses 1,024, computed as fnv1a(company_id) % 1024. A versioned shard map, stored in etcd, assigns each bucket to a physical shard. The bucket count never changes. Resharding means reassigning some buckets to new nodes, so you move only the data in those buckets.

To move a bucket, a rebalancer first backfills the bucket's rows onto the target shard. It then streams ongoing changes from the source through logical replication until lag is under a second. Next it freezes the bucket: the map version is bumped and routers refuse writes to it, returning a retryable error. It waits for the final changes to drain, then flips the bucket to the target and bumps the version again. The freeze typically lasts a few seconds, and clients retry with backoff through it.

For hot tenants, the map also carries a pinned table that overrides the hash. Northgate Heating gets a dedicated shard sized for its load. If a single tenant outgrows even a dedicated machine, the key must become finer for that tenant, for example (company_id, region_id). Do that only for tenants that need it.

Each shard also records which buckets it owns and rejects writes for any it does not. That way a router holding a stale map gets an error instead of writing to the wrong node.

An everyday analogy

The same idea, outside software.

Think of a large public library that outgrows one building and opens several branches. Instead of shelving books by title across branches, it gives every patron a card number, and the last three digits pick one of 1,000 lockers. A printed directory at each entrance says which branch holds each range of lockers. When a new branch opens, staff move a few hundred lockers, briefly closing each one while it is carried across, and reprint the directory. The patrons and their card numbers stay the same. One patron, a university with thousands of borrowers, gets a branch of its own.

Structure

The pieces and how they relate.

Fieldbook routes every request by company_id through a versioned bucket map; a rebalancer moves buckets to new shards while serving traffic.Technician apps calls Jobs API (HTTPS). Jobs API calls Shard router (route(company_id)). Shard router calls Shard map (watch version). Shard router sends to pg-shard-01. Shard router sends to pg-shard-02. Shard router sends to pg-shard-16. Shard router sends to pg-dedicated-1 (pinned tenant). Rebalancer calls Shard map (freeze, flip). Rebalancer calls pg-shard-17 (backfill bucket 517). pg-shard-02 sends asynchronously to Change stream (WAL for bucket 517). Change stream sends asynchronously to pg-shard-17 (apply changes).Technician appsmobile and webJobs APIstateless, 40 podsShard routerfnv1a(company_id) %1024Shard mapetcd, versionedbuckets + pinspg-shard-0164 bucketspg-shard-0264 buckets, bucket517 movingpg-shard-1664 bucketspg-dedicated-1pinned: NorthgateHeatingRebalancerbackfill, freeze,flipChange streamlogical replicationper bucketpg-shard-17new node, receivingbucketsOwnership fenceshards reject writesfor buckets they d…HTTPSroute(company_id)watch versionpinned tenantfreeze, flipbackfill bucket 517WAL for bucket 517apply changes
Fieldbook routes every request by company_id through a versioned bucket map; a rebalancer moves buckets to new shards while serving traffic.

Participants

Shard key (company_id)
The column that decides where a row lives. It appears in the WHERE clause of almost every query, so most requests touch one shard. Every sharded table carries it, including child tables such as job_events.
Bucket space (1,024 logical buckets)
A fixed intermediate layer. Keys hash into buckets once and stay there for good. Buckets, not keys, are the unit of placement and of movement, which keeps resharding to a list of bucket moves.
Shard map
Versioned record of bucket-to-shard assignments, pinned tenants and frozen buckets, stored in etcd. Routers watch it and swap to each new version atomically.
Shard router
A library inside the Jobs API. It computes the bucket, applies pins, refuses writes to frozen buckets and returns the target shard plus the map version it used.
Physical shards
Independent Postgres primaries, each with its own replicas. Each stores the set of buckets it owns and rejects writes for any other bucket, which fences out routers holding a stale map.
Rebalancer
Moves one bucket at a time. It backfills, tails the change stream, freezes the bucket, waits for lag to reach zero, flips ownership, then deletes the old copy after a grace period.

Pseudocode

The solution to the scenario, language-neutral.

BUCKETS = 1024

function bucket_for(key):
    return fnv1a(utf8(key)) mod BUCKETS

function route(map, tenant_id, op):
    b = bucket_for(tenant_id)
    if tenant_id in map.pinned:
        return (map.pinned[tenant_id], b, map.version)
    if op == write and b in map.frozen:
        raise ShardMoving(b)          // caller retries with backoff
    return (map.buckets[b], b, map.version)

// on the shard itself, inside the write transaction
function guard_write(shard, bucket):
    if bucket not in shard.owned_buckets:
        abort "wrong shard, refresh map"

function move_bucket(b, source, target):
    backfill rows where bucket = b from source to target (throttled)
    tail source change stream for bucket b into target until lag < 1s
    map = map with frozen += b, version += 1; publish; wait until all routers ack version
    wait until change stream lag for b == 0
    target.owned_buckets += b; source.owned_buckets -= b
    map = map with buckets[b] = target, frozen -= b, version += 1; publish
    after 24h: delete rows of bucket b from source

The code

The same solution in TypeScript, Python and PHP.

const BUCKETS = 1024;

export class ShardMovingError extends Error {
  constructor(public readonly bucket: number) {
    super(`bucket ${bucket} is being moved; retry shortly`);
    this.name = "ShardMovingError";
  }
}

// 32-bit FNV-1a over UTF-8 bytes: stable across languages and processes.
export function fnv1a(key: string): number {
  let h = 0x811c9dc5;
  for (const b of new TextEncoder().encode(key)) {
    h ^= b;
    h = Math.imul(h, 0x01000193) >>> 0;
  }
  return h >>> 0;
}

export interface ShardMap {
  version: number;
  buckets: string[]; // index = bucket, value = physical shard id
  pinned: Record<string, string>; // tenant id -> dedicated shard
  frozen: number[]; // buckets in cutover: writes refused
}

export interface Route {
  shard: string;
  bucket: number;
  version: number;
}

export function evenMap(shards: string[]): ShardMap {
  const buckets = Array.from({ length: BUCKETS }, (_, i) => shards[i % shards.length]);
  return { version: 1, buckets, pinned: {}, frozen: [] };
}

// Rebalancer steps. Each returns a new map version for routers to pick up.
export function freeze(map: ShardMap, bucket: number): ShardMap {
  const frozen = [...new Set([...map.frozen, bucket])];
  return { ...map, version: map.version + 1, frozen };
}

export function flip(map: ShardMap, bucket: number, target: string): ShardMap {
  const buckets = [...map.buckets];
  buckets[bucket] = target;
  const frozen = map.frozen.filter((b) => b !== bucket);
  return { ...map, version: map.version + 1, buckets, frozen };
}

export class ShardRouter {
  private readonly frozen: Set<number>;

  constructor(private readonly map: ShardMap) {
    if (map.buckets.length !== BUCKETS) {
      throw new Error(`shard map must have ${BUCKETS} buckets`);
    }
    this.frozen = new Set(map.frozen);
  }

  bucketFor(tenantId: string): number {
    return fnv1a(tenantId) % BUCKETS;
  }

  route(tenantId: string, op: "read" | "write"): Route {
    const bucket = this.bucketFor(tenantId);
    const pinned = this.map.pinned[tenantId];
    if (pinned !== undefined) {
      return { shard: pinned, bucket, version: this.map.version };
    }
    if (op === "write" && this.frozen.has(bucket)) {
      throw new ShardMovingError(bucket);
    }
    return { shard: this.map.buckets[bucket], bucket, version: this.map.version };
  }
}

// Demo: route, freeze a bucket, then move it to a new shard.
let map = evenMap(["pg-01", "pg-02", "pg-03", "pg-04"]);
map = { ...map, version: map.version + 1, pinned: { "northgate-heating": "pg-dedicated-1" } };

const tenant = "acme-plumbing";
const bucket = new ShardRouter(map).bucketFor(tenant);
console.log(new ShardRouter(map).route(tenant, "write"));
console.log(new ShardRouter(map).route("northgate-heating", "write"));

map = freeze(map, bucket);
try {
  new ShardRouter(map).route(tenant, "write");
} catch (e) {
  if (e instanceof ShardMovingError) console.log(e.message);
  else throw e;
}
console.log(new ShardRouter(map).route(tenant, "read"));

map = flip(map, bucket, "pg-05");
console.log(new ShardRouter(map).route(tenant, "write"));

When to use it

Situations where it pays off.

  • Write throughput or data size exceeds what the largest affordable single primary can handle, and you have already moved reads to replicas.

    Replicas multiply read capacity but every write still lands on one node. Sharding is the main way to scale writes horizontally.

  • Your data has a natural owner, such as a tenant, user or account, that almost every query filters by.

    Sharding on that owner keeps the common path on a single shard, with local joins and transactions. Without such a key, you trade one bottleneck for constant fan-out.

  • Operational limits of one huge database hurt: vacuum or index builds take days, failover takes tens of minutes, major upgrades are too risky.

    Ten 600 GB shards are each faster to vacuum, back up, restore and upgrade than one 6 TB node. A failure takes out one slice of tenants, not all of them.

  • Load per key is skewed but predictable, such as a handful of very large enterprise customers.

    A directory-based map lets you pin those keys to dedicated hardware without changing the scheme for everyone else.

How to implement it

Steps to introduce it in existing code.

  1. List the top 20 queries by frequency and latency budget and check which column each one filters by. Pick the shard key that turns the most of them into single-shard queries. Reject keys with low cardinality or a time component that concentrates new writes.

  2. Add the shard key to every table that belongs to the entity, including child tables, and to every primary key and unique index. Unique constraints are only enforced within a shard.

  3. Replace sequential IDs with globally unique ones, such as ULIDs or IDs that embed the bucket. That way IDs never collide across shards and you can still find the shard from the ID.

  4. Hash keys into a fixed bucket count much larger than your shard count. Fieldbook uses 1,024 buckets for 16 to 32 shards. Store bucket assignments in a versioned map that routers watch.

  5. Measure per-key load from the start and keep a pinned table in the map. Move a tenant to a dedicated shard once it passes about 30% of a normal shard's write budget.

  6. Build the rebalancer before you need it: backfill, change-stream catch-up, short write freeze, ownership flip, delayed delete. Rehearse moving one bucket in staging until the freeze stays under 5 seconds.

  7. Send cross-shard work such as global reports, search and billing totals to a separate store fed by change data capture, instead of fanning queries out at request time.

Pros and cons

What you gain and what you pay.

Pros

  • Write capacity and storage grow roughly linearly with node count, as long as the key spreads load evenly.
  • Each shard is small enough for fast vacuum, backup, restore and failover. Fieldbook's failover went from 35 minutes to under 4.
  • Failures are contained: losing one shard affects about one sixteenth of tenants, not everyone.
  • The bucket indirection lets you rebalance gradually, a few buckets at a time, without changing application queries.
  • Hot tenants can be isolated on dedicated hardware, which also fits enterprise contracts that ask for it.

Cons

  • Queries that do not include the shard key must hit every shard, and their latency becomes that of the slowest shard.
  • Transactions, foreign keys and unique constraints only hold within a shard. Cross-shard invariants need sagas or a separate coordinator.
  • The shard key is very expensive to change later, since every row has to move and every query has to change.
  • Operating 16 or more primaries means 16 times the monitoring, upgrades, connection pools and schema migrations, which need to roll out shard by shard.
  • Resharding tooling such as backfill, change streams, freezes and fencing is real software that needs testing and on-call ownership.

Trade-offs

Decisions you'll have to make, each with its price.

  • Bucket directory (key to 1,024 buckets to shards) instead of hash(key) % N

    You gainAdding shards moves only the buckets you choose, a few percent at a time, and you can pin or move any bucket on purpose.

    You payYou must run a highly available map store and propagate versions to every router. A stale map without shard-side fencing can misroute writes.

  • Shard by company_id rather than by job_id

    You gainOver 95% of Fieldbook queries become single-shard, with local joins and transactions, so dispatch board p99 stays near 80 ms.

    You payLoad follows tenant size, so one large company can overload a shard. Cross-company analytics needs a separate warehouse.

  • Short write freeze at cutover instead of dual writes

    You gainSimple to reason about: there is exactly one owner at any instant, and no conflict resolution between two copies.

    You payWrites for one bucket fail for 2 to 5 seconds per move, so clients must retry. Moving 512 buckets means 512 brief freezes spread over days.

  • Dedicated shard for tenants above 30% of a shard's write budget

    You gainIsolates Northgate Heating's 22% of writes so the 700 other companies on its old shard return to normal latency.

    You payA dedicated r6i.4xlarge-class node mostly serves one customer, and the pin is manual operational state someone has to review.

  • Start with 16 physical shards rather than 64

    You gainFewer primaries to monitor, patch and migrate while the team learns to operate the system.

    You payYou will reshard sooner, so the rebalancer has to be production quality from day one rather than a someday project.

How it fails

What goes wrong in production and how to prevent it.

  • One tenant becomes a hot spot: a shard's CPU sits at 95% while others idle at 30%.

    What to doTrack writes per second per company_id on every shard and alert when one tenant passes 30% of a shard's budget. Pin it to a dedicated shard with the same backfill and freeze flow. If it outgrows a full machine, add a sub-key such as region_id for that tenant only.

  • A router uses a stale map after a flip and writes bucket 517 to the old shard.

    What to doEach shard stores its owned buckets and checks the bucket inside the write transaction, aborting with a wrong-shard error. The router then refetches the map and retries. The rebalancer also waits for all routers to ack the freeze version before draining.

  • Backfill of a large bucket saturates the source shard's disk and raises production latency.

    What to doThrottle backfill to a fixed rate, for example 20 MB/s, run it from a replica where possible, and pause it automatically when source p99 write latency passes a threshold such as 50 ms.

  • A rebalancer crash leaves a bucket frozen, and writes for those tenants fail indefinitely.

    What to doStore each move as a state machine in the map store with a lease. Freezes have a maximum duration, for example 30 seconds, after which the move aborts and the bucket unfreezes on its original shard. A restarted rebalancer resumes or rolls back from the recorded state.

  • Duplicate IDs or broken uniqueness, because sequence-based primary keys and unique indexes are only per-shard.

    What to doUse globally unique IDs such as ULIDs. Include company_id in every unique constraint. For truly global uniqueness, such as a public invoice number, use a small dedicated allocation service.

  • An admin query without company_id fans out to all shards and times out at the slowest one.

    What to doBan unkeyed queries on the request path through a check in the data access layer. Serve global views from a warehouse fed by CDC. Where fan-out is unavoidable, use per-shard timeouts and return partial results that are clearly marked as partial.

In a system design interview

When to bring it up and how to explain it.

Bring it up once you have shown that writes or data size exceed a single primary, after you have mentioned replicas and caching. Typical prompts are multi-tenant SaaS, chat messages per conversation, orders per merchant, or any design where the interviewer pushes the numbers past one database.

What you could say

Replicas already handle our reads, so the bottleneck is writes on one primary, which means I'd shard. The most important decision is the shard key. I'd pick the column almost every query filters by, here company_id, so the dispatch board and job pages hit exactly one shard with normal joins and transactions. I would not use job_id, because that spreads writes well but turns every per-company read into a fan-out. I also wouldn't use a time-based key, because all of today's writes would land on one node.

I wouldn't map keys straight to nodes. I'd hash company_id into a fixed 1,024 buckets and keep a versioned bucket-to-shard map in etcd that routers watch. Resharding from 16 to 32 nodes is then just moving buckets. For each one we backfill, tail the change stream, freeze writes for a few seconds, flip ownership and bump the version. Each shard also checks bucket ownership on write, so a stale router gets an error instead of corrupting data.

The skew risk is big tenants. I'd measure per-tenant write rates and pin anything above roughly 30% of a shard to dedicated hardware. Cross-tenant reporting goes to a warehouse fed by CDC, not to live fan-out queries.

Likely follow-ups

What if a single tenant is too big even for a dedicated shard?

Then the key is too coarse for that tenant. I'd switch it to a compound key like (company_id, region_id) so its data spreads across several shards, and accept that its company-wide views now fan out across those few shards or come from a read model. Everyone else keeps the simple key.

Why not consistent hashing instead of a bucket map?

Consistent hashing also limits movement when nodes change, and it avoids a central map. But placement follows the ring, so pinning one tenant or moving a specific hot range is awkward. A directory gives explicit control at the cost of running the map store. With thousands of tenants and a few huge ones, I'd choose control.

How do clients behave during the write freeze?

The router returns a retryable error with the bucket number. The API retries internally with jittered backoff for up to about 5 seconds before returning 503 with Retry-After. Reads continue from the source shard throughout, since it remains authoritative until the flip.

How do you keep a transaction that touches two companies consistent?

Avoid it where possible by keeping each operation inside one tenant. When it is required, for example moving a job between companies, I'd run a saga with idempotent steps on each shard and a compensating step, rather than distributed two-phase commit across shards.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

How many buckets should I create?

Use enough that the smallest unit you move is a small fraction of a shard, and that you will never need to change the count. With 1,024 buckets, a 16-shard cluster has 64 buckets per shard, so one move shifts about 1.5% of a shard. Even at 128 shards you still have 8 per node. More buckets only cost a larger map, which at a few thousand entries is trivial.

Is sharding the same as table partitioning?

No. Partitioning splits a table into pieces inside one database server, which helps vacuum and pruning but shares that server's CPU, disk and write limit. Sharding puts the pieces on separate servers, each with its own primary. You can use both: each Fieldbook shard partitions job_events by month.

What should I try before sharding?

Move reads to replicas, add caching, archive cold data, fix the worst queries, and scale the primary up. Sharding is worth its cost when writes or data size outgrow the largest node you can run, or when operations on one huge node such as vacuum, restore and failover become unacceptable.

How do I run schema migrations on 32 shards?

Make every migration backward compatible, apply it shard by shard with a tool that records per-shard progress, and only ship code that depends on it once every shard reports done. Expect a period where some shards have the new column and others do not.

Why not shard by a hash of the row's own ID?

It spreads writes perfectly but separates rows that are read together. Fieldbook tried hashing job_id, and a company's daily job list became a 16-shard fan-out. Pick the key your reads group by, then deal with skew separately.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide5 of 8 · DataConsistent Hashing: Adding Cache Nodes Without a Miss StormRead the next one