Sharding infrastructure drills¶
How to use this lesson¶
Seven deep dives into specific sharding technologies, each with a hand-drawn diagram or an interactive figure: Cassandra's lightweight transactions, node failure in Cassandra versus CockroachDB, range versus hash hot spots, unbounded partitions, Vitess cutover, a Redis failover oversell, and top-k across shards. It builds on Distributed systems: interview drills, so read topics 4, 5 and 10 there first.
Try each question out loud before opening the answer, and predict what the figure will do before you press a button. You can switch language with the EN / VI buttons in the header.
Contents
Jump to a question.
- B1 · Cassandra LWT and Paxos
- B2 · A node dies mid-write: Cassandra versus CockroachDB
- B3 · Increasing keys on range versus hash sharding
- B4 · The unbounded time-series partition
- B5 · Vitess SwitchTraffic
- B6 · Redis flash sale and failover
- B7 · Top-k across shards
Background in 60 seconds
A quorum is a majority of the replicas; any two quorums overlap. Paxos lets several proposers compete to fix one value: phase 1 prepare/promise, then phase 2 propose/accept, and a later proposer is forced to reuse a value that was already accepted. Raft is Paxos with a stable leader, so each write needs only one network round trip.
B1 · Cassandra LWT and Paxos¶
Two clients race to claim the username bob. With a plain INSERT, both succeed and one write vanishes. With a lightweight transaction, Cassandra runs Paxos on that one partition.
B1 Why does Cassandra have no cross-partition transactions? What does an LWT (Paxos) cost?
Ideas to cover: Cassandra is leaderless with LWW, an LWT runs Paxos for one partition, 4 round trips, contention, do not mix LWT and plain writes.
Cassandra has no leader: the client sends to any node (the coordinator), which writes to the RF replicas and waits for enough acks for the consistency level. Two concurrent writes are resolved by LWW, so "check then write" (claiming the username bob) can leave two people both winning.
An LWT (INSERT ... IF NOT EXISTS) runs Paxos for one partition key in four steps: prepare/promise, read (to evaluate the IF), propose/accept, commit. The cost:
- About 4 round trips versus 1 for a normal write (Paxos v2 since 4.1 trims this in the best case).
- Contention on one partition collapses throughput (ballot retries).
- On a timeout you do not know whether the value was chosen.
- You must not mix LWT and plain writes on the same data.
- The scope is one partition only.
There is no cross-partition transaction because every partition has its own replica set, and making two of them atomic needs 2PC with a durable coordinator, against the goals of no central point and low latency. A logged BATCH only promises that "eventually all of it is applied", with no isolation.
B2 · A node dies mid-write: Cassandra versus CockroachDB¶
The same failure, two very different outcomes. Cassandra tolerates divergence and repairs it later. CockroachDB runs Raft per range, so a write is either committed by a majority or it never happened.
B2 How do CockroachDB and Cassandra differ when a node dies in the middle of a write?
Ideas to cover: Cassandra hinted handoff and repair, a half-done write may surface later; Cockroach Raft per range, committed entries are never lost; AP versus CP.
Cassandra (RF=3, QUORUM writes): if a replica dies mid-write, the other two ack and the write succeeds; the coordinator stores a hint (up to 3 hours by default), and read repair plus nodetool repair converge the copies. If the coordinator dies mid-write the client gets a timeout and does not know whether it was applied; there is no rollback, and a half-written record may surface later when repair spreads it. With CL=ONE even an acknowledged write can be lost.
CockroachDB: data is split into ranges (about 512 MB), each a 3-replica Raft group with a leaseholder. A follower dies: the leader still has a majority, commits normally, and the node catches up from the Raft log when it returns. The leader dies mid-write: committed entries are never lost, uncommitted ones are discarded and the client retries; the range cannot take writes for a few seconds until a new leader is elected. If 2 of 3 replicas die the range is unavailable.
| Cassandra | CockroachDB | |
|---|---|---|
| Model | Leaderless, tolerates divergence then converges | Raft: one order per range |
| A write that fails midway | May look "successful" and surface later | Either committed by a majority or treated as never happened |
| On losing quorum | A low CL can still write (and diverge) | Refuses writes |
| Philosophy | AP | CP |
B3 · Increasing keys on range versus hash sharding¶
Range sharding keeps keys sorted. That is great for scans and terrible when the key only goes up.
B3 Why do increasing keys create a hot spot on range-sharded databases but not on hash-sharded ones?
Ideas to cover: range sharding funnels inserts into the last range, hashing spreads them but loses range scans, the fixes (hash-sharded index, salt, UUID).
Range-sharded: data is sorted by key and cut into contiguous ranges. An increasing key (auto-increment, timestamp, Snowflake ID, UUIDv7) sends every new insert to the last range: one node takes all the writes, adding nodes does not help, and when the range splits the new piece is still at the tail.
Hash-sharded: shard = hash(key) % N, so neighbouring keys land on different shards and writes spread evenly. The price: locality is gone, and a range query becomes a scatter-gather.
Fixes on a range-sharded database (Cockroach, Spanner, HBase): UUID v4 (loses ordering), a hash-sharded index (prefix the key with a bucket column), salted or prefixed buckets for time-series, a bit-reversed sequence (Spanner).
B4 · The unbounded time-series partition¶
In Cassandra the partition key decides which three nodes own the data. If it never changes, one partition grows forever.
B4 A time-series partition with no upper bound grows forever. Explain the problem and the fix.
Ideas to cover: partition key versus clustering key, all rows with one key live in one partition on the same RF nodes, heavy compaction and repair, tombstones, bucketing, TWCS and TTL.
One sensor writing once a second at 100 bytes a row is about 8.6 MB a day, about 3 GB a year, tens of GB after a few years, on exactly 3 nodes. The pain is mostly operations and load balance:
- All writes go to 3 fixed nodes; adding nodes does not help.
- Uneven storage across nodes.
- Compaction rewrites large chunks, and repair and streaming are long and hard to retry.
- Deleting old data produces tombstones that slow reads.
The fix is bucketing: put time in the partition key.
Pick the bucket by write rate (keep partitions at tens of MB up to about 100 MB): once a second means a day or a week; 100 times a second means an hour. If one entity writes too fast, add a shard column (a salt) and read with fan-out N. Pair it with TimeWindowCompactionStrategy plus a TTL so old data is dropped as whole SSTables instead of row by row. The costs: queries across buckets must be merged in the application, and the current bucket is still hot.
B5 · Vitess SwitchTraffic¶
Moving live traffic between shards without losing a write is a small distributed protocol: freeze, catch up, flip, keep a way back.
B5 What does Vitess SwitchTraffic do with in-flight writes, and how do you roll back?
Ideas to cover: VReplication already copied and caught up, block writes on the source, wait for the GTID to catch up, switch routing, reverse stream for ReverseTraffic.
Details follow the VReplication model; behaviour changes between versions.
Before the switch: MoveTables/Reshard has set up VReplication streams from source to target (snapshot copy, then continuous binlog), and VDiff has checked they match.
1. Check preconditions, lock the workflow
2. BLOCK writes on the source (with query buffering, queries to the primary are held for a few seconds)
3. Wait for in-flight transactions on the source to finish (or kill them after a timeout)
4. Record the source's last GTID, wait until VReplication reaches exactly that position
5. Create the REVERSE stream (target back to source)
6. Update routing: vtgate points writes at the target
7. Unlock; buffered queries run on the target
A transaction committed before the block is certainly on the target thanks to step 4. An uncommitted one either finishes or is aborted and the client retries. No committed write is lost; the cost is a short stall or errors.
Rollback: ReverseTraffic runs the same procedure backwards using the reverse stream, so the source stayed up to date and nothing is lost. When you are confident, Complete tears down the reverse stream and cleans up the old tables; after that there is no quick way back.
B6 · Redis flash sale and failover¶
A Redis counter is a great gate for a flash sale and a terrible source of truth, because replication is asynchronous.
B6 Why can a Redis DECR gate still oversell during a failover?
Ideas to cover: asynchronous replication, the master acks before the replica copies, a minority-side master keeps accepting writes, WAIT does not make Redis CP, the DB as the judge.
Stock = 10
master: DECR 9, 8, ... 0, each returning "OK" (10 people pass the gate)
replication to the replica lags by a beat
replica: has only reached "stock = 7"
--- the master dies, the replica is promoted (stock = 7) ---
7 more people pass the gate: 17 people "bought" 10 tickets
The master reported success before the replica had the command. Other causes: AOF everysec loses about a second; during a partition a master on the minority side keeps accepting writes until node-timeout; WAIT only reduces, not removes, the chance of loss; Redlock has no fencing token.
The right approach: Redis is a fast gate, not the source of truth.
1. Redis Lua DECR filters most people at the door
2. DB: UPDATE stock SET n = n - 1 WHERE item = ? AND n > 0 (the final judge)
3. After a Redis failover, reload the stock from the DB
If Redis lets extra people through, the DB refuses them and they only see "sold out". Or use a single writer (a Kafka partition per item), or a consensus DB.
B7 · Top-k across shards¶
Merging per-shard winners does not give the global winner when a key's count is split across shards.
B7 The celebrity problem: if you spread interactions evenly over shards, top-k gets harder. How do you design it?
Ideas to cover: top-k does not decompose from local top-k when keys are split, a separate read model (CQRS), salting hot keys, approximate sketches.
- Shard by interaction (even): every celebrity is split across all shards. A celebrity ranked 5th on every shard can be the global number 1 without being in any shard's local top-1, so you cannot merge local top-k; you need the full counts from every shard (or a multi-round algorithm such as TPUT).
- Shard by celeb_id: exact and cheap top-k (merge N x k candidates), but celebrities are hot keys and concentrate load on one shard.
What works in practice: separate the write path from the top-k read path (CQRS). Write interactions into an evenly sharded store (or salt hot keys celeb#rand(0..M-1)), stream them through Kafka and Flink to count over 1-second windows and write in batches, and serve top-k from a derived read model: a Redis sorted set (ZINCRBY, ZREVRANGE), ClickHouse/Pinot, or an approximation with Count-Min Sketch or HeavyKeeper (RedisBloom TOPK), since sketches merge across shards. Add a read cache and a separate tier for hot celebrities (combined with key splitting).