Horizontal Sharding: Distribution Strategies for Scale

Learn database sharding strategies including shard key selection, consistent hashing, cross-shard queries, and operational procedures for distributed data.

published: reading time: 17 min read author: Geek Workbench updated: June 17, 2026
Quick Summary

Horizontal sharding spreads rows or key ranges across nodes, but routing and rebalancing depend on the database or application architecture. This guide compares application-managed routing with Citus, CockroachDB, and Spanner, then walks through shard-key selection and a reversible migration plan. Use the worksheet before committing to a key.

Introduction

Horizontal sharding spreads rows or key ranges across multiple nodes. The owner of placement varies: an application router may choose a shard, a database extension may route through a coordinator, or a distributed database may manage ranges itself.

The diagram shows only the application-managed case. Its router hashes user_id and chooses a shard. Database-native systems use their own placement and routing rules.

This approach assumes that common queries can be routed using the chosen key. Queries without that key, including global reports and cross-tenant joins, may still touch several shards.

Sharding architectures

Start by asking who owns placement and routing. This table compares responsibilities, not latency or consistency rankings.

Approach Who routes a query? Who moves data? What the application still owns
Application-managed shards Application or middleware router Application-specific migration and routing process Shard map, key design, migration safety, cross-shard behavior
Citus 13 on PostgreSQL Citus coordinator routes to one or more workers Citus manages shards and exposes rebalancing operations Distribution column, co-location model, query shape
CockroachDB distributed SQL SQL gateway nodes route operations to key ranges CockroachDB splits and replicates ranges Transaction retry handling, locality choices, schema and query design
Google Cloud Spanner Spanner routes reads and writes to relevant splits and replicas Spanner splits and rebalances as size and traffic change Key design, transaction scope, regional configuration, read consistency choice

These systems make different trade-offs. CockroachDB’s current stable docs describe SERIALIZABLE as its default transaction isolation. A transaction can return a retryable error when the database cannot safely retry it, so applications need a retry strategy. Spanner’s default serializable transactions provide external consistency; its read APIs also offer timestamp-bound stale reads. A request’s latency depends on transaction scope, replica or leader placement, regions, and read mode. TrueTime supports Spanner’s commit ordering; it does not make global writes inherently faster. See CockroachDB architecture and transaction behavior, plus Spanner transaction guarantees and TrueTime consistency.

Citus 13 is a PostgreSQL extension with a coordinator and worker nodes. Applications send SQL to the coordinator; it routes a query to one worker when possible or fans it out when data spans workers. A distribution column determines row placement. Co-locating tables on a common tenant or entity key can keep joins local, while queries without that key may need work across workers. See the Citus concepts and distribution-column guidance.

Database-managed ranges reduce how much shard-routing code an application owns, but applications still need to account for transaction retries, data locality, and query costs. With application-managed sharding, the application also owns the routing map and the migration between placements.

MongoDB Sharding

MongoDB provides built-in sharding with automatic chunk distribution:

// Enable sharding on the database
sh.enableSharding("myapp");

// Shard a collection by hashed shard key (for even distribution)
sh.shardCollection("myapp.orders", { order_id: "hashed" });

// Shard by range (when range queries matter)
sh.shardCollection("myapp.events", { timestamp: 1 });

// Check cluster status
sh.status();

// Manually split a chunk to enable migration
db.adminCommand({
  split: "myapp.orders",
  middle: { order_id: NumberLong(500000) },
});

// Move a chunk to a specific shard
db.adminCommand({
  moveChunk: "myapp.orders",
  find: { order_id: NumberLong(500000) },
  to: "shard2",
});

Shard key selection for MongoDB:

Use Case Shard Key Why
User data user_id (hashed) Even distribution, user-specific queries efficient
Time-series events device_id + timestamp (compound) Query by device range, timestamps within device
E-commerce user_id + order_id (compound) User orders together, order lookups by user
Multi-tenant SaaS tenant_id (hashed) Tenant isolation, even load per tenant

PostgreSQL Citus

Citus extends PostgreSQL for distributed tables. It partitions tables across worker nodes while presenting a single PostgreSQL interface:

-- Install Citus extension on coordinator
CREATE EXTENSION IF NOT EXISTS citus;

-- Add worker nodes
SELECT citus_add_node('worker-1.internal', 5432);
SELECT citus_add_node('worker-2.internal', 5432);
SELECT citus_add_node('worker-3.internal', 5432);

-- Create distributed table (by hash)
CREATE TABLE users (
    user_id BIGSERIAL,
    email TEXT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT now(),
    PRIMARY KEY (user_id)
);
SELECT create_distributed_table('users', 'user_id', shard_count => 16);

-- Create reference table (replicated to all nodes)
CREATE TABLE countries (
    country_code TEXT PRIMARY KEY,
    name TEXT NOT NULL
);
SELECT create_reference_table('countries');

-- Check shard placement
SELECT * FROM citus_shards;
SELECT * FROM citus_shard_placements;

Citus supports co-located tables, where related rows can stay on the same worker, and queries that span workers. The create_distributed_table function sets a distribution column and shard count. In Citus 13, unique constraints on distributed tables must include the distribution column; foreign keys between co-located distributed tables must include it as well. See the Citus 13 DDL reference.

CockroachDB

CockroachDB presents a distributed SQL database rather than an application-owned shard map. It splits its keyspace into ranges, replicates those ranges, and redistributes them across nodes. Applications send SQL to a gateway node; the database coordinates operations across the ranges involved. A multi-range transaction can cost more than a local single-range transaction, and applications must handle retryable transaction errors. CockroachDB’s stable documentation lists SERIALIZABLE as the default isolation level. See the architecture overview and transaction guidance.

The database normally splits and places ranges automatically. Use manual split or placement controls only for a measured workload need, and check the command behavior against the deployed CockroachDB version before using it. An application should not treat a range as a permanent shard: ranges can split or move without changing the application key map.

Google Cloud Spanner

Spanner also manages splits and placement. It adjusts splits as traffic and data size change; pre-splitting is available when a bulk load or known traffic event needs additional capacity sooner. The pre-splitting guide describes those cases.

Spanner’s default serializable transactions provide external consistency. Read-only operations can also use timestamp bounds, including bounded staleness when the application can accept an older consistent snapshot. These modes have different latency and freshness properties; choose them for the query’s requirements rather than assuming that every read or write is global and synchronous. See Spanner transactions and TrueTime and external consistency.

Operational Procedures

Adding a Shard

For an application-managed router, consistent hashing can limit the key space that moves when membership changes. The estimate depends on ring balance, virtual-node placement, and traffic skew, so measure planned movement before cutover. The function below is illustrative; it is not a production router:

def add_shard_with_consistent_hashing(router, new_shard_id, virtual_nodes=100):
    """
    Add a new shard to an existing consistent hash ring.
    Only keys in the new shard's range are redistributed.
    """
    # Record current state
    current_distribution = {
        shard: count_keys(router, shard)
        for shard in router.shards
    }

    # Add new shard to ring
    router.add_shard(new_shard_id, virtual_nodes)

    # Verify redistribution is limited to adjacent range
    new_distribution = {
        shard: count_keys(router, shard)
        for shard in router.shards
    }

    # Calculate migration percentage
    total_keys = sum(current_distribution.values())
    migrated = sum(abs(new_distribution.get(s, 0) - current_distribution.get(s, 0))
                   for s in set(new_distribution) | set(current_distribution)) // 2

    migration_pct = migrated / total_keys * 100
    print(f"Migration: {migration_pct:.1f}% of keys moved")

    return migration_pct  # Compare with a workload-specific migration budget

For MongoDB, adding a shard triggers automatic rebalancing of chunks across available shards. The balancer runs in the background and moves chunks gradually to avoid impacting performance.

For Citus 13, inspect the proposed shard moves before starting a rebalance. See the Citus 13 utility reference:

-- Add new worker
SELECT citus_add_node('worker-4.internal', 5432);

-- Rebalance distributed tables (runs in background)
SELECT * FROM get_rebalance_table_shards_plan();

-- Start the background rebalance after reviewing the plan
SELECT citus_rebalance_start();

Removing a Shard

Shard removal requires migrating data before decommissioning. Never remove a shard until all data has moved:

def remove_shard(router, shard_to_remove):
    """
    Safely remove a shard by migrating data first.
    """
    # 1. Stop routing new traffic to shard
    router.deactivate_shard(shard_to_remove)

    # 2. Migrate all data
    for key in router.get_keys_for_shard(shard_to_remove):
        new_shard = router.get_shard(key)  # Will route to new owner
        data = router.get_data(shard_to_remove, key)
        new_shard.put(key, data)

    # 3. Verify migration complete
    remaining = router.count_keys(shard_to_remove)
    if remaining > 0:
        raise ValueError(f"Shard still has {remaining} keys")

    # 4. Remove from ring
    router.remove_shard(shard_to_remove)

In MongoDB, use mongosh to migrate chunks off a shard before removing it. Always verify chunk counts and document migration before decommissioning.

Migration and operations checklist

