Shard keys, hot spots, index tables and materialized views
Choose between range, hash and directory partitioning, compare three shard keys on one seeded workload, find and fix hot spots, and serve the queries the key does not fit with scatter-gather, index tables or materialized views.
Contentsand lesson path
On this page
- Why it matters
- Range, hash and directory partitioning
- Three keys on one workload
- Choosing a key and handling hot spots
- Serving queries that do not match the key
- Check your understanding
- Apply it
- Review prompt
Lessons of Database Replication & Sharding
- Leaders, read replicas, sync versus async replication and failover Concept · 20 min
- Multi-leader and leaderless quorums Concept · 20 min
- Observing replication lag with a read replica Lab · 25 min
- Shard keys, hot spots, index tables and materialized views Concept · 30 min
- Sharding a social graph table and planning a rebalance Worked example · 30 min
- Replication and sharding check Knowledge check · 8 questions
What you will learn
- Choose a shard key and strategy (range, hash, directory) that avoids hot partitions and serves the main queries.
- Plan rebalancing and resharding, and serve cross-shard queries with index tables or materialized views while estimating the cost of cross-shard joins and transactions.
01. Why it matters
Replicas add read capacity, but every replica still stores the whole data set and replays every write. When a table outgrows what one server can hold, back up and restore in reasonable time (a 5 TB table, say), or when writes outgrow one leader, you split the rows across several databases. Each piece is a shard, also called a partition, and each row lives on exactly one shard, usually with its own replicas. The shard key is the column, or columns, that decides which shard a row belongs to.
The shard key is hard to change later, because changing it means moving every row while the system keeps running. It decides which queries stay cheap (one shard), which become expensive (many shards), and whether load spreads evenly or piles onto one machine.
02. Range, hash and directory partitioning
There are three ways to map a key to a shard:
- Range partitioning gives each shard a contiguous range of keys. Neighbouring keys sit together, so range scans such as "orders from 1 to 7 May" read one or two shards. The risk is uneven load: if the key grows with time, every new row lands in the last range. Ranges are split when they grow too big.
- Hash partitioning runs the key through a hash function and uses the result to pick a shard. A good hash scatters keys evenly, so data and load spread well when there are many distinct keys. The price is order: neighbouring keys land on different shards, so a range scan must ask every shard. Avoid
hash(key) mod Nas the final mapping, because changing N moves most keys; real systems hash into fixed logical partitions or use consistent hashing. - Directory partitioning, also called lookup partitioning, keeps an explicit map from each key, or each group of keys such as a tenant, to a shard. It is the most flexible: you can give a large customer its own shard, keep a country's data in its own region, or move one key alone. The costs are an extra lookup on every request, so routers cache the map, and a map that must stay available and correct.
These combine well: many systems hash keys into a fixed set of logical partitions, say 4,096, and a small directory assigns partitions to shards, as in lesson 05.
03. Three keys on one workload
The script generates 300,000 orders from 20,000 customers over one year; a few business customers order far more often than everyone else. It places the orders on 8 shards with three candidate keys and prints: rows on the largest shard divided by the average, the share of today's orders on the busiest shard, the average number of shards holding one customer's orders, and the number of shards holding the last week. The seed is fixed, so every run prints the same numbers.
"""Compare three shard keys for one orders table. Python 3.12, standard library only."""
import hashlib
import random
from collections import Counter, defaultdict
SHARDS, DAYS, CUSTOMERS, ORDERS = 8, 365, 20_000, 300_000
rng = random.Random(42)
def h(key: int) -> int:
"""A stable hash (Python's own hash() of an int is the int itself)."""
return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest())
# A long tail: a few business customers order far more often than everyone else.
weights = [1 / rank**0.9 for rank in range(1, CUSTOMERS + 1)]
rng.shuffle(weights)
buyers = rng.choices(range(1, CUSTOMERS + 1), weights, k=ORDERS)
days = sorted(rng.randrange(DAYS) for _ in range(ORDERS)) # ids grow with time
orders = [(i + 1, buyers[i], days[i]) for i in range(ORDERS)]
STRATEGIES = {
'range(created_at)': lambda oid, cust, day: day * SHARDS // DAYS,
'hash(order_id)': lambda oid, cust, day: h(oid) % SHARDS,
'hash(customer_id)': lambda oid, cust, day: h(cust) % SHARDS,
}
print(f'{ORDERS:,} orders, {SHARDS} shards')
print('strategy rows max/avg today on busiest shards/customer shards/week')
for name, place in STRATEGIES.items():
rows, today = Counter(), Counter()
shards_of, week = defaultdict(set), set()
for oid, cust, day in orders:
shard = place(oid, cust, day)
rows[shard] += 1
today[shard] += day == DAYS - 1
shards_of[cust].add(shard)
if day >= DAYS - 7:
week.add(shard)
skew = max(rows.values()) / (ORDERS / SHARDS)
hot = max(today.values()) / sum(today.values())
fan = sum(len(s) for s in shards_of.values()) / len(shards_of)
print(f'{name:<18} {skew:>13.2f} {hot:>17.0%} {fan:>16.1f} {len(week):>12}')
top, n = Counter(buyers).most_common(1)[0]
print(f'largest customer: id {top}, {n:,} orders ({n / ORDERS:.1%} of all)')300,000 orders, 8 shards
strategy rows max/avg today on busiest shards/customer shards/week
range(created_at) 1.02 100% 4.1 1
hash(order_id) 1.01 14% 4.1 8
hash(customer_id) 1.47 17% 1.0 8
largest customer: id 6609, 17,196 orders (5.7% of all)range(created_at)keeps the last week on one shard, which suits a weekly report, but all of today's writes hit that one shard.hash(order_id)spreads rows and writes evenly, but one customer's history is scattered over about four shards, and the weekly report must ask all eight.hash(customer_id)puts each customer's history on one shard, so "show my orders" touches one shard. But the largest shard holds 1.47 times the average, because the largest customer alone places 5.7% of all orders, and this key cannot split one customer.
No key wins every column: choose the one that serves your most frequent and important queries, and serve the rest another way.
04. Choosing a key and handling hot spots
A good shard key usually has these properties:
- The main queries filter on it, so they touch one shard. List the top queries by rate and importance first.
- High cardinality: many more distinct values than shards. A
countrykey with 200 values, one of them huge, cannot fill 64 shards evenly. - Even load, not just even size. Rows can be balanced while requests are not.
- It never changes. If a row's key changes, the row must move to another shard.
- It keeps a transaction's rows together, such as a customer and their orders, so one local transaction covers them.
A hot spot (or hot partition) is a shard with far more load than the others. It has two causes. Data skew means some keys own far more rows, like the 5.7% customer above. Load skew means some keys receive far more requests, like a celebrity's profile or a flash-sale product. Measure requests per partition and per key, not only rows per shard. The fixes depend on the cause:
- Split the key. Add a small suffix, a bucket from 0 to 15 for example, so that one key's rows spread over 16 partitions. Writes spread out, but a read of that key must ask all 16 buckets. Split only the keys that need it, and record which.
- Isolate it. With a directory, give a very large tenant its own shard.
- Absorb reads elsewhere. A cache in front of a read-hot key often helps more than any partitioning change; see Surviving stampedes and hot keys.
- Change the key when a sequential key concentrates writes, for example by hashing it, at the cost of range scans.
05. Serving queries that do not match the key
Orders keyed by customer still need "find the order with tracking number X" and "revenue per seller today". Four ways serve such queries:
- Scatter-gather. The router sends the query to every shard and merges the answers. Its cost grows with the shard count: 300 lookups per second on 16 shards become 4,800 shard queries per second, and each answer waits for the slowest shard. Sorting, limits and totals need care in the merge.
- Local secondary indexes. Each shard indexes its own rows, for example on tracking number. Writes stay local, but a lookup is still a scatter-gather, only cheaper per shard.
- Global secondary indexes, or index tables. A separate table, sharded by the indexed value, maps each value to the shard key:
tracking_number → customer_id. A lookup reads one index partition, then one base shard. Every write to the base table now also writes to the index, usually on another shard. Unless both are updated in one distributed transaction, the index is maintained asynchronously from the change stream (logical decoding), so it can briefly miss new rows or point to old ones. Make the updater idempotent and apply only newer versions. - Materialized views. A precomputed result stored in the shape a query needs, such as revenue per seller per day, sharded by seller. Reads become single-shard lookups. The view lags its sources by the refresh interval or pipeline delay, costs storage and compute, and must be rebuildable from its sources.
Choose by how often the query runs and how fresh its answer must be.
Joins and transactions across shards are possible but costly, and the cost depends on the engine. Vitess, for example, joins across shards by querying one side and then looking up matching rows on the others; an application can do the same. Such joins add round trips and network transfer, so designs avoid frequent ones: shard tables that are joined together by the same key (customers and orders both by customer_id), store a denormalised copy of the fields a page needs, or copy small, slowly changing tables such as exchange rates to every shard. Unless the engine updates every copy in one distributed transaction, the copies change one shard at a time, so give each version an id or a validity time, and let a query that spans shards use one version.
A transaction that must change rows on two shards atomically needs an atomic commit protocol such as two-phase commit. The alternative, a saga of local transactions with compensating steps, gives up atomicity and isolation in exchange; see Consensus and distributed transactions and Distributed data patterns. To estimate the cost, count the round trips and forced log flushes that a commit waits for in sequence. With assumed numbers, to be replaced by your own measurements:
single shard 1 round trip + 1 flush ≈ 0.6–4 ms
two-phase commit prepare: 1 round trip + 1 flush on each shard, in parallel
over two shards decision: 1 flush in the coordinator's log
commit: 1 round trip + 1 flush on each shard
total: 2 round trips + 3 flushes ≈ 1.3–10 msThe extra milliseconds are rarely the main cost. The rows stay locked across both rounds, about twice as long in this estimate, so requests for hot rows queue longer; and if the coordinator fails after the prepare, the shards keep those locks until it recovers.
06. Check your understanding
07. Apply it
Start the second half of this skill's practice task, a shard-key proposal for a 5 TB table you know (lesson 05 works through a full one):
- List the five most frequent queries with their rates, and mark the ones that must be single-shard.
- Propose a key and a strategy and say what the other candidates would cost; adapt
shard_keys.pyto your data. - Name the hottest key you expect and how you would handle it.
- Serve each off-key query by scatter-gather, a local index, an index table or a materialized view, with its write cost and staleness.
08. Review prompt
Without looking back, explain: what range, hash and directory partitioning make cheap and expensive; the properties of a good shard key; data skew versus load skew; when to use scatter-gather, local indexes, index tables and materialized views; and how to estimate a cross-shard commit.
References
- Sharding pattern (Azure Architecture Center)
- Index Table pattern (Azure Architecture Center)
- Materialized View pattern (Azure Architecture Center)
- Designing Data-Intensive Applications, chapters on replication and partitioning
- Vitess documentation
- Vitess documentation: analysing a statement with VEXPLAIN (a join planned across keyspaces)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.