Database sharding and replication interview questions

11 database interview questions on sharding, hot keys and replication lag, each with the correct answer and a full explanation.

Sharding and hot keys

Chat app: the main query is load the latest 50 messages of a conversation. Messages are sharded by hash(message_id) and that query fans out to every shard. Which shard key fixes it?

Show answer

Answer

conversation_id

Sharding by the key the hot query filters on puts a conversation on one shard, so the read hits one node.

More shards of message_id makes the fan-out wider. created_at puts all new messages on the newest shard. sender_id still spreads one conversation across every participant's shard.

Source: Hello Interview: Core Concepts for System Design, Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017

Followers are sharded by hash(user_id). A celebrity with 80M followers makes one shard hot. What helps?

Show answer

Answer

Split the hot key across several sub-keys (user_id plus a suffix) and cache its reads

One key always hashes to one shard, however many shards you have. Salting the hot key spreads its writes, and reads gather the sub-keys or come from cache.

Adding shards moves other keys, not the one hot key. Range sharding still keeps a single user_id on one shard. More replicas can help reads but not writes to one key.

Source: Amazon DynamoDB Developer Guide: Using write sharding to distribute workloads evenly, Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017

An events store is range-sharded by created_at. What problem shows up under steady ingest?

Show answer

Answer

All new writes land on the shard holding the newest range

Monotonic keys make the newest range a single write hotspot. Prefix with a well-spread key (for example source_id) and keep time as the second part.

Recent events are on one shard, the opposite of fan-out. Time ranges are exactly what range sharding is good at. Splits happen as ranges grow, not per insert.

Source: Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017, Amazon DynamoDB Developer Guide: Designing partition keys to distribute your workload

Keys are placed with hash(key) mod N. You go from 4 shards to 5. Roughly what fraction of keys must move?

Show answer

Answer

About 80%

A key stays only if hash mod 4 equals hash mod 5, which is true for 4 of every 20 residues, so about 80% move. Consistent hashing moves about 1/5 instead.

About 20% is the consistent hashing figure. 25% confuses it with the old shard count. With mod N the placement of existing keys changes as soon as N changes.

Source: Consistent Hashing and Random Trees, Karger et al., 1997, Dynamo: Amazon's Highly Available Key-value Store, DeCandia et al., 2007

A single Postgres primary: 300 GB, 3,000 queries per second, 35% CPU, p99 creeping up from a few slow queries. The team proposes sharding. What is the best next step?

Show answer

Answer

Fix the slow queries and indexes, and add read replicas or a bigger box before sharding

This load fits a single node well. Sharding adds cross-shard queries, transactions and rebalancing for no gain here, while the actual problem is a few slow queries.

Sharding early pays the complexity cost years ahead. Changing database type does not fix bad queries. Splitting by table breaks joins and does not address the slow queries.

Source: Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017, Hello Interview: Core Concepts for System Design

Users are sharded by user_id. How do you move money between two users on different shards?

Show answer

Answer

Avoid 2PC across shards if you can: it blocks while the coordinator is down and holds locks across the network. Use a saga: debit the sender with an idempotent ledger entry and an outbox event, then credit the receiver idempotently using the transfer id, with a compensating credit if the second step fails permanently.

Keep a transfer row with its state so retries and reconciliation can find stuck transfers. If such transfers are frequent, reconsider the shard key so related accounts live together.

Source: Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017, Pattern: Transactional outbox, Chris Richardson, microservices.io

Replication and lag

Reads go to async replicas. A user saves a new display name, the page reloads, and they see the old name. What is the standard fix?

Show answer

Answer

Read that user's own data from the primary for a short window after they write

The replica has not applied the write yet. Routing the writer's reads to the primary for a while (or until the replica passes the write's log position) gives read-your-writes without moving all reads.

A cache can also hold the old value and is another lag source. More replicas spread load but each still lags. A TTL does nothing for replication lag.

Source: Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017, StackScholar: Database replication and sharding interview questions

Postgres primary with one asynchronous standby. The primary's disk dies and you promote the standby. What can be lost?

Show answer

Answer

Transactions committed on the primary that had not yet reached the standby

With async replication the primary acknowledges commit before the standby has the WAL. Anything in that gap is gone after promotion.

Durable on the primary's disk does not help when that disk is lost. Open transactions are lost in any setup, the surprise is committed ones. The standby has applied WAL continuously, not only up to the base backup.

Source: PostgreSQL Documentation: High Availability, Load Balancing, and Replication, Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017

Postgres with synchronous_standby_names set to a single standby and synchronous_commit = on. That standby goes down. What happens to writes on the primary?

Show answer

Answer

Commits wait and hang until a synchronous standby is back or the setting changes

Each commit waits for the sync standby's confirmation, so with no standby commits block. That is why setups list two or more candidates or use quorum.

Postgres does not fall back to async on its own. Continuing without confirmation would break the guarantee. The primary keeps running, its commits just wait.

Source: PostgreSQL Documentation: Synchronous Replication

A user refreshes and sees a new comment, refreshes again and it is gone, then it reappears. Reads go to random replicas. Which fix targets this specific anomaly?

Show answer

Answer

Pin each user's reads to the same replica

Different replicas lag by different amounts, so random routing can step back in time. Sticking a session to one replica gives monotonic reads.

Queuing writes does not change which replica you read. Synchronous replication slows every commit and, in Postgres, only makes the write visible on the standby with remote_apply. Sharding does not touch read routing.

Source: Designing Data-Intensive Applications, Martin Kleppmann, O'Reilly, 2017

A Postgres primary is at 95% CPU from INSERT and UPDATE traffic, reads are light. Will adding read replicas help?

Show answer

Answer

No, every replica still replays all writes and the primary does all of them

Replicas scale reads. Every write still runs on the one primary. For write load you reduce writes, batch them, scale up, or partition and shard.

Single-leader replicas cannot accept writes. Synchronous replication adds latency to writes. A load balancer cannot send writes to a read-only node.

Source: PostgreSQL Documentation: High Availability, Load Balancing, and Replication, StackScholar: Database replication and sharding interview questions

These questions come from the Database Interview Practice pack in Bertopia.

More database topics

Practise these on your commute