Sub topic 7
Why random keys hurt B-tree indexes
This chapter assumes you know what a primary key and an index are, and that you have a rough picture of a balanced tree. It also assumes you have read the earlier chapters on random IDs and UUID v4. Random IDs need no coordination, but they have a cost inside the database. Here you will see where that cost comes from, how to measure it, and when it matters.
How a B-tree stores keys
Most relational databases index a primary key with a B-tree (strictly a B+tree). The tree has three kinds of nodes:
- Internal pages hold separator keys and pointers to child pages.
- Leaf pages hold the keys in sorted order, along with a row pointer or the row itself.
- Every page has a fixed size. PostgreSQL uses 8 KB and InnoDB uses 16 KB by default.
To insert a key, the database walks from the root to the one leaf page whose key range contains the new key. It adds the key to that leaf, shifting entries to keep them sorted. If the leaf has no room, the database does a page split. It allocates a new page, moves about half the entries into it, and adds a new separator key to the parent.
Two facts drive everything below:
- The key's value decides which leaf page is modified.
- A modified page must be in memory (the buffer pool) and later written to disk.
Sequential keys: a hot right edge
With an auto-increment ID or a time-ordered ID, each new key is larger than all existing keys. Every insert goes to the same place, the rightmost leaf.
- That page is almost certainly in memory, because the last insert just used it.
- When it fills, the database starts a new page on the right. Most engines detect this append pattern and leave the old page nearly full instead of half empty.
- The set of pages being written at any moment is tiny: the rightmost leaf and its ancestors.
- Old pages are no longer touched, so they are written once and can leave the cache.
Random keys: writes everywhere
With UUID v4, each new key lands at a uniformly random position in the key space. That has four consequences.
- Cache misses. The target leaf is chosen at random from all leaves. If the index is larger than the buffer pool, most inserts need a disk read before they can write.
- Splits in the middle. A random insert hits a full page often enough that splits are frequent. Each split moves half a page and touches the parent.
- Low fill factor. Pages that split in half start at about 50% full and then fill gradually. Across a whole random-insert workload, average leaf utilization settles near 69% (ln 2). Sequential inserts get close to 100%. The same rows need roughly 40% more leaf pages, so the index is bigger, scans read more pages, and the cache holds less useful data.
- More write volume. Many different dirty pages must be flushed to disk. PostgreSQL also writes a full copy of a page into the write-ahead log the first time that page changes after a checkpoint. Random inserts touch many distinct pages, so they trigger many more of these full-page images than sequential inserts do.
The diagram shows where inserts land in each case.
Measuring it with a simulation
The script below models leaf pages as sorted lists with a capacity of 64 keys. It inserts the same number of keys in sequential order and in random order, then reports page count, fill, splits, and how many distinct leaves were touched during the last 5,000 inserts. That last number approximates the working set the cache has to hold.
import bisect
import random
CAPACITY = 64
N = 50_000
WINDOW = 5_000
def simulate(keys):
mins = [-1] # lower bound of each leaf; keys are non-negative
leaves = [[]]
touched = [] # id of the leaf modified by each insert
splits = 0
for key in keys:
i = bisect.bisect_right(mins, key) - 1
leaf = leaves[i]
bisect.insort(leaf, key)
touched.append(id(leaf))
if len(leaf) > CAPACITY:
splits += 1
if i == len(leaves) - 1 and leaf[-1] == key:
cut = len(leaf) - 1 # append pattern: keep the old page full
else:
cut = len(leaf) // 2 # ordinary split: half and half
right = leaf[cut:]
del leaf[cut:]
leaves.insert(i + 1, right)
mins.insert(i + 1, right[0])
fill = len(keys) / (len(leaves) * CAPACITY)
recent_pages = len(set(touched[-WINDOW:]))
return len(leaves), fill, splits, recent_pages
random.seed(1)
sequential = list(range(N))
shuffled = random.sample(range(10**9), N)
for name, keys in [("sequential", sequential), ("random", shuffled)]:
pages, fill, splits, recent = simulate(keys)
print(f"{name:10} pages={pages:5} fill={fill:5.1%} "
f"splits={splits:5} distinct pages in last {WINDOW} inserts={recent}")When you run it, expect these approximate results:
- The sequential run ends with fill close to 100% and a recent working set of about 80 pages (5,000 inserts divided by 64 keys per page).
- The random run ends with fill near 70% and about 1,100 leaves, and its recent working set is close to every leaf in the tree.
The exact numbers vary with the seed. The gap is the point: the same 5,000 inserts touch more than ten times as many pages when keys are random.
The simulation ignores disk and caching. Add the assumption that the buffer pool holds only 200 pages, and the sequential workload never misses while the random workload misses on most inserts.
When the effect is real, and when it is not
The penalty depends on how the index compares to memory and how the engine stores rows.
| Situation | Effect of random keys |
|---|---|
| Whole index fits in the buffer pool | Small. Splits and lower fill still cost CPU and space, but there are no disk reads on the insert path. |
| Index much larger than memory | Large. Most inserts need a random read, and many dirty pages must be flushed. |
| InnoDB (table is clustered on the primary key) | Large. The table rows themselves are stored in the primary key B-tree, so random keys scatter the data pages as well as the index. |
| PostgreSQL (heap table plus separate index) | Moderate. Rows are appended to the heap regardless of key. Only the primary key index and any index on the ID column suffer. |
| Insert-light workload (a few hundred rows per second) | Often negligible. Measure before changing the scheme. |
Secondary indexes in InnoDB
In InnoDB, every secondary index entry stores the primary key value so it can find the row. A wide primary key makes every secondary index larger. Compare the sizes:
| Key format | Bytes per entry |
|---|---|
| BIGINT (for example a Snowflake ID) | 8 |
| UUID stored as BINARY(16) | 16 |
| UUID stored as CHAR(36) text | 36 (more with a multibyte character set) |
Storing UUIDs as text is a common mistake. It more than doubles the key size compared with binary, so fewer entries fit per page and the tree is deeper and fatter. Use the database's native UUID type (PostgreSQL uuid) or BINARY(16).
How time-ordered IDs reduce the cost
UUID v7, ULID, and Snowflake IDs put a millisecond timestamp in the high bits. Keys generated at roughly the same time sort close together, so inserts concentrate in the right edge of the index, as in the sequential case.
Some details are worth knowing:
- Many writers still work well. Ten application servers inserting concurrently generate IDs whose timestamps differ by milliseconds. All of those land in the same few recent leaves, so the working set stays small.
- Order is approximate. IDs from different machines within the same millisecond, or from machines with skewed clocks, arrive slightly out of order. That causes the occasional mid-page insert, which is cheap because the page is hot.
- Recent data is hot. Time-ordered keys also give good locality for reads, because queries often ask for recent records.
- Sequential keys have a downside. All writers contend for the same rightmost leaf. At very high insert rates this causes latch contention (waiting on a lock protecting the page) on that page. Some systems spread writes on purpose, for example by hashing, partitioning by a shard prefix, or giving each node its own range.
A practical checklist
- Find out whether your engine clusters rows on the primary key (InnoDB, SQL Server by default) or not (PostgreSQL).
- Compare the index size with the memory available for the buffer pool.
- Check how the ID is stored. Binary or native UUID types are far better than text.
- Run an insert benchmark with realistic table size. A test on an empty table hides the problem, because the index fits in memory.
- If random keys hurt, consider UUID v7, ULID, or a Snowflake-style ID. If you must keep an opaque public ID, keep an internal time-ordered key as the primary key and expose the random one in a separate unique column.
Exercise
A team uses UUID v4 stored as CHAR(36) as the primary key of an InnoDB table with three secondary indexes. Insert throughput falls sharply once the table reaches 200 GB on a server with 32 GB of RAM. Give two distinct reasons for the slowdown and one change for each.
Show answer
First reason: random keys scatter inserts across all leaf pages of the clustered index, so with the index far larger than RAM most inserts need a disk read and cause splits and extra page flushes. A fix is to use a time-ordered key such as UUID v7 or a Snowflake ID so inserts concentrate on the right edge. Second reason: the 36-byte text key is copied into all three secondary indexes, so every index is much larger, fewer entries fit per page, and less of each index fits in RAM. A fix is to store the UUID as BINARY(16), or use an 8-byte BIGINT key. Either change reduces the number of pages that must be cached.
Exercise
In the simulation, the sequential run reaches fill near 100% and the random run about 70%. Why does the random run settle near 70% and not stay at 50% after a split?
Show answer
A split leaves two pages that are each about half full, but later random inserts keep filling them until they split again. Over many splits, pages are at all stages between half full and full, and the average utilization converges to about 69% (ln 2). Sequential inserts avoid this because the old page is left full and only the new rightmost page grows.
Exercise
Your PostgreSQL table uses a random UUID primary key, and the table has 2 million rows that fit entirely in memory. A colleague wants to migrate to UUID v7 for index performance. Is the expected gain large? What would you check first?
Show answer
The gain is probably small, because the index fits in the buffer pool and inserts do not need disk reads. Splits and lower fill still cost some CPU and space, but not the large penalty seen with an out-of-memory index. Before migrating, benchmark inserts at the expected future table size and check how many full-page images the write-ahead log produces, since growth beyond memory is when the difference appears.