Databases: SQL, NoSQL, Sharding

System Design · Scaling & Data · Intermediate · 16 min

Pick the right database and split data when it gets too big.

A wall of filing cabinets. A clerk adds up the letters of each name to pick a cabinet, so 'alice' always goes to cabinet 2. Pick the label badly (everyone's country) and one cabinet overflows while the rest stand empty. Photocopies of a cabinet (replicas) let more people read at once, a moment behind the original.

The idea in everyday words

SQL is a strict filing cabinet with labelled folders and rules (every invoice must have a customer). NoSQL is a big box of flexible notebooks, and each can have different pages. Sharding = when one cabinet is full, buy more cabinets and file A–M in cabinet 1 and N–Z in cabinet 2.

SQL vs NoSQL

SQL (Postgres, MySQL) NoSQL (MongoDB, DynamoDB, Cassandra)
Shape Tables, fixed schema Documents / key-value / wide-column
Joins Great Limited
Transactions Strong (ACID) Varies
Scale Vertical + read replicas Built for horizontal
Use Payments, orders Feeds, logs, IoT, catalogs

Replication vs Sharding

  • Replication: copies of the same data. One primary takes writes, replicas serve reads. Helps reads + survives failure.
  • Sharding: split rows across machines by a shard key (e.g. user_id). Helps writes + storage.
  • Bad shard key → hot shard (e.g. sharding by country when 80% users are in one country).

CAP theorem (simple)

When the network breaks (Partition), you must choose: Consistency (everyone sees the same latest data, maybe errors) or Availability (always answer, maybe stale). Banks pick C, social feeds pick A.

Step by step

  1. Write:

    User 1234 posts → hash(1234) % 4 = shard 2.

  2. Primary:

    Shard 2's primary saves it.

  3. Replicate:

    Copies stream to 2 replicas (async).

  4. Read:

    Feed reads go to a replica: fast, but maybe a little stale (usually milliseconds, more under load).

Code example

def shard_for(key, num_shards):
    h = sum(ord(c) for c in str(key))   # toy hash
    return h % num_shards

for user in ["alice", "bob", "carol", "dave"]:
    print(user, "-> shard", shard_for(user, 3))

Interview tips

  • Cloud SQL: AWS RDS/Aurora, GCP Cloud SQL/Spanner, Azure SQL. NoSQL: DynamoDB, Firestore/Bigtable, Cosmos DB; open source Postgres, MongoDB, Cassandra.

  • Mention consistent hashing to avoid moving all data when adding shards.

  • Indexes speed reads but slow writes.

Challenge: Toy Shard Router

Return the shard for a string key: add up the character codes (ord / charCodeAt) and take % num_shards.

Example: shard_for("ab", 3) → (97+98) % 3 = 0

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Scaling & Data

Previous: Caching (Redis & CDN) · Next: Choosing a Database on AWS