Secondary Indexes on Partitioned Data
How to look records up by something other than the partition key: local indexes with scatter/gather reads, global indexes with costlier writes, and how real databases keep each in step.
Overview
A partitioned database finds a record quickly when you give it the partition key: hash or look up the key, go to one partition, done. But applications also search by other fields: orders by status, products by color, users by email. An index on a field other than the primary key is a secondary index, and on partitioned data it raises a question with no free answer: which partition holds the index entries?
There are two answers. A local index keeps each partition's index next to that partition's data, so writes are cheap and reads must ask every partition. A global index partitions the index by the indexed value, so reads go to one place and writes may touch several machines. Most real systems offer one or both, and the choice decides your read latency, write cost and how fresh the index is.
The problem
Picture an orders table partitioned by order ID. Partition P1 holds orders 1 to 1M, P2 holds orders 1M to 2M, and P3 holds orders 2M to 3M. Now a query asks for every order with status 'shipped'. The partition key does not help here, because shipped orders are spread across every partition. The database cannot say which partition to ask, so the index for status has to live somewhere, and each of the two answers puts it in a different place.
Key concepts
- Secondary index
- Local (document-partitioned) index
- Global (term-partitioned) index
- Scatter/gather
- Query then fetch
- Asynchronous index maintenance
- Index scoped to the partition key
Interview questions
- Users are sharded by user ID. How do you support login by email?
- How does Elasticsearch run a search across a distributed index?
- Why can a DynamoDB global secondary index return stale results, and what do you do about it?
- Local or global secondary index: how do you decide in an interview?
Sign up free to read the full topic
More DDIA topics
- Relational vs Document Data Models
- Reliability, Scalability, and Maintainability
- Replication Lag and Consistency Anomalies
- Schema Evolution and Backward/Forward Compatibility
- Schema-on-Read vs Schema-on-Write
- Secondary Indexes and Index Trade-offs
- Single-Leader Replication
- SLAs, SLOs, and Percentile Latency
- Unbundling the Database
- What Is a Data-Intensive Application?
- Write Skew and Phantom Reads
- ZooKeeper, etcd, and Distributed Coordination
Start free on Cariara · Coding problems · System design studio