PrepStack › Databases › Scaling Databases
Scaling Databases interview cheat sheet
Replication, partitioning, sharding, consistency, CAP/PACELC and distributed SQL
System design and senior backend interviews almost always reach the question “and how does the database scale?”. Interviewers want to see that you scale in the right order (optimise, cache, pool, replicate, then shard), that you know what each step costs (replication lag, hot shards, cross-shard queries, distributed transactions), and that you can use CAP, PACELC and consistency models correctly. Read the 15-minute revision first; the small simulations show the numbers behind each idea. Then switch to Quiz mode and answer out loud.
15-minute revision
- Scale in order: measure and optimise queries → cache → pool connections → scale up → read replicas → partition → shard. Every step adds operational cost, so do not skip ahead.
- Vertical scaling = bigger machine (simple, has a ceiling, one failure domain). Horizontal scaling = more machines (no hard ceiling, but you now own distribution problems).
- Size a pool with Little's law: busy connections ≈ QPS × average query time. A pool far bigger than the database's cores makes things slower, not faster.
- Read replicas scale reads, not writes. Async replicas lag, so give users read-your-writes (route to primary after a write, or wait for the replica to reach the write's LSN/GTID).
- Replication: single-leader (simple, one write node), multi-leader (writes in many regions, conflicts), leaderless (quorums, Dynamo-style). Sync = no loss but slower; async = fast but can lose the last writes on failover; semi-sync = at least one replica has it.
- Split brain = two nodes both accept writes as primary. Prevent it with a majority-based failure detector (etcd/ZooKeeper/Raft) plus fencing (epoch tokens, STONITH).
- Partitioning splits a table inside one database; sharding spreads partitions across servers. Vertical partitioning splits columns, horizontal splits rows, federation splits by business function.
- Sharding strategies: range (good scans, hot tail), hash (even spread, no range scans), directory/lookup (flexible, extra hop), geo (data residency, low latency).
- A good shard key has high cardinality, even load, appears in most queries and keeps related rows together (for example
tenant_id,user_id). It is very hard to change later. - Hash mod N moves almost every key when N changes. Consistent hashing with virtual nodes moves only about 1/N of keys and keeps load even.
- Hot spots / celebrity problem: one key gets most traffic. Fix with key salting (split into sub-keys), caching, dedicated shards, or a hybrid fan-out.
- Cross-shard queries are scatter-gather: push down filters and LIMIT, merge at the coordinator, and rebuild AVG from SUM and COUNT. Avoid cross-shard joins by co-locating or denormalising.
- 2PC gives atomic commits across nodes but blocks if the coordinator dies. Sagas use local transactions plus compensations and accept eventual consistency.
- Global IDs: Snowflake (41-bit ms time + 10-bit worker + 12-bit sequence), UUIDv7 (RFC 9562, time-ordered, index friendly), ticket servers. Avoid random UUIDv4 as a clustered key.
- CAP: during a network partition you choose consistency (linearizability) or availability. PACELC adds: else (normal operation) you trade latency against consistency.
- Quorums: with N replicas, R + W > N means every read set overlaps the latest write set. N=3, W=2, R=2 is the classic setting.
Foundations: scale the cheap way first
Vertical vs horizontal scaling
Scale up (a bigger box) until it hurts, then scale out (more boxes), because scale-out turns one database into a distributed system.
- Vertical scaling (scale up): more CPU, RAM, faster NVMe disks and network on the same server. No code changes, and you keep ACID transactions and joins.
- Limits of scaling up: a hardware ceiling, cost that grows faster than capacity at the top end, a single failure domain, and a restart or failover to resize.
- Horizontal scaling (scale out): add servers. For reads this means replicas; for writes and data size it means sharding.
- Scale-out brings distributed problems: replication lag, rebalancing, cross-node queries and transactions, partial failures and more moving parts to operate.
- Most databases are bound by one resource first: CPU (bad queries), memory (working set does not fit in cache), disk IOPS, or connections. Find which one before choosing a fix.
- Stateless app servers scale out easily. The database is hard to scale out because it holds state that must stay correct.
Interview questions
- What is the difference between vertical and horizontal scaling of a database?
- When would you choose to scale up instead of scaling out?
- Why is it harder to scale a database horizontally than an application server?
Query optimisation & caching first
Most “we need to shard” problems are really missing indexes, N+1 queries or no cache; fix those first because they are 10–100× cheaper.
- Measure first: slow query log (MySQL),
pg_stat_statements(Postgres), APM traces. Optimise the queries that use the most total time, not just the slowest single one. - Read plans with
EXPLAIN/EXPLAIN ANALYZE. Look for full scans on big tables, bad row estimates, sorts spilling to disk and nested loops over large inputs. - Typical fixes: the right composite index (equality columns first, then range), covering indexes, removing N+1 queries, keyset pagination instead of large
OFFSET, and batching writes. - Cache hot, read-heavy data in Redis or Memcached. Cache-aside is the default: read cache → on miss read DB → set with TTL; on write update DB then delete the key.
- Other cheap wins: materialized views or summary tables for heavy aggregates, denormalised columns (counters), moving analytics to a separate replica or warehouse, and archiving cold data.
- Protect the DB from cache stampedes: request coalescing (single-flight), jittered TTLs, and serving stale values while one worker refreshes.
Interview questions
- Your database CPU is at 90%. What do you do before adding hardware?
- Explain cache-aside and its main pitfalls.
- When does caching not help the database?
Connection pooling
Reuse a small, fixed set of database connections; the right pool size comes from Little's law, not from “more is better”.
- Opening a connection costs a TCP and TLS handshake plus authentication. In PostgreSQL each connection is also a separate backend process with its own memory.
- App-side pools (HikariCP, SQLAlchemy pool, node-postgres
Pool) live in each app instance. With 50 pods × 20 connections you already have 1,000 connections. - Server-side poolers (PgBouncer, pgcat, Supavisor, RDS Proxy, ProxySQL for MySQL) sit in front of the DB and multiplex many client connections onto a few server ones.
- Little's law: busy connections = QPS × average time a connection is held. Slow queries and long transactions eat connections much faster than extra traffic does.
- More connections than the DB can run in parallel just adds context switching and lock contention. HikariCP's guide suggests starting near
cores × 2 + effective spindlesand then load testing. - Serverless functions (Lambda) create connection storms; put a pooler or a data API in front of the database.
Interview questions
- Why do we need connection pooling?
- How do you choose a pool size?
- What is the difference between session and transaction pooling in PgBouncer?
Replication & high availability
Read replicas, lag & read-your-writes
Replicas copy the primary's log to serve reads; with async replication they lag, so you must route reads that need fresh data carefully.
- The primary handles all writes. It streams its change log (Postgres WAL, MySQL binlog) to replicas, which replay it and serve read-only queries.
- Use them for read-heavy apps (often 80–95% reads), reports and analytics, backups, and as failover candidates.
- Replication lag is how far a replica is behind, in bytes, transactions or seconds. It grows with heavy write bursts, long queries on the replica, slow networks or big transactions.
- Read-your-writes options: read from the primary for a short time after a user writes; route to primary for that user's own data; or track the commit LSN/GTID and only use a replica that has replayed it.
- Other anomalies: monotonic reads (a user hits a fresh replica, then a staler one, and sees data go back in time). Fix with sticky routing per user or session.
- Monitor lag:
pg_stat_replication(replay_lag) on the Postgres primary,SHOW REPLICA STATUSin MySQL. Take lagging replicas out of the read pool automatically.
Interview questions
- What is replication lag and how does it affect users?
- How do you guarantee read-your-writes with read replicas?
- Can read replicas fix a write bottleneck?
- How would you handle a replica that falls far behind?
Replication types: leaders, sync & async
Choose how many nodes accept writes (one, many or any) and how long a commit waits for replicas (sync, semi-sync, async).
- Single-leader: one primary takes writes, replicas follow. No write conflicts; the default for Postgres, MySQL, SQL Server and MongoDB replica sets.
- Multi-leader: several nodes (often one per region) accept writes and replicate to each other. Low local write latency and region failover, but write conflicts need resolution (LWW, CRDTs, app merge).
- Leaderless (Dynamo-style: Cassandra, ScyllaDB, Riak): the client or a coordinator writes to several replicas and reads from several, using quorums, read repair and anti-entropy.
- Synchronous: commit waits until a replica confirms. No data loss on failover, but higher latency, and writes stall if that replica is down.
- Asynchronous: commit returns after the local flush. Fast, but a failover can lose the last few transactions (RPO > 0).
- Semi-synchronous: wait for at least one replica to receive (not necessarily apply) the change, then return. MySQL's semi-sync falls back to async after a timeout; Postgres can wait for
FIRST norANY nstandbys.
Interview questions
- Compare synchronous, asynchronous and semi-synchronous replication.
- When would you use multi-leader replication?
- How do leaderless databases like Cassandra stay consistent?
- What is the problem with last-write-wins?
Failover & split brain
Failover promotes a replica when the primary dies; the hard part is being sure it is really dead and making sure the old one can never write again.
- Steps: detect failure (missed heartbeats), agree on it (a majority, not one watcher), choose the most up-to-date replica, fence the old primary, promote, and repoint clients and other replicas.
- Tools: Patroni (Postgres, uses etcd/Consul/ZooKeeper as the source of truth), MySQL InnoDB Cluster / Group Replication, Orchestrator, and managed services such as RDS Multi-AZ or Aurora.
- Split brain: a network partition or a long pause makes two nodes believe they are primary. Both accept writes and the data diverges.
- Prevent it with a majority quorum (an odd number of voters across failure zones) and fencing: STONITH (power off the old node), revoking its VIP or credentials, or fencing tokens that storage checks.
- With async replication a failover loses the unreplicated tail. Know your RPO (data you may lose) and RTO (time to recover).
- When the old primary comes back it must rejoin as a replica (for example with
pg_rewind), never as a second primary.
Interview questions
- What is split brain and how do you prevent it?
- Walk me through an automatic failover.
- How much data can you lose in a failover?
Partitioning & sharding
Partitioning: vertical, horizontal & federation
Split data so each piece is smaller: by columns (vertical), by rows (horizontal) or by business function (federation); sharding is horizontal partitioning across servers.
- Vertical partitioning: move some columns to another table, for example large
bio/settingsblobs out of a hotuserstable. Rows get smaller and more fit in memory. - Horizontal partitioning: split rows by a key (date, tenant, region) into partitions with the same schema. In one database this is table partitioning; across servers it is sharding.
- Postgres declarative partitioning supports
RANGE,LISTandHASH. The planner prunes partitions that cannot match theWHEREclause. - Huge win for time-series and retention: dropping or detaching an old partition is instant, while
DELETEof millions of rows causes bloat and load. - Federation (functional partitioning): separate databases per domain (users, orders, catalog). Each DB is smaller and can scale on its own, but joins across them move into the app.
- Partitioning alone does not add hardware; it improves maintenance, pruning and index sizes. Sharding adds machines.
Interview questions
- What is the difference between partitioning and sharding?
- Vertical vs horizontal partitioning?
- What is database federation?
Hot spots & the celebrity problem
Even with a good key, one key can get a huge share of traffic; split the hot key, cache it, or handle it with a different path.
- A hot spot is a shard with much more load than the others. Causes: skewed keys (celebrities, viral posts, big tenants), monotonic keys, or time-of-day patterns.
- Key salting / splitting: write to
key#0…key#k-1at random and sum or merge on read. Writes spread out; reads get k times more expensive. - Sharded counters: keep N counter rows for a like count and add them up (or aggregate them asynchronously). Writes never contend on one row.
- Caching and coalescing: hot reads come from a cache or CDN; many identical requests are collapsed into one DB read.
- Isolation: move a whale tenant or celebrity to a dedicated shard, or split a hot range (range-based systems like CockroachDB and Bigtable split and move hot ranges automatically).
- Celebrity feeds: fan-out-on-write to millions of followers is too expensive, so use fan-out-on-read for celebrities and fan-out-on-write for normal users (hybrid).
Interview questions
- What is the celebrity problem and how do you solve it?
- How would you implement a like counter for a viral post?
- Your monitoring shows one shard at 95% CPU and others at 20%. What do you do?
Resharding & consistent hashing
With hash mod N, adding one shard moves most keys; consistent hashing with virtual nodes moves only about 1/N of the keys and keeps load balanced.
- Resharding = changing the number of shards or moving data between them. You need it when shards get too big, too hot, or you add capacity.
- With
hash(key) mod N, going from N to N+1 moves about N/(N+1) of all keys (about 80% for 4→5). That is a full data migration. - Consistent hashing places nodes and keys on a ring. A key belongs to the first node clockwise. Adding a node only takes keys from its neighbours: about 1/N moves.
- Virtual nodes (many points per physical node) smooth out the load, let bigger machines take more points, and spread a failed node's load across many peers.
- Alternatives: a fixed number of logical shards mapped to hosts (Vitess keyspace ranges, Citus shards, Elasticsearch primary shards), jump consistent hash, and rendezvous (HRW) hashing.
- Online resharding steps: copy (backfill) data → stream ongoing changes (CDC/binlog) → verify → switch reads/writes per shard → clean up the old copy.
Interview questions
- What is consistent hashing and why is it used?
- Why do we need virtual nodes?
- How do you reshard a live database without downtime?
Cross-shard queries & joins
Queries without the shard key fan out to every shard and merge results; design so the hot paths stay on one shard.
- Single-shard query: the router uses the shard key to pick one shard. Fast and scales linearly. Aim for this on all hot paths.
- Scatter-gather: send the query to all shards in parallel and merge. Latency = the slowest shard, and load grows with shard count.
- Push work down: each shard applies
WHERE,ORDER BYandLIMIT k(oroffset + limit); the coordinator merges and cuts again. RebuildAVGfromSUMandCOUNT; distinct counts need sketches like HyperLogLog. - Avoid cross-shard joins: co-locate related tables on the same key, replicate small tables to every shard (reference/broadcast tables), or denormalise the joined fields.
- Cross-shard reports belong in a warehouse or OLAP store fed by CDC, not on the OLTP shards.
- Deep pagination across shards is expensive; use keyset (cursor) pagination on a globally ordered key.
Interview questions
- How do you run a join across shards?
- How do you paginate “latest posts across all users” on a sharded database?
- Why can't you average per-shard averages?
Distributed correctness
Distributed transactions: 2PC & sagas
2PC makes several nodes commit atomically but blocks on coordinator failure; sagas chain local transactions with compensations and give eventual consistency.
- Two-phase commit (2PC): phase 1 the coordinator asks every participant to prepare (make the change durable and keep locks) and vote; phase 2 it logs the decision and tells all to commit or abort.
- 2PC is blocking: if the coordinator dies after participants voted yes, they hold locks until it recovers. It also adds round trips and couples availability of all participants.
- Distributed SQL (Spanner, CockroachDB, YugabyteDB) runs 2PC over consensus-replicated participants, so a single node failure does not block it.
- Saga: a sequence of local transactions; if step k fails, run compensating transactions for steps k−1 … 1. No global locks, but intermediate states are visible.
- Choreography (services react to each other's events) vs orchestration (a central orchestrator, often a workflow engine such as Temporal, drives the steps).
- Make sagas reliable with the transactional outbox (write the event in the same local transaction), idempotent handlers and retries. Use semantic locks (a
PENDINGstatus) to reduce anomalies.
Interview questions
- Explain two-phase commit and its drawbacks.
- What is a saga and how is it different from 2PC?
- Choreography vs orchestration in sagas?
- How would you place an order that reserves stock, charges a card and creates a shipment across services?
Global unique IDs: Snowflake, UUIDv7, ticket servers
Once you shard, auto-increment no longer gives unique ids; use time-ordered 64-bit Snowflake ids or 128-bit UUIDv7 instead of random UUIDv4.
- Per-shard auto-increment collides across shards. A quick fix is step/offset (
auto_increment_incrementandauto_increment_offsetin MySQL), but adding shards gets awkward. - Ticket servers (Flickr): a tiny DB whose only job is handing out auto-increment numbers; two servers with odd/even offsets for availability. Simple, but a central dependency.
- Snowflake (Twitter): 64-bit = 41 bits of milliseconds since a custom epoch (about 69 years) + 10 bits worker id + 12 bits sequence (4,096 ids per ms per worker). Fits a
BIGINT, sorts roughly by time. - UUIDv4 is fully random: no coordination, but random inserts into a B-tree cause page splits and poor cache locality, and 16 bytes per key in every index.
- UUIDv7 (RFC 9562, 2024): 48-bit Unix ms timestamp then random bits. Globally unique without coordination and roughly ordered, so inserts go to the right-hand edge of the index. PostgreSQL 18 ships
uuidv7(). - Time-based ids leak creation time and need sane clocks: Snowflake must refuse or wait if the clock moves backwards.
Interview questions
- How do you generate unique ids in a sharded system?
- Why is UUIDv4 a bad primary key for some databases?
- Explain the Snowflake id layout and its limits.
CAP theorem & PACELC
CAP: when the network partitions, a replicated system must give up either linearizable consistency or availability; PACELC adds that without a partition you still trade latency for consistency.
- C in CAP means linearizability (every read sees the latest write, as if there is one copy). It is not the C in ACID.
- A means every request to a non-failed node gets a non-error response, eventually. P means the system keeps working while messages between nodes are lost.
- Partitions will happen, so “choose 2 of 3” is misleading. The real choice is: during a partition, refuse some requests (CP) or answer with possibly stale data (AP).
- CP examples: a majority-quorum system (etcd, ZooKeeper, Spanner, CockroachDB) where the minority side stops serving. AP examples: Cassandra or Riak with low consistency levels, DNS, many caches.
- PACELC (Abadi): if Partition, choose A or C; Else, choose Latency or Consistency. It explains why systems that are rarely partitioned still offer weaker modes: to be faster.
- Many databases are tunable per request (Cassandra consistency levels, MongoDB read/write concerns), so label a configuration, not a product.
Interview questions
- Explain the CAP theorem correctly.
- Is a single-node relational database CA?
- What does PACELC add to CAP?
- Is MongoDB CP or AP?
Consistency models
Consistency models describe what reads may return when data is replicated, from linearizable (one copy, real-time order) down to eventual (copies agree some time later).
- Linearizable (strong): every operation appears to happen at one instant between its start and end; once a write completes, every later read sees it. Needed for locks, leader election, uniqueness checks.
- Sequential: all nodes see operations in the same order, and each client's own order is kept, but that order need not match real time.
- Causal: operations that are causally related (a reply after a post) are seen in that order by everyone; unrelated ones may appear in any order. Strongest model that stays available during partitions.
- Eventual: if writes stop, replicas converge. Reads may be stale or out of order in the meantime.
- Session guarantees (client-centric): read-your-writes, monotonic reads (never go back in time), monotonic writes, writes-follow-reads. Cheap to provide with sticky sessions or version tokens.
- Do not confuse with isolation levels (read committed, serializable), which are about concurrent transactions. Strict serializability = serializable + linearizable; Spanner calls it external consistency.
Interview questions
- What is the difference between linearizability and serializability?
- Explain eventual consistency with an example.
- What is causal consistency and why is it useful?
Quorums: N, R and W
With N replicas, writes wait for W acks and reads ask R nodes; if R + W > N, every read overlaps the latest successful write.
- N = replicas per key, W = acks needed for a write, R = replicas consulted per read. Classic: N = 3, W = 2, R = 2.
- R + W > N means read and write sets always share at least one node, so a read can see the latest acknowledged write (pick the newest version).
- Tuning: W = N, R = 1 gives fast reads but writes fail if any replica is down. W = 1, R = N is the opposite. W + W > N also keeps two concurrent writes from both succeeding on disjoint sets.
- Tolerated failures: writes survive N − W down nodes, reads survive N − R. Majority quorums (W = R = ⌊N/2⌋+1) balance both.
- Quorums alone are not linearizable: concurrent writes, LWW with clock skew, failed writes that partly applied, and sloppy quorums (writes to fallback nodes with hinted handoff) can all return stale data.
- Cassandra exposes this as consistency levels:
ONE,QUORUM,LOCAL_QUORUM(majority in the local datacenter),EACH_QUORUM,ALL.
Interview questions
- What does R + W > N mean?
- With N = 3, which settings would you choose for a read-heavy and a write-heavy workload?
- Does a quorum guarantee strong consistency?
Architecture patterns & distributed SQL
CQRS & read models
Separate the write model from one or more read models that are shaped for queries and updated asynchronously from change events.
- CQRS (Command Query Responsibility Segregation): commands go to a normalized write store that enforces invariants; queries go to read models built for each screen or API.
- Read models are projections: a consumer reads change events (outbox, CDC via Debezium, Kafka) and updates denormalised views in Redis, Elasticsearch, a document DB, or another SQL table.
- Benefits: reads and writes scale independently, each read model uses the best store (search, cache, graph), and complex joins happen once at write time instead of on every read.
- Costs: eventual consistency between the write and read side, more moving parts, and you need idempotent projectors and a way to rebuild a view by replaying events.
- Not the same as event sourcing. CQRS is often used with it, but the write side can be a normal relational database.
- A simple first step: a materialized view or a summary table on a replica, before you build a full event pipeline.
Interview questions
- What is CQRS and when should you use it?
- How do you keep read models in sync with the write database?
- CQRS vs read replicas?
NewSQL, sharding middleware & polyglot persistence
Distributed SQL databases and sharding layers give you SQL on many nodes; polyglot persistence means picking the right store per workload.
- Google Spanner: globally distributed, Paxos-replicated splits, TrueTime (GPS and atomic clocks with bounded uncertainty) for external consistency. Offers GoogleSQL and a PostgreSQL dialect.
- CockroachDB: data split into ranges, each replicated by Raft; serializable isolation by default; PostgreSQL wire protocol; hybrid logical clocks instead of special hardware.
- YugabyteDB: DocDB storage with Raft-replicated tablets; YSQL reuses the PostgreSQL query layer, and YCQL is Cassandra-compatible.
- Vitess: sharding layer for MySQL (from YouTube, a CNCF graduated project). VTGate routes queries using vindexes, VTTablet sits next to each MySQL; supports online resharding.
- Citus: PostgreSQL extension; a coordinator distributes tables across workers by a distribution column, with co-located and reference tables. Available as Azure Cosmos DB for PostgreSQL.
- Polyglot persistence: use several stores by need, for example Postgres for orders, Redis for sessions and counters, Elasticsearch for search, a time-series DB for metrics, S3 for blobs, a warehouse for analytics. Each one adds operations and sync work.
Interview questions
- What is NewSQL / distributed SQL?
- How does Spanner provide external consistency?
- Vitess vs Citus?
- What is polyglot persistence and what are its risks?
Scenarios: 1k → 1M QPS and a social app
Scale in stages driven by measurements, and design the data model around the hottest access patterns.
- ~1k QPS: one well-tuned primary with a standby. Indexes, pooling,
pg_stat_statements, backups and a tested failover. - ~10k QPS: add a Redis cache-aside layer for hot reads and read replicas with lag-aware routing; move reports off the primary; scale up the primary.
- ~100k QPS: high cache hit ratio (90%+), CDN for public content, partitioning of big tables, federation of independent domains, async writes through a queue for non-critical paths.
- ~1M QPS: shard the hottest domains by a hashed key into many logical shards (Vitess, Citus or app-level), each shard with replicas; CQRS read models for feeds and search; or adopt distributed SQL.
- Always ask: read/write ratio, data size and growth, latency targets, consistency needs per feature, and regions. 1M QPS of cacheable reads is a very different problem from 1M writes per second.
- Social app: users, posts, follows, likes, feeds. Shard by user_id; posts live with their author; follows stored twice (followers and following); Snowflake ids; hybrid feed fan-out; counters via sharded counters; media in object storage.
Interview questions
- How would you scale a database from 1k to 1M QPS?
- Design the data layer for a Twitter-like social app.
- Your write traffic is growing 3× a year and the primary is at 70% CPU. What is your plan?
- How do you keep a feed fast for a user who follows 2,000 accounts including some celebrities?