For an application-managed shard map, use the reversible migration plan below. Do not enable dual writes by default; first decide how to order writes, resolve conflicts, replay failures, and make retries idempotent.

  • Test the largest and busiest shard with representative data before a production move.
  • Compare row counts and checksums, then test the queries and transactions that depend on the new placement.
  • Keep a recoverable backup and a versioned routing map until the rollback window closes.
  • Set per-shard timeouts from observed service objectives. If a query cannot return complete data after a shard timeout, fail it clearly instead of presenting partial results as complete.
  • Monitor skew, p95/p99 latency, connection pressure, and replication lag against your workload baseline; there is no universal 2x or 80% threshold.

Protect migration access with least-privilege credentials, TLS between router and database nodes, and audit logs for routing and placement changes. Store backups and their encryption keys separately from the shards they protect.

Failure scenarios

These examples illustrate failure patterns; the timings and thresholds in a real system must come from its own workload.

A hot tenant overloads one shard

A tenant’s data may be evenly distributed by row count but not by traffic. If nearly all writes belong to one tenant, hashing tenant_id still sends that tenant’s rows to the same placement. Check write rate and storage per key, not just the total number of distinct keys. A very large tenant may need a sub-key or a dedicated placement. That spreads load but makes tenant-wide joins and transactions more expensive.

A good hash function spreads different key values. It does not split one hot key across several destinations by itself. Adding random salt can make point lookups harder because the application must know where each salted copy lives; use it only with a deliberate read and write design.

A router has stale shard metadata

During an application-managed reshard, router instances can disagree about the active map. A stale router may send a request to the old location after data has moved. Version the routing map, keep the source available through cutover, and check each router’s map version before moving more traffic. If a mismatch or checksum failure appears, stop the migration. Reconcile writes before changing the route back; do not rely on a blind map flip.

Database-managed systems have their own metadata and rebalancing workflows. Do not apply a custom router’s cutover steps to CockroachDB, Spanner, or Citus internals.

A cross-shard query waits on one slow participant

A scatter-gather join or report can be limited by the slowest shard. Start with the query plan, fan-out count, per-shard latency, and the amount of data exchanged. Set request deadlines and cancel work that can no longer finish in time. Return an error or mark partial results explicitly; never present an incomplete aggregate as complete.

Where the access pattern is stable, co-locate related rows or maintain a separate reporting path. Citus can route a query to one worker when its distribution column is present and can fan out queries that span workers. The same query shape has different execution behavior in an application router or a distributed SQL database.

Schema changes reach shards at different times

If one shard has the new column while another still has the old schema, code that assumes a single schema can fail on routed or cross-shard queries. Use an expand-and-contract rollout: add a compatible schema change, deploy code that handles both forms, backfill and validate, then remove the old path only after all shards and clients have moved. Use the database’s documented online DDL tools; table rewrites and lock behavior vary by engine and version.

The destination is missing acknowledged writes

A copy or rebalance can fall behind while writes continue. Compare source and destination counts and checksums, and track the change-log or replication position. Keep one authoritative write path unless the migration system defines ordering, idempotency, and conflict resolution for both destinations. The reversible migration plan sets the rollback point and reconciliation steps.

Shard-key decision worksheet

Answer these questions with production query logs and representative data.

Question What to check
Which requests dominate reads and writes? List the common filters, joins, transaction boundaries, and write rates. Estimate what share can include the candidate key.
Is the key well distributed by traffic? Count distinct values, then check data volume and write rate per value. High cardinality alone does not prevent a hot tenant or hot account.
What data must be co-located? Identify rows that are read or updated together. A shared tenant or entity key may keep those operations local, at the cost of concentrating a large tenant.
Which queries must cross keys? Record global reports, uniqueness checks, and cross-tenant joins. Decide whether scatter-gather, a reference table, or a separate reporting path is acceptable.
Where are transactions allowed to span? List the rows that must change atomically. Application-managed shards need an explicit cross-shard transaction design; a distributed SQL system has its own transaction behavior and costs.
What happens as a key grows? Test the largest tenant or account, sequential write patterns, regional placement requirements, and the plan for splitting or moving that key.

A good candidate fits the workload’s most common access and transaction paths without concentrating writes on a few values. If every candidate creates hot keys or forces critical transactions across shards, first test simpler options such as a larger instance, indexes, read replicas, caching, or database partitioning.

Reversible migration plan

