Database Sharding

Difficulty: Advanced

Question

What is database sharding? How do you choose a shard key, and what problems does sharding introduce?

Answer

Sharding is splitting one large logical dataset across multiple independent database servers, called shards, where each shard holds a subset of the rows and handles reads and writes for that subset. A shard key (such as user_id or merchant_id) decides which shard owns each row. It lets you scale writes and storage beyond what a single machine can handle, at the cost of significant application and operational complexity.

Sharding vs partitioning vs replication

  • Partitioning usually means splitting a table into pieces inside one database server (Postgres declarative partitioning, MySQL partitions).
  • Sharding spreads those pieces across separate servers, each with its own CPU, memory and disk.
  • Replication copies the same data to more servers. It scales reads and availability, not write capacity. Real systems combine both: each shard is itself a primary with replicas.

Common sharding strategies

StrategyHow rows are placedProsCons
Hashhash(key) mod N or consistent hashingEven distributionRange queries hit every shard
RangeKey ranges (A-F, G-M, ...) or date rangesEfficient range scansHot spots on newest range
Directory / lookupA mapping table says which shard owns a keyFlexible moves, tenant pinningLookup service is a dependency
GeoBy region or countryData residency, low latencyUneven load across regions

Naive mod N forces moving most rows when N changes. Consistent hashing or a fixed large number of logical shards (say 1,024 virtual shards mapped onto 8 physical servers) keeps rebalancing incremental.

Choosing a good shard key

A good key has high cardinality, spreads load evenly, and appears in most queries so they can be routed to one shard. For a food delivery app, customer_id keeps a customer's orders together, but a restaurant dashboard listing all its orders would then fan out to every shard. Pick the key around the most frequent, latency-sensitive queries and serve the rest from a secondary store or an analytics copy.

Bad keys: created_at (all writes hit the newest shard), country (India dominates), booleans or low-cardinality enums.

Problems sharding introduces

  • Cross-shard queries and joins require scatter-gather in the application or a query router.
  • Cross-shard transactions need two-phase commit or sagas; most teams design to avoid them.
  • Hot partitions: one celebrity user or one huge merchant overloads its shard.
  • Resharding while live is hard: dual writes, backfill, verification, cutover.
  • Global uniqueness: auto-increment IDs collide across shards, so use Snowflake-style IDs or UUIDv7.
  • Operational load: backups, schema migrations and monitoring multiplied by N.

Do you actually need it?

Shard last. First try indexing, query tuning, caching, read replicas, vertical scaling and archiving old data. When you do need it, tools like Vitess (MySQL, used by YouTube and Slack), Citus (Postgres), MongoDB's built-in sharding, or distributed SQL databases such as CockroachDB and YugabyteDB handle much of the routing and rebalancing for you.

How a sharded query is routed. The router uses the shard key to send each query to exactly one shard when possible.
  1. App query with user_id = 8421: Every hot query includes the shard key.
  2. Router hashes the shard key: hash(8421) maps to logical shard 37.
  3. Shard map lookup: Logical shard 37 lives on server db-3.
  4. Shard db-3 primary: Executes the query on its subset of rows.
  5. Result returned to app: Other shards are never touched.

Code examples

Routing with logical shards in application code

import hashlib

LOGICAL_SHARDS = 1024
# Mapping of logical shard ranges to physical servers (kept in config/etcd)
SHARD_MAP = {range(0, 256): "db-1", range(256, 512): "db-2",
             range(512, 768): "db-3", range(768, 1024): "db-4"}

def logical_shard(user_id: int) -> int:
    digest = hashlib.md5(str(user_id).encode()).hexdigest()
    return int(digest, 16) % LOGICAL_SHARDS

def server_for(user_id: int) -> str:
    ls = logical_shard(user_id)
    for r, host in SHARD_MAP.items():
        if ls in r:
            return host
    raise KeyError(ls)

print(server_for(8421))
# Resharding moves whole logical shards between servers;
# the hash function and LOGICAL_SHARDS never change.

A fixed number of logical shards decouples the hash from the number of servers, so scaling out means moving some logical shards rather than rehashing every row.

Distributing a table with Citus (PostgreSQL)

CREATE TABLE orders (
  order_id    BIGINT,
  merchant_id BIGINT NOT NULL,
  amount_paise BIGINT,
  PRIMARY KEY (merchant_id, order_id)  -- PK must include distribution column
);
SELECT create_distributed_table('orders', 'merchant_id');

Citus hash-distributes rows by merchant_id across worker nodes and routes single-merchant queries to one node.

Key points

  • Sharding splits data across servers; replication copies it. Most systems use both.
  • A good shard key has high cardinality, even load and appears in most queries.
  • Use logical shards or consistent hashing so resharding moves only part of the data.
  • Cross-shard joins, transactions and unique IDs become application problems.
  • Exhaust indexing, caching, replicas and vertical scaling before sharding.

Common follow-up questions

  • How does consistent hashing reduce data movement when adding a shard?
  • How would you handle a hot shard caused by one very large merchant?
  • How do you generate globally unique IDs across shards?
  • How would you reshard a live database without downtime?

Interview tips

  • Start with "do we need to shard at all?" and list alternatives; it shows maturity.
  • Justify the shard key from the dominant query pattern of the system in question.
  • Proactively list the pain points (cross-shard queries, resharding, hot keys).

Concepts covered

Horizontal Scaling, Shard Key, Hash Sharding, Range Sharding, Hot Partition, Resharding

More Database Design questions