Menu

Earn Premium with Referrals

Invite your friends and earn Premium rewards through our referral program.

See how it works and start inviting friends.

Distributed SQL and Sharding
SQL

Distributed SQL and Sharding

Explore horizontal scaling, replication, and how modern distributed SQL engines bridge the gap between SQL and NoSQL.

When a single database server is no longer enough, you must distribute data across multiple machines. This is where sharding and distributed SQL come into play.

Sharding

Sharding splits a large database into smaller, independent databases called “shards”. Each shard holds a subset of the data and runs on its own server (or set of servers).

-- Shard key determines which shard stores a row
-- Example: Shard by user_id
-- Shard 1: user_id 1-10000
-- Shard 2: user_id 10001-20000
-- Shard 3: user_id 20001-30000

Sharding Strategies

StrategyHow It WorksBest For
Range-BasedPartition by ID range (1-1000, 1001-2000)Sequential data, simple to implement
Hash-BasedHash the shard key, mod by shard countEven distribution, no hot spots
Directory-BasedLookup table maps keys to shardsFlexible, dynamic rebalancing
GeographicPartition by regionMulti-region applications

Sharding Challenges

  • Cross-shard queries: Queries that span multiple shards are slow and complex.
  • Rebalancing: Adding or removing shards requires redistributing data.
  • Transactions: Distributed transactions across shards are expensive (2PC).
  • Joins: Joining data across shards must happen in the application layer.
  • Auto-increment IDs: Global unique IDs are harder to generate (use UUIDs or Snowflake IDs).

Replication

Replication copies data from one server to another for redundancy and read scaling.

TypeDescription
Master-SlaveOne primary (writes), multiple replicas (reads)
Multi-MasterMultiple nodes accept writes (conflict resolution needed)
SynchronousWrite is committed on all replicas before ack (slower)
AsynchronousWrite is ack’d immediately, replicated later (faster, possible data loss)

Distributed SQL

Modern distributed SQL databases (like CockroachDB, YugabyteDB, Google Spanner) aim to provide the SQL interface and ACID guarantees of traditional databases while scaling horizontally like NoSQL.

Key features:

  • Automatic sharding and rebalancing.
  • Distributed ACID transactions across shards.
  • SQL interface (joins, aggregations, constraints).
  • Multi-region deployment with low-latency reads.

Distributed SQL vs NoSQL Sharding

AspectDistributed SQLNoSQL Sharding
ConsistencyStrong ACIDEventual (BASE)
Query CapabilityFull SQL (joins, aggregates)Limited (key-based lookups)
TransactionsDistributed transactionsSingle-document transactions
Operational ComplexityAutomated (rebalancing, repair)Manual (shard management)

Read/Write Splitting (Application-Level Sharding)

For applications that need both consistency and scale, a common pattern is:

Writes   → Master PostgreSQL instance
Reads    → Read replicas (asynchronously replicated)
Analytics → Dedicated columnar store

This allows the main database to handle writes without being slowed down by heavy reporting queries.

Q: What is sharding?

A: Sharding is a horizontal scaling technique where data is split across multiple independent database servers. Each shard holds a subset of the data and operates independently.

Q: What are the challenges of sharding?

A: Cross-shard queries are slow, joins across shards are complex, distributed transactions are expensive, and rebalancing data when adding/removing shards is operationally difficult.

Q: What is the difference between sharding and partitioning?

A: Partitioning splits tables within a single database instance. Sharding distributes data across multiple physical servers. Partitioning is a feature of the database engine; sharding is an architectural pattern.

Q: What is a shard key and how do you choose one?

A: A shard key determines which shard stores each row. A good shard key distributes data evenly and avoids “hot spots”. Common choices: user_id (hash), customer_id (range), or geographic region.

1. Design a social media database.

Challenge: 500M users, each with posts, likes, and comments. Solution: Shard by user_id (hash-based). User data, posts, and comments for a user stay on the same shard. Cross-shard queries (e.g., “find posts liked by friends”) are done at the application layer.

2. Choose between distributed SQL and NoSQL for a multi-region finance app.

Answer: Distributed SQL (CockroachDB). Finance requires ACID across regions. NoSQL’s eventual consistency could lead to overdrafts or double-spending.

3. Design for a global e-commerce platform.

Architecture:

  • Product catalog: MongoDB (flexible schema, global replication).
  • Orders/Payments: Distributed SQL (CockroachDB, ACID required).
  • Session cache: Redis (key-value, fast).
  • Search: Elasticsearch (full-text search).
  • Analytics: ClickHouse (columnar).

My Private Notes

Notes are auto-saved locally to this device.