Unit 1 of 14 · about 2 hours · explain

Range and hash partitioning

Partitioning decides which machine answers each key. The Systems unit on partitioning, hot keys, rebalancing and stale writers taught range and hash placement, modulo movement and fixed shards. Here the new work is choosing a scheme from two contrasting access patterns and writing the decision down, including compound keys and the growth limit of a fixed shard count.

You'll be able to

  • Choose range, hash or compound-key partitioning for a stated access pattern from scan fan-out and write spread.
  • Explain when a compound key keeps a range scan on one shard under hash partitioning.
  • State the fixed-shard-count trade-off between cheap moves, split cost and the growth limit.

Covers

Range partitioningHash partitioning
1

Read

In this order, only the parts listed

0 of 3 done

  1. Sharding by key range and by hash of keyDDIA 2e - Chapters 7 and 8 Sharding and Transactions

    Chapter 7, Sharding of Key-Value Data (pp. 255-262): Sharding by Key Range, Rebalancing key-range sharded data, Sharding by Hash of Key with Figures 7-2 and 7-3, plus Fixed number of shards and Sharding by hash range

    Skim the range and modulo pages you read for the Systems unit; read Sharding by hash range and its compound-key paragraph closely. Stop before Consistent hashing (p. 263); the next unit derives it.

  2. Sharding strategies and choosing a partition keyHLD Handbook - Sharding, Distributed Transactions and Idempotency

    Sharding strategies (range, hash, consistent-hash, directory, geographic) and Choosing partition key: high-cardinality, stable keys that appear in queries

  3. Why one database stops being enoughAlgoMaster System Design - Selected Sharding and Transaction Problems

    The opening: vertical scaling limits, read replicas, and why data is divided across servers

    Use as vocabulary for the sharding decision. The routing math comes from DDIA and the drill below.

2

Focus on

  • Range partitioning keeps contiguous keys together, so a scan visits only the shards whose ranges overlap it. Sequential keys such as timestamps can concentrate writes on the newest shard.
  • Hashing the partition key spreads writes but loses its order, so a range over that key visits every shard. A compound key keeps a range over its later columns on one shard when the query fixes the partition key (DDIA p. 261).
  • Mod-N placement couples every key to the node count: adding one node reassigns most keys, as Figure 7-3 shows.
  • Fixed shard counts decouple keys from nodes so only whole shards move, but no cluster can use more nodes than shards, and a wrong initial count forces expensive resharding.
Common mistakes · 3
  • Hashing the key does not remove skew. It removes correlation between key order and placement; a hot key stays hot on whichever shard owns it.
  • More shards are not free. Each shard adds metadata and recovery work; DDIA warns the size must be just right, neither too big nor too small.
  • Assuming every range query fans out under hashing. Only a range over the hashed key does; a compound key keeps a range over later columns on one shard when the query fixes the partition key.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write a decision table for two access patterns: sensor readings written every second and read as one sensor's last hour, and user profiles read and written by user ID. For range by timestamp, hash of the whole key and a compound key (hash of the sensor ID, then timestamp), give the shards one write touches, the shards one sensor's hour scan touches, and what a split costs. Then route keys 1 to 8 with key % 3 to get loads [2, 3, 3].
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Sensor writes keyed by timestamp land on one shard under range partitioning. Why, and what key change spreads them?Answer

    Time-contiguous keys fall in one range, so the current shard takes all writes. Prefix each timestamp with the sensor ID so ordering is by sensor then time; each sensor then needs its own range scan afterward.

  2. 2.Keys 1 to 8 route by key % 3. What are the shard loads?Answer

    Shard 0 holds 3 and 6, shard 1 holds 1, 4 and 7, shard 2 holds 2, 5 and 8, so [2, 3, 3].

  3. 3.A 10-node cluster holds 1,000 fixed shards and adds an 11th node. What moves?Answer

    Only whole shards move from old nodes to the new one until shares even out. No key changes shard; only the shard-to-node assignment changes.

  4. 4.Why can a cluster hold fewer nodes than shards but never usefully more?Answer

    Each node serves whole shards, so a node with no shard serves nothing. Splitting shards to make room is the expensive reshard operation.

5

Practice

  • AlgoMaster Calculate Hash Shard Load

    Implement shardLoads(keys, numShards) routing each key to key % numShards. Example 1 ([1, 2, 3, 4, 5, 6, 7, 8], 3) gives [2, 3, 3]; Example 2 ([10, 20, 30, 40], 4) gives [2, 0, 2, 0]

    This drills mod-N routing only. Rings, movement and skew arrive in later units.

You're done when

