Partitioning
When replication is not enough for a huge dataset or very high query throughput, the data is split into partitions (shards) spread across nodes. This chapter covers how to split data, how secondary indexes fit in, how to rebalance, and how requests find the right partition.
Key takeaways
- Goal of partitioning: spread data and query load evenly; uneven load is skew, and an overloaded partition is a hot spot.
- Key range partitioning keeps keys sorted, so range scans are cheap, but sequential keys (timestamps) create hot spots.
- Hash partitioning spreads load evenly but destroys key order; Cassandra's compound key hashes only the first column and sorts by the rest.
- Hashing cannot fix a single very hot key (a celebrity); the application must split it, e.g. by appending a random number.
- Secondary indexes: local (document-partitioned) = cheap writes, scatter/gather reads; global (term-partitioned) = single-partition reads, multi-partition and usually asynchronous writes.
- Never rebalance with
hash mod N: changing N moves almost every key. Use a fixed number of partitions, dynamic splitting, or a fixed number per node. - Fully automatic rebalancing plus automatic failure detection can cause cascading failures; a human in the loop is safer.
- Request routing is service discovery: nodes forward, a routing tier forwards, or clients route; cluster metadata often lives in ZooKeeper or spreads by gossip.
Introduction
- A partition is called a shard (MongoDB, Elasticsearch, SolrCloud), region (HBase), tablet (Bigtable), vnode (Cassandra, Riak) or vBucket (Couchbase).
- Usually each record belongs to exactly one partition; each partition is in effect a small database of its own.
- Not the same as a network partition (a fault; see Chapter 8).
- Main reason: scalability. Partitions live on different nodes of a shared-nothing cluster, spreading data over many disks and queries over many processors.
- Single-partition queries scale by adding nodes; large queries can be parallelized across nodes, but that is much harder.
- Pioneered in the 1980s (Teradata, Tandem NonStop SQL), rediscovered by NoSQL and Hadoop warehouses. Fundamentals apply to both transactional and analytic workloads.
Partitioning and Replication
- Partitioning is usually combined with replication: each record is in one partition, but that partition is copied to several nodes for fault tolerance.
- A node can hold many partitions. With leader-follower replication, each partition's leader sits on one node and its followers on others, so a node is leader for some partitions and follower for others.
- Chapter 5's replication ideas apply unchanged per partition; the partitioning scheme is mostly independent of the replication scheme, so the chapter ignores replication.
Partitioning of Key-Value Data
- Aim: each node takes a fair share, so in theory 10 nodes handle 10x the data and 10x the read/write throughput.
- Skew: some partitions get more data or queries. Worst case: all load on one partition, 9 of 10 nodes idle. That partition is a hot spot.
- Random assignment spreads data evenly, but then a read cannot know where an item lives and must query every node.
- Better: assume a key-value model accessed by primary key and derive the partition from the key.
Partitioning by Key Range
- Each partition owns a continuous range of keys, like the volumes of a paper encyclopedia. Known boundaries tell you the partition, and the partition-to-node map tells you the node.
- Ranges need not be even: the book's encyclopedia has volume 1 = A-B but volume 12 = T-Z. Boundaries must adapt to the data; set by an admin or chosen automatically.
- Used by Bigtable, HBase, RethinkDB, and MongoDB before 2.4.
- Keys stay sorted inside a partition (SSTables), so range scans are easy and the key acts as a concatenated index.
- Example: sensor readings keyed by timestamp; fetching a month of readings is one range scan.
- Downside: hot spots from access patterns. With timestamp keys, all of today's writes go to today's partition while others idle.
- Fix: put the sensor name first (key = sensor name + timestamp). Writes spread across sensors, but a time-range query over many sensors needs one range query per sensor.
Partitioning by Hash of Key
- To avoid skew, many stores hash the key. A good hash turns skewed input into a uniform spread (e.g. a 32-bit hash gives values 0 to 232 − 1; similar strings hash far apart).
- Need not be cryptographic: Cassandra and MongoDB use MD5; Voldemort uses Fowler-Noll-Vo.
- Language built-ins may be unsuitable: Java's
Object.hashCode()and Ruby'sObject#hashcan give the same key different hashes in different processes. - Each partition owns a range of hashes. Boundaries may be evenly spaced or chosen pseudorandomly (then sometimes called consistent hashing).
- Cost of hashing: no efficient range queries. Adjacent keys scatter over all partitions.
- MongoDB in hash-sharding mode sends range queries to all partitions. Riak, Couchbase and Voldemort do not support range queries on the primary key.
- Cassandra's compromise: a compound primary key. Only the first column is hashed to pick the partition; the other columns form a concatenated index for sorting in SSTables.
- You cannot range-scan the first column, but with a fixed first column you can range-scan the rest.
- Fits one-to-many data: key
(user_id, update_timestamp)keeps one user's updates on one partition, sorted by time, while users spread across partitions.
Skewed Workloads and Relieving Hot Spots
- Hashing cannot help if all reads and writes hit the same key: identical IDs hash identically.
- Book's example: a celebrity with millions of followers triggers a burst of writes to one key (the user ID, or the ID of the action being commented on).
- Most systems cannot compensate automatically, so the application must reduce skew.
- Technique: add a random number to the start or end of a known hot key. A two-digit random number splits writes over 100 keys on different partitions.
- Costs: reads must fetch all 100 keys and combine them; you need bookkeeping of which keys are split, and should split only the few hot ones.
Partitioning and Secondary Indexes
- Primary-key access maps cleanly to a partition. A secondary index searches for occurrences of a value (all actions by user 123, articles containing "hogwash", red cars) and does not map neatly to partitions.
- Core to relational and document databases and the whole point of Solr and Elasticsearch. HBase and Voldemort avoided them for complexity; Riak started adding them.
- Two approaches: document-based and term-based partitioning.
- Hand-rolling a value-to-ID index in a key-value store is risky: races and partial write failures easily put it out of sync with the data.
Partitioning Secondary Indexes by Document
- Example: a used-car site partitioned by document ID (IDs 0-499 in partition 0, 500-999 in partition 1), with secondary indexes on
colorandmake. - Each partition keeps its own index covering only its own documents (adding a red car adds its ID to that partition's
color:redentry). Called a local index. - Writes touch only the partition holding the document.
- Reads: red cars can be in any partition, so a query goes to all partitions and results are combined: scatter/gather.
- Scatter/gather is expensive and, even in parallel, prone to tail latency amplification.
- Still widely used: MongoDB, Riak, Cassandra, Elasticsearch, SolrCloud, VoltDB.
- Vendors advise designing so index queries hit one partition, which is often impossible, especially with several indexes in one query (color and make together).
Partitioning Secondary Indexes by Term
- Instead build a global index over all partitions. It cannot sit on one node (bottleneck), so it is itself partitioned, but differently from the primary key.
- Book's example:
color:redlists red cars from every partition; colors a-r live in index partition 0, s-z in partition 1; the make index splits between f and h. - Called term-partitioned: the term (e.g.
color:red) picks the index partition. "Term" comes from full-text indexes, where terms are a document's words. - Partition by the term itself (supports range scans, e.g. asking price) or by its hash (more even load).
- Reads are efficient: one request to the partition holding the term, no scatter/gather.
- Writes are slower and complex: one document write may touch several index partitions on different nodes.
- Keeping the index always current needs a distributed transaction across those partitions, which not all databases support (Chapters 7, 9).
- So global index updates are often asynchronous: a read right after a write may miss it. DynamoDB says its global secondary indexes update within a fraction of a second normally, longer during infrastructure faults.
- Also used by Riak search and the Oracle data warehouse (which offers local or global). More in Chapter 12.
| Document-partitioned (local) | Term-partitioned (global) | |
|---|---|---|
| Index lives | With the documents it covers | Partitioned by the indexed term |
| Write | One partition | Possibly many index partitions |
| Read | Scatter/gather over all partitions | One partition per term |
| Freshness | Updated with the write | Often asynchronous |
| Used by | MongoDB, Riak, Cassandra, Elasticsearch, SolrCloud, VoltDB | DynamoDB GSIs, Riak search, Oracle DW |
Rebalancing Partitions
- Things change: throughput grows (more CPUs), data grows (more disks and RAM), machines fail (others take over). Each calls for moving data and requests between nodes: rebalancing.
- Minimum requirements: load is shared fairly afterward; the database keeps serving reads and writes during it; no more data moves than necessary.
Strategies for Rebalancing
How not to do it: hash mod N. Why assign hash ranges instead of hash(key) mod N? Because when N changes, most keys move.
- Book's example: hash(key) = 123456 sits on node 6 with 10 nodes, node 3 with 11, node 0 with 12. Such frequent moves make rebalancing far too expensive.
Fixed number of partitions. Create many more partitions than nodes, several per node (e.g. 10 nodes, 1,000 partitions, about 100 each).
- A new node steals a few partitions from every existing node; removal reverses this.
- Only whole partitions move. Key-to-partition mapping and partition count never change, only partition-to-node assignment.
- Transfer takes time, so the old assignment serves reads and writes during the move.
- Mismatched hardware: give stronger nodes more partitions.
- Used by Riak, Elasticsearch, Couchbase, Voldemort.
- The count is usually set at setup and never changed (splitting is often not implemented), so it caps the number of nodes. Choose it high enough for growth, but each partition has overhead.
- Hard when dataset size varies: partition size grows with total data. Too big = expensive rebalancing and recovery; too small = too much overhead.
Dynamic partitioning. Fixed boundaries suit key ranges badly: wrong boundaries could put all data in one partition, and fixing them by hand is tedious.
- HBase and RethinkDB split a partition when it exceeds a configured size (HBase default 10 GB), about half on each side; small partitions can merge with a neighbor. Similar to a B-tree's top level.
- Nodes hold many partitions; after a split, one half can move to another node (HBase moves files via HDFS).
- Advantage: partition count adapts to data volume. Small data, few partitions, low overhead; huge data, each partition capped at a maximum.
- Caveat: an empty database starts with one partition, so one node takes all writes until the first split. Pre-splitting (HBase, MongoDB) configures initial partitions, but for key ranges you must know the key distribution in advance.
- Works with hash partitioning too: MongoDB since 2.4 splits dynamically in both modes.
Partitioning proportionally to nodes. Dynamic: partition count tracks dataset size. Fixed: partition size tracks dataset size. Both are independent of node count.
- Cassandra and Ketama instead use a fixed number of partitions per node. Partitions grow with data, then shrink when nodes are added; since more data usually means more nodes, size stays fairly stable.
- A joining node randomly picks a fixed number of existing partitions, splits them, and takes one half of each.
- Randomness can split unfairly, but it averages out over many partitions (Cassandra default 256 per node). Cassandra 3.0 added an algorithm that avoids unfair splits.
- Random boundaries require hash partitioning. This is closest to Karger's original consistent hashing; newer hash functions get a similar effect with less metadata.
| Strategy | Partition count | Partition size | Used by |
|---|---|---|---|
| Fixed number | Fixed at setup | Grows with dataset | Riak, Elasticsearch, Couchbase, Voldemort |
| Dynamic | Grows with dataset | Between min and max | HBase, RethinkDB, MongoDB |
| Proportional to nodes | Fixed per node | Fairly stable | Cassandra, Ketama |
Operations: Automatic or Manual Rebalancing
- A gradient from fully automatic (system moves partitions itself) to fully manual (admin configures assignment). Couchbase, Riak and Voldemort suggest an assignment automatically but need an admin to commit it.
- Automatic is convenient but unpredictable. Rebalancing reroutes requests and moves lots of data; done carelessly it overloads the network or nodes and hurts other requests.
- Danger with automatic failure detection: an overloaded, slow node is declared dead; the cluster moves load away from it, adding load to it, other nodes and the network, risking a cascading failure.
- A human in the loop is slower but prevents operational surprises.
Request Routing
- How does a client know which node (IP and port) holds key "foo", given that assignments change during rebalancing? This is service discovery, a general problem for any highly available networked software; many companies have open-sourced in-house tools.
- Three approaches (Figure 6-7):
- Client contacts any node (e.g. round-robin load balancer); that node handles it or forwards to the owner and relays the reply.
- A routing tier receives all requests and forwards them; it handles none itself, acting as a partition-aware load balancer.
- Partition-aware clients connect straight to the right node.
- Key problem: how does whoever routes learn about assignment changes? All participants must agree, or requests go to the wrong node. Consensus protocols exist but are hard to implement (Chapter 9).
- Many systems keep cluster metadata in a coordination service such as ZooKeeper: nodes register, ZooKeeper holds the authoritative partition-to-node map, and the routing tier or clients subscribe and get notified of changes.
- ZooKeeper users: LinkedIn's Espresso (via Helix, with a routing tier), HBase, SolrCloud, Kafka. MongoDB is similar but uses its own config servers with
mongosdaemons as the routing tier. - Cassandra and Riak use a gossip protocol among nodes; any node accepts a request and forwards it (approach 1). More complexity in the nodes, no external coordination dependency.
- Couchbase does not rebalance automatically, simplifying things; it usually uses a routing tier,
moxi, that learns changes from cluster nodes. - Clients still need IP addresses of the routing tier or nodes; these change slowly, so DNS is usually enough.
Parallel Query Execution
- So far: single-key reads and writes, plus scatter/gather for local indexes. That is about what most NoSQL stores support.
- Massively parallel processing (MPP) relational databases, often for analytics, support far richer queries (joins, filters, grouping, aggregation).
- The MPP optimizer breaks a query into stages and partitions, many run in parallel on different nodes. Large scans benefit most.
- A specialized, commercially important topic; techniques covered in Chapter 10.
Summary
- Partitioning is needed when data is too large to store and process on one machine. Goal: spread data and query load evenly and avoid hot spots, via a scheme suited to the data plus rebalancing as nodes come and go.
- Key range partitioning: sorted keys, each partition owns min to max. Efficient range queries; hot-spot risk when accesses cluster in key order. Usually rebalanced dynamically by splitting a range in two when it grows too big.
- Hash partitioning: each partition owns a range of hashes. Loses key order (range queries inefficient) but may spread load more evenly. Commonly a fixed number of partitions created up front, several per node, whole partitions moved on node changes; dynamic partitioning also works.
- Hybrid: a compound key, one part picking the partition and another the sort order.
- Secondary indexes must be partitioned too. Document-partitioned (local): stored with the primary data; one-partition writes, scatter/gather reads. Term-partitioned (global): partitioned by indexed value; writes update several index partitions, reads hit one.
- Routing ranges from partition-aware load balancing to sophisticated parallel query engines.
- Partitions operate mostly independently, which is what lets the database scale. Writes spanning several partitions are hard to reason about (what if one succeeds and another fails?); later chapters address this.
Condensed from Designing Data-Intensive Applications by Martin Kleppmann (O'Reilly, 2017). Parts I-III (complete book), 12 chapters.