Skip to main content
The Art of Database Sharding
Tutorial 8m

The Art of Database Sharding

Understanding when to shard and how to choose a shard key to avoid hotspots. Practical examples with Postgres.

Partha Saradhi•Oct 15, 2023• 8m• 890 views

Database sharding — the practice of splitting a large dataset horizontally across multiple database instances — is one of the most misused scaling patterns in engineering. Teams shard too early, choose the wrong shard key, and end up with a distributed system that is harder to operate than the monolith they escaped.

When to Shard

Sharding is a tool of last resort. Before you shard, you should have exhausted: read replicas, connection pooling (PgBouncer), query optimization, partial indexes, table partitioning, and vertical scaling. Most teams that think they need sharding actually need better indexing.

  • Your primary key space exceeds what fits on a single disk (100GB+ tables).
  • Write throughput has saturated a single master and replication lag is > 1s.
  • Regulatory requirements mandate data locality (GDPR, HIPAA).

Choosing a Shard Key

The shard key determines which database instance each row lives on. A bad shard key creates hotspots — one shard absorbs 80% of queries while others sit idle. The ideal shard key has high cardinality, is immutable, and is present in most queries.

Shard Key Anti-Pattern: Timestamp

Never shard by created_at or any time-based field. All new inserts land on the same shard (the "current" one), creating a write hotspot. Use tenant_id, user_id, or a consistent hash of the entity's natural key instead.

Avoiding Hotspots

Hotspots occur when a small subset of shard key values generates a disproportionate amount of traffic. The classic example: a social platform sharding by user_id, where a celebrity's account generates 10,000x the traffic of an average user.

Mitigation strategies: Virtual shards — map logical shard IDs to physical nodes with a lookup table, allowing rebalancing without rehashing. Salt the key — append a random suffix (e.g., user_123_0 through user_123_9) to spread a hot entity across multiple physical shards.

Postgres Implementation

partition_setup.sql
sql
-- Range partition orders by customer_shard_id (pre-computed)
CREATE TABLE orders (
  id          BIGSERIAL,
  customer_id UUID        NOT NULL,
  shard_id    SMALLINT    NOT NULL,  -- 0-255
  amount      NUMERIC(12,2),
  created_at  TIMESTAMPTZ DEFAULT NOW()
) PARTITION BY RANGE (shard_id);

-- Shard 0: customers 0-63
CREATE TABLE orders_s0 PARTITION OF orders
  FOR VALUES FROM (0) TO (64);

-- Shard 1: customers 64-127
CREATE TABLE orders_s1 PARTITION OF orders
  FOR VALUES FROM (64) TO (128);

-- Index on shard boundary
CREATE INDEX ON orders (customer_id, shard_id);

Use Postgres Partitioning First

Native table partitioning in Postgres 14+ handles most sharding use-cases without the operational complexity of a distributed system. Partition by range or hash, and let Postgres prune partitions automatically during query planning. Only move to external sharding when partitioning hits its limits.

#postgres#database#sharding#scalability