This plan applies to application-managed shard maps. Citus, CockroachDB, Spanner, and other databases provide their own migration and rebalancing operations; use the runbook for the deployed version instead of treating their internal ranges or splits as application shards.

  1. Record the current state. Version the shard map, capture row counts and checksums by key range, take a restorable backup, and record query latency, error rate, and replication lag. Define who can stop the migration.
  2. Prepare the destination. Add the new shard or key mapping without removing the old route. Copy existing data with a database-native replication feature or a durable change log. Do not assume generic dual-write is safe: both writes need idempotency, ordering, conflict handling, and a repair path.
  3. Validate before cutover. Compare counts and checksums, verify unique and foreign-key constraints, sample reads through both routes, and test the queries and transactions that will cross shard boundaries. Resolve replication lag before advancing.
  4. Canary the new map. Route a small, reversible cohort through a versioned routing table. Compare results and monitor write errors, latency, retries, and per-shard load. Keep the old data and route available.
  5. Set the rollback boundary. Before the new shard accepts primary writes, switching the routing map back may be enough. After writes land on the new shard, replay or reconcile them to the old location before routing back; otherwise the rollback can lose acknowledged writes. Pause at this boundary if change capture is behind or checksums differ.
  6. Clean up after the retention window. Keep a verified backup and the old route until the new layout has passed the agreed observation period. Remove old data only after a restore and rollback drill succeeds.

For database-managed distribution, operators generally change schema or placement through vendor tools while the database maintains its metadata. For example, Spanner can split and rebalance as traffic changes, and Citus provides a rebalance plan and background rebalance job. The application still needs a compatibility plan for its schema, queries, and transaction retries.

Interview Questions

1. Does a high-cardinality shard key guarantee even load?

No. Cardinality counts distinct values; it does not measure traffic. Measure reads, writes, and storage per value. A popular tenant can still dominate a shard even when millions of other keys exist.

2. How does Citus choose where a row lives?

In Citus 13, a distributed table has a distribution column. The coordinator uses it to route queries to workers and can fan out queries that touch several workers. Co-locating related tables on the same distribution column can keep joins local. Unique and foreign-key constraints on distributed tables must include the distribution column where the Citus documentation requires it.

3. Are CockroachDB ranges and Spanner splits application shards?

No. Both databases manage placement internally. CockroachDB divides and replicates key ranges; Spanner adjusts splits based on traffic and size. Applications still need to design keys and transactions, but should use the database's operational controls rather than maintaining a custom shard map for those internal ranges.

4. How much data moves when a consistent-hash ring gains a shard?

For an evenly distributed ring, a single added shard is expected to receive about 1 divided by the new shard count of the key space. Adding four nodes to eight therefore moves roughly one third in the idealized model, not a fixed percentage in every system. Virtual-node placement, data skew, and the migration implementation change the actual volume; measure the plan before cutover.

5. What makes an application-managed shard migration reversible?

Keep a versioned route map and the old data until validation passes. Before the destination accepts primary writes, a route change can return traffic to the old shard. After that point, first replay or reconcile acknowledged writes; simply flipping the map back can lose data.

6. Why can a cross-shard join slow down when one shard is busy?

A scatter-gather query may wait for work from several shards, so a slow participant can dominate the response time. Check the query plan, per-shard latency, skew, and network traffic. Use a timeout only when the application can handle an incomplete or failed result; do not return partial data as if it were complete.

Further Reading

Papers:

  • “Dynamo: Amazon’s Highly Available Key-value Store” — describes a design based on consistent hashing and eventual consistency
  • “Bigtable: A Distributed Storage System for Structured Data” — sharding model behind Google’s database infrastructure
  • “Spanner: Google’s Globally Distributed Database” — TrueTime and global consistency guarantees

Books:

  • Designing Data-Intensive Applications by Martin Kleppmann — a reference for partitioning, replication, and consistency models
  • Database Internals by Alex Petrov — deep dive into storage engines, B-trees, and LSM trees underlying distributed databases

Tools and References:

Related Topics:

Conclusion

Use this checklist before choosing or changing a shard layout:

  • Choose a key from observed query patterns, transaction boundaries, and per-key traffic; cardinality by itself is not a load estimate.
  • Identify who owns routing, placement changes, and recovery: your application, an extension coordinator, or the database.
  • Keep the old route and data through validation. Define how to reconcile writes before naming a rollback point.
  • Keep common joins local where that does not create a hot key. Put deadlines on fan-out queries and report incomplete results explicitly.
  • Set alerts from your service objectives and workload baseline. Rehearse the system-specific migration and restore procedure before production needs it.

Category

Related Posts

Asynchronous Replication: Lag, Failover, and Freshness

Learn how asynchronous database replication affects read freshness, failover data loss, lag monitoring, and recovery choices during network partitions.

#distributed-systems #replication #eventual-consistency

Consistent Hashing for Load Balancing

Learn how consistent-hash rings, virtual nodes, and bounded-load policies reduce reassignment, and when sticky sessions still make sense.

#load-balancing #consistent-hashing #distributed-systems

etcd: Distributed Key-Value Store for Configuration

Deep dive into etcd architecture using Raft consensus, watches for reactive configuration, leader election patterns, and Kubernetes integration.

#distributed-systems #databases #etcd