Skip to main content

Module 3: Databases

Database Sharding

Split a large database across shards — shard keys, hotspots, routing, cross-shard queries, resharding, and when to shard vs replicate.

When one primary can no longer hold write volume or data size, you partition rows across multiple databases (shards). Sharding scales writes — and multiplies operational pain — so interviews expect you to justify the shard key and name the hard parts.

What you will learn

  • Explain when to shard vs scale up / add read replicas
  • Pick shard keys that appear in queries and avoid hotspots
  • Describe request routing (hash, range, directory)
  • List cross-shard query and transaction problems
  • Outline resharding and consistent-hashing approaches
An app router hashes a user id and sends the request to one of three database shards.
The shard key picks one database. Cross-shard transactions are the expensive part.

When sharding becomes necessary

  • Sharding is a last-mile scale move. Exhaust simpler options first so you do not own N databases too early.
  • Single primary CPU, IOPS, or storage is saturated even after tuning
  • Write QPS exceeds what vertical scale and batching can absorb
  • Dataset size outgrows comfortable backup/restore and buffer-pool fit
  • Try first: indexes, caching, read replicas, vertical scale, queueing writes
  • Sharding helps writes and data size; it does not fix a bad data model by itself

How sharding works

  • Horizontal partitioning: each shard is its own database holding a subset of rows.
  • Rows are assigned by a shard key (userId, tenantId, geo, orderId, …)
  • App, proxy, or coordinator routes each query to the right shard(s)
  • Each shard can have its own primary + replicas
  • Global uniqueness often uses snowflake/ULID IDs or per-shard sequences + prefixes
  • The system becomes a fleet of smaller databases, not one magic bigger box

Choosing a shard key

  • The shard key is the most important design decision. Bad keys create permanent hotspots.
  • Must appear in almost every query path you care about
  • Should spread load evenly — high cardinality, not a few hot values
  • Stable — changing a row’s shard key means migrating data
  • Common choices: userId/tenantId for multi-tenant SaaS; geo for locality
  • Avoid monotonic keys alone (time, auto-increment) without bucketing — they create write hotspots

Routing strategies

  • Once you have a key, decide how key → shard is computed.
  • Hash sharding — hash(key) % N or consistent hashing; even spread, range queries harder
  • Range sharding — key ranges map to shards; good for range scans, risk of hot ranges
  • Directory / lookup service — key → shard map in a metadata store; flexible, extra hop
  • Consistent hashing reduces remapping when N changes (see earlier lesson)
  • Entity groups: keep related rows that must transaction together on one shard

Hot shards & skew

  • Even with a good key, popularity is not uniform. Celebrity tenants melt one shard.
  • Hot key: one user/tenant/product gets disproportionate traffic
  • Mitigations: cache aggressively, split hot entity into sub-shards, dedicated shard, rate limits
  • Monitor per-shard QPS, CPU, and replication lag — averages hide skew
  • Rebalancing may be required even if the hash looks uniform on paper

Cross-shard queries

  • Queries without the shard key become scatter-gather — slow, expensive, and fragile.
  • Fan-out to many shards, merge in the app/coordinator
  • Global secondary indexes or search clusters for non-key lookups (email → user)
  • Avoid cross-shard JOINs; denormalize or precompute instead
  • Pagination and sorting across shards need careful merge logic
  • Design APIs so the shard key is always known when possible

Transactions & consistency

  • ACID inside one shard is still possible. Across shards, you leave the easy path.
  • Keep transactions single-shard whenever you can (co-locate related data)
  • Cross-shard 2PC is slow and reduces availability
  • Sagas / outbox patterns for multi-shard workflows with compensation
  • Idempotency keys matter when retries span multiple shards
  • Unique constraints are per-shard unless you add a global allocator/service

Resharding

  • N will change. Plan how data moves without long downtime.
  • Split a hot shard into two; or add capacity with consistent hashing
  • Dual-write / shadow-read during migration; verify checksums before cutover
  • Move data in the background; keep a rollback plan
  • Metadata versioning so routers know the current map
  • Resharding is why teams delay sharding until metrics force it

Sharding vs related ideas

  • Keep vocabulary clean so the interviewer trusts your diagram.
  • Vertical split — different tables/services on different DBs (by domain), not by row key
  • Read replicas — copy the same data for read scale; writes still hit one primary
  • Partitioning (within one engine) — table partitions on one server/cluster feature
  • Sharding — separate databases/servers, each owning a key range or hash bucket
  • Often used loosely as synonyms — define what you mean in the interview

Common mistakes

  • These choices create long-term pain.
  • Sharding before caching, indexing, and replicas are exhausted
  • Shard key missing from the hottest query paths
  • Assuming hash % N never needs resharding care
  • Cross-shard joins in the request path as a habit
  • No hotspot plan for celebrity tenants

Interview framing

  • Use this order when the write path outgrows one primary.
  • Show you tried simpler levers first
  • Propose shard key + routing method and why load spreads
  • Draw app → router → shard primaries (+ replicas)
  • Call out cross-shard and hotspot limitations explicitly
  • Sketch how you would add a shard later (consistent hash / split)

Quick revision checklist

  • Start with vertical split and replicas before sharding one giant table.
  • Pick a shard key that is on every hot query and evenly distributed.
  • Mention lookup service or consistent hashing for routing.
  • Name cross-shard joins/transactions as expensive.
  • Have a hotspot story for celebrity keys.
  • Describe a careful resharding/migration approach.

FAQs

Sharding vs partitioning?

Often used interchangeably. “Partitioning” may be within one engine; “sharding” usually means separate servers/databases. Define your meaning in the interview.

Sharding vs replication?

Replication copies the same data for durability and read scale. Sharding splits different rows across nodes to scale writes and storage. Many designs use both: each shard is replicated.

What makes a good shard key?

High cardinality, even access distribution, present on almost every query, and stable. userId/tenantId are common; pure timestamps are risky hotspots.

How do I look up by email if I shard by userId?

Use a global secondary index, a dedicated lookup service/table, or a search system. Scatter-gather across all shards on every email login is a last resort.

Can I run ACID transactions after sharding?

Yes within a single shard. Cross-shard transactions need 2PC or sagas and are slower/harder — co-locate data that must commit together.

When should I not shard?

When vertical scale, indexes, caching, and read replicas still meet SLOs. Sharding adds routing, resharding, and cross-shard complexity that small systems should avoid.

Practice

Learner’s Task

  • Practice out loud for 8–10 minutes. Design sharding for one write-heavy table.
  1. Pick a workload (Twitter-like posts or multi-tenant SaaS) and state why one primary is not enough.
  2. Choose a shard key and routing method (hash / range / directory); justify even load.
  3. Draw client → router → 3 shards (each with a replica) and mark where a write goes.
  4. Name one cross-shard query you refuse to do in the request path and your alternative.
  5. Write a 4-sentence closing: why shard, key choice, hotspot risk, and resharding approach.