You fill the decision table for both access patterns without notes and can state the growth limit of your fixed shard count.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 14 more in the section
  • DDIA 2e - Chapters 7 and 8 Sharding and TransactionsMartin Kleppmann and Chris Riccomini · primary

    Read both chapters completely. Build a decision table connecting access pattern, partition key, isolation, atomicity, failure and recovery before implementing either the partition map or workflow.

  • HLD Handbook - Sharding, Distributed Transactions and IdempotencyHLD Handbook · required

    Read Part 2 database sharding, then Part 3 distributed transactions, idempotency and consistent hashing. Use Part 5 event patterns only for the chosen workflow design.

  • AlgoMaster System Design - Selected Sharding and Transaction ProblemsAlgoMaster · support

    Use the sharding, consistent hashing, ACID, saga, idempotency and outbox lessons as vocabulary, and the problems Calculate Hash Shard Load, Count Keys Moved by Resharding, Merge Cross-Shard Top-K Results, Analyze Transaction Serializability, Build a Saga Compensation Order and Consume Outbox Events Idempotently and in Order as drills. The capstone must supply real persistence, fault history and load evidence.

Also in this section

  • A Critique of ANSI SQL Isolation Levels (Berenson et al., 1995)arXiv (Microsoft Research report) · required

    Read the phenomena P0 to P3, the snapshot-isolation anomalies A5A (read skew) and A5B (write skew) and the summary tables. Cite these definitions, not the SQL-92 prose they correct.

  • Weak Consistency: A Generalized Theory and Optimistic Implementations for Distributed Transactions (Adya, 1999)MIT LCS · support

    Read the dependency-graph definitions of G0, G1 (a, b and c) and G2 and the levels PL-1 to PL-3 they define. They are the anomalies Elle checks on recorded histories.

  • Serializable Snapshot Isolation in PostgreSQL (Ports and Grittner, 2012)arXiv · support

    Read the dangerous-structure rule (two adjacent read-write antidependencies) from Cahill et al. and how PostgreSQL implements and limits it. False positives abort transactions, so measure abort rates.

  • Sagas (Garcia-Molina and Salem, 1987)Cornell course copy · required

    Read the whole paper: a saga is a sequence of transactions with compensating transactions, and compensation is application-defined. Name the steps whose effects cannot be compensated.

  • Spanner: Google's Globally-Distributed Database (Corbett et al., 2012)Google (author copy) · support

    Read TrueTime and the concurrency-control section (timestamps, commit wait, read-write and read-only transactions, two-phase commit over Paxos groups). TrueTime needs clock hardware, so emulate bounded uncertainty in simulation.

  • Large-scale Incremental Processing Using Distributed Transactions and Notifications (Peng and Dabek, 2010)USENIX OSDI · support

    Read the snapshot-isolation transaction protocol over Bigtable (primary lock, timestamp oracle) and notifications. Snapshot isolation still admits write skew.

  • CMU 15-445 - Concurrency Control, Logging and RecoveryCarnegie Mellon Database Group · required

    Follow Fall 2025 lectures 17 to 22, the transactions homework and the concurrency-control project where available. Reproduce lost update and write skew outside the project before claiming an isolation level.

  • PostgreSQL 18 Documentation - Transaction Isolation and Explicit LockingPostgreSQL Global Development Group · required

    Read Section 13.2 (Read Committed, Repeatable Read and Serializable with its serialization failures) and 13.3 (row locks and deadlocks). Reproduce write skew under Repeatable Read and its rejection under Serializable in the postgres:18 image.

  • The Internals of PostgreSQL - Concurrency ControlHironobu Suzuki · support

    Read Chapter 5 Sections 5.5 to 5.9 (snapshots, visibility rules, preventing lost updates and serializable snapshot isolation) to see one real engine implement the anomalies and isolation levels you reproduce. Note the date you read it.

  • MIT 6.5840 - Distributed Transactions and Lab 5 Sharded KVMIT PDOS · required

    Use lecture 11 and Lab 5 for coordinator failure, shard ownership and migration. Treat the lab as the integrated advanced path; a smaller deterministic partition map is sufficient for the compulsory gate if time is constrained.

  • DSLabs - Lab 4 Sharded Store and TransactionsUniversity of Washington (Ellis Michael) · support

    Labs are Java 21 message-passing state machines tested on an emulated network and by model-checking search tests that print a minimal violating trace; run them with the run-tests.py script and its --lab and --part options. Lab 4 adds a shard master, shard movement and multi-key transactions across groups with two-phase commit and locking (Part 3): use it for the commit protocol across groups, which MIT Lab 5 does not exercise.

  • Gossip Glomers - Totally Available TransactionsFly.io and Jepsen · support

    Each challenge runs locally under Maelstrom (v0.2.4; the pages were tested on 0.2.3) with its checker and, where the page says so, the partition nemesis; keep the run directory as the history. Do 6a to 6c (read-uncommitted, then read-committed transactions under partition). The 6b page says the checker cannot detect G0 anomalies, so a pass is weaker than its label.

  • Building Distributed Systems - The Sharder and The CoordinatorBuild Distributed Systems · optional

    Only the first three tasks of each track are free: in The Sharder, a shard controller, consistent hashing and configuration change; in The Coordinator, two-phase commit, coordinator failure and three-phase commit. Tasks are graded in the browser after login, so treat a pass as a drill and keep your local harness as the evidence.

  • Replicated Log and Stream Processor - Partition and Workflow SliceRoadmap-Final · support

    Add partition routing, ownership epochs, rebalance, one cross-partition invariant and a durable transaction or saga path. Inject stale routes, coordinator death, duplicate steps and failed compensation.