
Random UUIDs quietly tax every insert. I measured how much, and what to use instead.
Every new table starts with the same question: what goes in the id column?
The usual advice is "it depends." So I stopped guessing and loaded 10 million rows into three otherwise identical Postgres tables, one per key type. Here's what happened.
TL;DR: UUIDv4 was 3.5x slower to load than
bigint, built a 29% bigger index than UUIDv7, and right after a checkpoint wrote 18x more WAL per batch than UUIDv7. UUIDv7 performed close tobigint. Usebigintfor internal IDs and UUIDv7 when you need a UUID. Avoid UUIDv4 as the primary key on big, write-heavy tables.
The three contenders
bigintidentity: 8 bytes, handed out by a sequence: 1, 2, 3, …UUIDv4: 16 bytes, 122 of the 128 bits random.
UUIDv7: 16 bytes, standardized in RFC 9562 (May 2024). It starts with a timestamp, so new IDs sort after old ones.
flowchart LR
subgraph V4["UUIDv4 (all random)"]
direction LR
f["<b>48 bits</b><br/>random"]:::rand ~~~ g["<b>4</b><br/>ver 4"]:::meta ~~~ h["<b>12</b><br/>random"]:::rand ~~~ i["<b>2</b><br/>variant"]:::meta ~~~ j["<b>62 bits</b><br/>random"]:::rand
end
subgraph V7["UUIDv7 (time first, then random)"]
direction LR
a["<b>48 bits</b><br/>Unix time (ms)"]:::time ~~~ b["<b>4</b><br/>ver 7"]:::meta ~~~ c["<b>12</b><br/>sub-ms time<br/>or counter"]:::time2 ~~~ d["<b>2</b><br/>variant"]:::meta ~~~ e["<b>62 bits</b><br/>random"]:::rand
end
classDef time fill:#1c7ed6,stroke:#1864ab,color:#fff
classDef time2 fill:#74c0fc,stroke:#1c7ed6,color:#0b2a4a
classDef rand fill:#e8590c,stroke:#c2410c,color:#fff
classDef meta fill:#868e96,stroke:#495057,color:#fffWhy the order of keys matters
A primary key is a B-tree index. Its leaves are 8 KB pages kept in key order.
With ascending keys (bigint, UUIDv7), every insert lands on the rightmost leaf. Postgres keeps that one page in memory, fills it to 90% (the default fillfactor), and moves on to a new one.
With random keys (UUIDv4), each insert lands on a random leaf, so every leaf has to be in memory to keep inserts fast. Full pages split 50/50 and refill at random, so pages settle around 70% full. The index ends up bigger, and the working set is the whole index.
flowchart TB
subgraph RND["UUIDv4: every page is hot"]
direction TB
r2((root)) --> m1["leaf ← insert"]:::hot & m2["leaf ← insert"]:::hot & m3["leaf ← insert"]:::hot & m4["leaf ← insert"]:::hot
end
subgraph SEQ["bigint / UUIDv7: one hot page"]
direction TB
r1((root)) --> l1[leaf]:::cold & l2[leaf]:::cold & l3[leaf]:::cold & l4["leaf ← all inserts"]:::hot
end
classDef hot fill:#e8590c,stroke:#c2410c,color:#fff
classDef cold fill:#d3f9d8,stroke:#2f9e44,color:#1b4332There's a second cost. After every checkpoint, the first change to any page writes a full copy of that page to the WAL (full_page_writes, on by default). One hot page means one copy. Thousands of random pages means thousands of 8 KB copies, which then flow to your replicas and backups.
The benchmark
Postgres 16.15, stock config (
shared_buffers128 MB,max_wal_size1 GB), on a 2 vCPU / 7 GB cloud VM.Three tables:
id,created_at timestamptz,payload text(32 chars). Only theidtype differs.Keys are generated client-side, like most apps do, by a Python script that simulates 10 inserts per millisecond. The UUIDv7 generator orders IDs within each millisecond, as Postgres 18 does.
Loaded with
\copyin 100 batches of 100k rows. Then one more batch right after aCHECKPOINT, to measure the worst moment.I ran it twice; the runs agreed within 8%. The numbers below are from the second run. Full scripts are at the end.
Every number here is measured, not estimated. I actually inserted 10.1 million rows into each table on a running Postgres server, did the whole run twice, and ran extra rate tests on top. The exact scripts are in the appendix, so you can rerun them on your own hardware.
The results
| UUIDv7 | UUIDv4 | |
|---|---|---|---|
Load 10M rows | 17.9 s | 21.4 s | 61.8 s |
ms per 100k batch: first 1M rows → last 1M rows | 169 → 167 | 191 → 253 | 355 → 731 |
WAL written during the load | 1.2 GB | 1.3 GB | 2.0 GB |
Primary key index size | 216 MB | 304 MB | 393 MB |
Leaf pages full (avg density) | 90% | 90% | 70% |
One batch right after a checkpoint: | |||
WAL written | 12 MB | 14 MB | 250 MB |
Full-page images in WAL | 4 | 8 | 42,438 |
Index pages read from outside | 1 | 1 | 67,184 |
Sizes measured at 10.1M rows.
UUIDv4 doesn't just start slower. It gets slower as the table grows, because the index outgrows memory while bigint and UUIDv7 keep writing to the same few pages:
%%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#2f9e44, #1c7ed6, #e8590c"}}}}%%
xychart-beta
title "ms per 100k-row batch as the table grows"
x-axis "Millions of rows already loaded" ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
y-axis "ms per batch" 0 --> 900
line [169, 156, 176, 174, 195, 176, 181, 160, 238, 167]
line [191, 195, 195, 202, 217, 202, 213, 282, 194, 253]
line [355, 454, 461, 488, 674, 695, 726, 774, 825, 731]Green: bigint · Blue: UUIDv7 · Orange: UUIDv4
Three takeaways:
UUIDv7 performs much closer to
bigintthan to UUIDv4. It loaded in 21 s vs 18 s. Its index is 41% bigger thanbigint's because the keys are twice as wide, but it's just as tightly packed.UUIDv4's index is 29% bigger than UUIDv7's for the same 16-byte keys. The difference is wasted space in partly empty pages.
Right after a checkpoint, UUIDv4 wrote 250 MB of WAL to insert about 9 MB of rows. It touched over 42,000 different pages, and each one was copied in full to the WAL.
One caveat: this VM had enough RAM that "reads from outside shared_buffers" came from the OS cache. On a production database whose index doesn't fit in RAM, those reads go to disk, and the gap grows.
The UUIDv7 trap: not all generators are equal
The first 48 bits of a UUIDv7 only resolve to the millisecond. What fills the next 12 bits is up to the generator:
Sub-millisecond time or a counter: IDs stay in order even inside one millisecond. Postgres 18's
uuidv7()uses 12 bits of sub-millisecond time, and Python 3.14'suuid.uuid7()uses a counter.Random: IDs inside a millisecond come out in random order. Many copy-paste SQL snippets work this way.
I tested the random kind at different insert rates (one generator, 2M rows each):
Inserts per millisecond | 1 | 10 | 100 | 150 | 200 | 300 | 500 | 1,000 |
|---|---|---|---|---|---|---|---|---|
Leaf density, ms-only UUIDv7 | 90% | 90% | 93% | 53% | 68% | 52% | 75% | 67% |
Up to 100 inserts per millisecond, it was fine. Above that, density swung unpredictably and sometimes ended up worse than UUIDv4. The ordered version stayed at 90% at every rate I tried (1 to 1,000 per ms).
The same effect can come from several app servers whose clocks disagree by a few milliseconds, because their IDs interleave out of order. Generating IDs in one place, such as the database, keeps them close to arrival order.
On Postgres 13–17, here's an ordered uuidv7() you can use as a column default:
-- uuidv7() for Postgres 13-17. Postgres 18+ has a built-in uuidv7(); use that.
-- Layout: 48-bit Unix ms | version 7 | 12-bit fraction of the ms | variant | 62 random bits.
create or replace function uuidv7() returns uuid
language plpgsql volatile as $$
declare
us bigint := (date_part('epoch', clock_timestamp()) * 1000000)::bigint;
begin
return encode(
overlay(uuid_send(gen_random_uuid())
placing int8send(((us / 1000) << 16) -- Unix time in ms
| x'7000'::int::bigint -- version 7
| ((us % 1000) * 4096 / 1000)) -- fraction of the ms
from 1 for 8),
'hex')::uuid;
end $$;
-- create table orders (id uuid primary key default uuidv7(), ...);It costs about 3.3 µs per ID vs about 1.3 µs for gen_random_uuid() on my VM. That's fine for most workloads; for bulk loads, generate IDs in the app.
Things the benchmark doesn't show
Lookups by ID cost about the same. All three indexes were 3 levels deep at 10M rows, so finding a row reads the same number of pages.
UUIDv7 reveals when a row was created. Anyone with the ID can read the millisecond timestamp. That's harmless for an order ID, but maybe not for a user signup on a privacy-sensitive product.
bigintreveals counts and is guessable./invoices/1042invites someone to try/invoices/1043. Don't put sequential IDs in public URLs unless every endpoint checks access properly.Store UUIDs as
uuid, never astext. A 36-character string takes more than twice the space and compares slower.On MySQL (InnoDB) the stakes are higher. The table itself is stored as a B-tree ordered by primary key, so random keys scatter the rows themselves, and every secondary index stores a copy of the primary key.
So which one should you use?
flowchart TD
A{"IDs created outside<br/>the database?"} -->|Yes| V7["UUIDv7"]:::v7
A -->|No| B{"IDs shown in<br/>URLs or APIs?"}
B -->|No| BI["bigint identity"]:::bi
B -->|Yes| C{"Leaking creation<br/>time a problem?"}
C -->|No| V7
C -->|Yes| V4["bigint PK +<br/>UUIDv4 public_id"]:::v4
classDef v7 fill:#1c7ed6,stroke:#1864ab,color:#fff
classDef bi fill:#2f9e44,stroke:#2b8a3e,color:#fff
classDef v4 fill:#e8590c,stroke:#c2410c,color:#fffDefault for a new Postgres table:
bigint generated always as identityif the ID stays internal, UUIDv7 if it doesn't (generated by clients, merged across services or shards, or shown in URLs).If creation time must stay secret: keep a
bigintprimary key and add a UUIDv4public_idcolumn, or use a UUIDv4 primary key and accept the write cost.On Postgres 18+:
id uuid primary key default uuidv7(). It's built in.Already on UUIDv4? Small tables won't notice. If a big, write-heavy table is suffering, switching new rows to UUIDv7 helps right away: new IDs share nearly the same time prefix, so inserts hit one small region of the index instead of every page. The old random part stays as it is.
Avoid: UUIDv4 as the primary key on large, write-heavy tables, and millisecond-only UUIDv7 generators on tables with high insert rates.
Appendix: run it yourself
Needs Postgres 14+ (for pg_stat_wal), the pgstattuple extension, Python 3.8+, and superuser rights for CHECKPOINT and pg_stat_reset_shared (or the pg_checkpoint role on 15+). Generated keys take about 1.7 GB on disk.
python3 gen_keys.py 10100000 # 101 batches x 100k rows per key type, 10 inserts/ms
PSQL="psql -d bench" ./run.shsetup.sql
-- setup.sql: identical tables that differ only in primary key type.
create extension if not exists pgstattuple;
drop table if exists t_bigint, t_uuidv7, t_uuidv4;
create table t_bigint (
id bigint generated always as identity primary key,
created_at timestamptz not null default now(),
payload text not null
);
create table t_uuidv7 (
id uuid primary key,
created_at timestamptz not null default now(),
payload text not null
);
create table t_uuidv4 (
id uuid primary key,
created_at timestamptz not null default now(),
payload text not null
);gen_keys.py
#!/usr/bin/env python3
"""Generate CSV batches of (id, payload) for each key type, the way an app would.
Usage: python3 gen_keys.py [rows] [batch_size] [rows_per_ms] [out_dir] [kinds]
UUIDv7 timestamps are simulated at a fixed insert rate (rows_per_ms) so runs are
repeatable and the rate can be varied. Stdlib only; works on Python 3.8+.
"""
import hashlib
import os
import random
import sys
import uuid
ROWS = int(sys.argv[1]) if len(sys.argv) > 1 else 10_000_000
BATCH = int(sys.argv[2]) if len(sys.argv) > 2 else 100_000
RATE = float(sys.argv[3]) if len(sys.argv) > 3 else 10.0 # rows per millisecond
OUT = sys.argv[4] if len(sys.argv) > 4 else "keys"
WANT = (sys.argv[5] if len(sys.argv) > 5 else "t_bigint,t_uuidv7,t_uuidv4").split(",")
BASE_MS = 1_764_000_000_000 # a fixed start time (Nov 2025) for repeatability
rng = random.Random(42)
def v7(ms: int, rand_a: int) -> uuid.UUID:
"""48-bit Unix ms | ver 7 | 12-bit rand_a | variant 10 | 62 random bits."""
rand_b = rng.getrandbits(62)
n = (ms << 80) | (0x7 << 76) | (rand_a << 64) | (0b10 << 62) | rand_b
return uuid.UUID(int=n)
def uuidv7_subms(i: int) -> uuid.UUID:
"""RFC 9562 method 3: rand_a holds the fraction of the millisecond (like Postgres 18)."""
us = int(i * 1000 / RATE)
return v7(BASE_MS + us // 1000, (us % 1000) * 4096 // 1000)
def uuidv7_ms(i: int) -> uuid.UUID:
"""Millisecond precision only: random order inside each millisecond."""
return v7(BASE_MS + int(i / RATE), rng.getrandbits(12))
def uuidv4(i: int) -> uuid.UUID:
return uuid.UUID(int=rng.getrandbits(128), version=4)
KINDS = {"t_uuidv7": uuidv7_subms, "t_uuidv7_ms": uuidv7_ms, "t_uuidv4": uuidv4, "t_bigint": None}
for tbl in WANT:
make_id = KINDS[tbl]
os.makedirs(f"{OUT}/{tbl}", exist_ok=True)
for b in range(ROWS // BATCH):
with open(f"{OUT}/{tbl}/{b:04d}.csv", "w") as f:
for i in range(b * BATCH, (b + 1) * BATCH):
payload = hashlib.md5(str(i).encode()).hexdigest()
f.write(f"{make_id(i)},{payload}\n" if make_id else f"{payload}\n")
print(f"{tbl}: {ROWS // BATCH} files")run.sh
#!/usr/bin/env bash
# run.sh: load every batch but the last into each table, report, then load the
# last batch right after a checkpoint and measure what it cost.
# Usage: python3 gen_keys.py 10100000 && PSQL="psql -d bench" ./run.sh
set -euo pipefail
PSQL=${PSQL:-psql}
KEYS=${KEYS:-keys}
q() { $PSQL -X -q -At -v ON_ERROR_STOP=1 "$@"; }
q -f setup.sql
for t in t_bigint t_uuidv7 t_uuidv4; do
cols="(id, payload)"; [ "$t" = t_bigint ] && cols="(payload)"
files=("$KEYS/$t"/*.csv); last=${files[-1]}; unset 'files[-1]'
# 1) Bulk of the load: one \copy per batch, \timing prints each duration.
q -c "checkpoint"
lsn0=$(q -c "select pg_current_wal_lsn()")
{ echo '\timing on'
for f in "${files[@]}"; do echo "\\copy $t $cols from '$f' with (format csv)"; done
} | $PSQL -X -q -v ON_ERROR_STOP=1 | awk '/^Time:/ {print $2}' > "times_$t.txt"
wal=$(q -c "select pg_size_pretty(pg_current_wal_lsn() - '$lsn0')")
awk -v t="$t" -v wal="$wal" '{ms[NR]=$1; s+=$1} END {
for (i=1;i<=10;i++) {a+=ms[i]; b+=ms[NR-10+i]}
printf "%-9s load %5.1f s | first 10 batches %4.0f ms each | last 10 %4.0f ms each | WAL %s\n",
t, s/1000, a/10, b/10, wal}' "times_$t.txt"
# 2) One more batch right after a checkpoint (the worst moment for WAL).
q -c "checkpoint" -c "select pg_stat_reset_shared('wal')"
r0=$(q -c "select idx_blks_read from pg_statio_user_indexes where indexrelname = '${t}_pkey'")
ms=$( { echo '\timing on'; echo "\\copy $t $cols from '$last' with (format csv)"; } \
| $PSQL -X -q | awk '/^Time:/ {print $2}')
sleep 1 # let cumulative stats flush
q -F' | ' -c "select '$t after checkpoint', round($ms) || ' ms',
'WAL ' || pg_size_pretty(wal_bytes), 'full-page images ' || wal_fpi,
'pk pages read ' || (select idx_blks_read - $r0 from pg_statio_user_indexes
where indexrelname = '${t}_pkey')
from pg_stat_wal"
done
$PSQL -X -f report.sqlreport.sql
-- report.sql: sizes and B-tree health per table.
select t.tbl,
pg_size_pretty(pg_table_size(t.tbl::regclass)) as heap,
pg_size_pretty(pg_relation_size((t.tbl || '_pkey')::regclass)) as pk_index,
s.leaf_pages,
s.avg_leaf_density
from (values ('t_bigint'), ('t_uuidv7'), ('t_uuidv4')) as t(tbl),
lateral pgstatindex((t.tbl || '_pkey')::regclass) s;For the rate sweep: python3 gen_keys.py 2000000 2000000 <rows_per_ms> keys t_uuidv7_ms, load the file into a table with a uuid primary key, and check select avg_leaf_density from pgstatindex('<table>_pkey').
Comments0
Join the discussion by logging into your account.
No comments yet. Start the conversation.