Sub topic 7
Why random keys hurt B-tree indexes
This chapter assumes you know what a primary key and a B-tree index are, and that you have seen UUID v4 as a coordination-free ID. Here we look at what random keys do to insert performance, and why time-ordered IDs reduce the cost.
How a B-tree takes an insert
A B-tree stores keys in sorted order across fixed-size pages, such as 8 KB in PostgreSQL or 16 KB in InnoDB. Each insert walks from the root to the leaf page where the key belongs, then writes the key into that page.
Two things follow from this:
- The database must have that leaf page in memory. If it is not in the buffer pool, the database reads it from disk first.
- If the page is full, the database splits it into two pages and moves about half the keys to the new one.
Sequential keys: one hot page
With an auto-increment key, every new key is larger than all existing keys. Every insert goes to the rightmost leaf page. That page stays in memory, and it fills up completely before the next one is started. Pages are densely packed, and a split only adds an empty page at the right edge.
Random keys: every page is a target
A UUID v4 lands at a uniformly random position in the key order. Each insert touches an arbitrary leaf page, which causes three problems:
- Cache misses. If the index is larger than memory, most inserts need a disk read to load a leaf page that was not recently used.
- Page splits in the middle. Pages fill unevenly. When one overflows, it splits, and both halves are left partly empty. Steady-state fill is often well below that of a sequential index, so the index is larger and fewer pages fit in memory.
- More write volume. Each insert dirties a different page. The database must eventually flush many scattered dirty pages, and write-ahead logging may record full-page images after a checkpoint, which adds more log data.
Keys are also 16 bytes as a UUID, versus 8 for a bigint. In InnoDB, every secondary index entry also stores the primary key, so a wide random key makes every index larger.
Seeing the locality difference
This script estimates how many distinct leaf pages each key style touches. It assumes 200 keys per page and an index of 1,000,000 existing keys. It then inserts 10,000 more.
import random
KEYS_PER_PAGE = 200
EXISTING = 1_000_000
NEW = 10_000
def pages_touched_sequential():
# New keys are larger than every existing key, so they go to the end.
first_page = EXISTING // KEYS_PER_PAGE
last_page = (EXISTING + NEW) // KEYS_PER_PAGE
return last_page - first_page + 1
def pages_touched_random():
# Existing keys are spread evenly; a new key picks a random position.
total_pages = EXISTING // KEYS_PER_PAGE
touched = {random.randrange(total_pages) for _ in range(NEW)}
return len(touched)
print("sequential:", pages_touched_sequential())
print("random: ", pages_touched_random())Sequential inserts touch about 51 pages. Random inserts touch roughly 4,000 of the 5,000 pages. If the index does not fit in memory, that gap becomes disk reads.
When it matters
The cost depends on the size of the index relative to memory.
| Situation | Effect of random keys |
|---|---|
| Index fits in memory | Small. Splits and larger size still cost something, but there is no disk read on each insert. |
| Index much larger than memory | Large. Most inserts wait for a page read. |
| Low insert rate | Usually not noticeable. |
| High insert rate, big table | Often the dominant cost. |
Also note that random keys help in one way: they spread writes across pages, so there is no single hot page under heavy concurrent inserts. Some systems with range-partitioned storage are better off with random keys for exactly this reason. For a single-node B-tree, the locality cost usually wins.
Reducing the cost
A time-ordered ID such as UUID v7 puts a millisecond timestamp in the high bits. Recent IDs sort next to each other, so inserts concentrate on a small set of recent pages, close to the sequential case. The random low bits still keep IDs unique without coordination.
Other options are a bigint surrogate key with the UUID in a separate unique column, or a Snowflake-style ID, which is also time-ordered.
Exercise
A table uses UUID v4 primary keys. Its index is 40 GB and the server has 8 GB of memory for caching. Why do inserts slow down, and what change would reduce the problem?
Show answer
Each insert goes to a random leaf page. Most of the index is not in memory, so most inserts need a disk read, and random splits leave pages partly empty, which makes the index larger still. Switching to a time-ordered ID such as UUID v7 makes new keys land on a small set of recent pages that stay cached.