Skip to the page

Design building blocks · mid

SQL or NoSQL, and choosing a shard key

Choose the store by access pattern, consistency need, scale and team skills. Scale SQL step by step before sharding, and when you shard, choose a key that matches the most frequent query and avoids hot shards.

The notes

What you must know

  • Wallets and transactions: relational (Postgres, MySQL) for ACID, constraints and joins for reconciliation. Catalogue: a document store or Postgres with JSONB and GIN indexes, plus a search engine for text and facets.
  • Chat: wide-column (Cassandra, ScyllaDB) or DynamoDB, partitioned by conversation id and sorted by sequence: high write throughput and simple queries.
  • Scale SQL first: indexes, read replicas, partitioning, archiving, a bigger instance. Then sharding (Vitess for MySQL, Citus for Postgres) or distributed SQL (CockroachDB, YugabyteDB, TiDB, Spanner, Aurora DSQL).
  • NoSQL costs: you design around queries up front, ad hoc queries and joins are limited, and some modes are only eventually consistent.
  • Shard key for orders: choose by the most frequent, latency-sensitive query. Customer id keeps a customer history on one shard. Date as the key sends all new writes to one shard. Seller id makes big sellers hot.
  • Seller views come from a separate read model (CDC into a store partitioned by seller, or an analytics database). Order id lookups: put the shard number in the order id, or keep a lookup table.
  • Hash sharding spreads load but loses range scans. Use many logical shards (say 1,024) mapped to fewer machines so rebalancing moves logical shards.
  • Resharding: copy with CDC or dual writes, backfill, verify, switch reads, then writes. Cross-shard reports go to a warehouse fed by CDC, not scatter-gather on live databases.

The red pen

Common traps: mistake → fix

  • Mistake: NoSQL because it scales

    Fix: name the access pattern first.

  • Mistake: SQL does not scale

    Fix: it scales a long way before sharding is needed.

  • Mistake: Shard by date

    Fix: all new writes hit one hot shard.

  • Mistake: Store money in a store without transactions

    Fix: use ACID.

Easy to hard

Questions interviewers ask, easy to hard

  1. SQL or NoSQL for wallets, a catalogue and chat?
  2. What do you try before sharding?
  3. How do you choose a shard key for orders?
  4. How do you add shards later?
  5. How do you answer queries across shards?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview