Blog

UUIDv7 vs UUIDv4 PKs in Postgres 18: inserts and WAL

  • postgresql
  • uuid
  • performance
  • dotnet
  • npgsql
Illustration: two abstract B-trees on a dark background. The left tree has scattered amber nodes; the right tree has cyan nodes packed along the right edge.

Random UUID primary keys feel safe until you watch a B-tree under insert load. On PostgreSQL 18.6 we inserted the same 1,000,000 rows three ways — server-side uuidv4(), server-side uuidv7(), and client-side Guid.CreateVersion7() through Npgsql 10 — and measured insert rate, index size, leaf density, and WAL. Server-side uuidv7() was about 47% faster than uuidv4(), with a 21% smaller primary-key index, about 9% less WAL, and near-perfect leaf packing. Client-side Guid.CreateVersion7() was the fastest inserter, but its index looked more like v4 than like server v7 — and that gap is the real lesson.

This is a performance case study on one box, not a general ranking of UUID versions. It does not cover secondary indexes, concurrent writers, or replication lag.

Why random keys punish a B-tree

A PostgreSQL primary key on uuid is a B-tree. New keys have to land in the leaf that owns their sort position. With fully random v4 keys, that leaf is somewhere in the whole index, so each insert risks reading and dirtying a cold page, splitting a full leaf, and writing a full-page image to WAL. With time-ordered v7 keys, new values cluster near the right edge of the index, so the hot leaf stays cached and splits stay local.

Diagram comparing a scattered UUIDv4 B-tree on the left with a right-edge-appending UUIDv7 B-tree on the right. Illustrative only.

Illustrative only — not a measured page layout.

RFC 9562 defines UUID version 7 as a Unix-millisecond timestamp in the high 48 bits, plus random bits (optionally a sub-millisecond fraction or counter for monotonicity). PostgreSQL 18 adds uuidv7() for that layout, alongside the older random generators gen_random_uuid() / uuidv4(). .NET exposes the same version through Guid.CreateVersion7().

Environment and methodology

Item Value
Host 8 vCPU Intel Xeon, 15 GiB RAM, ext4 on virtio disk (ROTA=1)
OS Debian 13, Linux 6.12.94
PostgreSQL 18.6 (Debian 18.6-1.pgdg13+2), data checksums on
Notable settings shared_buffers=128MB, wal_level=replica, fsync=on, synchronous_commit=on, full_page_writes=on, max_wal_size=1GB
Client .NET 10.0.13 / SDK 10.0.402, Npgsql 10.0.3
Load shape 1,000,000 rows, batches of 100 via INSERT … SELECT unnest(...), one client connection
Runs 3 per arm; numbers below are medians
During load autovacuum=off, CHECKPOINT before and after each run
Index stats pgstatindex() from the pgstattuple extension

Schema (three otherwise identical tables):

CREATE TABLE rows_v4 (
  id uuid PRIMARY KEY DEFAULT uuidv4(),
  payload int NOT NULL
);

CREATE TABLE rows_v7 (
  id uuid PRIMARY KEY DEFAULT uuidv7(),
  payload int NOT NULL
);

CREATE TABLE rows_dotnet_v7 (
  id uuid PRIMARY KEY,
  payload int NOT NULL
);

For the server arms the client only sends payload; Postgres fills id from the default. For the .NET arm the client sends Guid.CreateVersion7() values. Before measuring, we confirmed Npgsql preserves version and timestamp:

dotnet_guid=01a170d6-9dd0-7f03-a9b0-f77729e3d49d
pg_version=7
has_timestamp=True
pg_text=01a170d6-9dd0-7f03-a9b0-f77729e3d49d

uuid_extract_version / uuid_extract_timestamp are documented in the PostgreSQL 18 UUID functions. Across millisecond boundaries, CreateVersion7() values were non-decreasing; within the same millisecond they were not, which matches the API remark that rand_a / rand_b are seeded with random data.

Download the harness: uuidv7-vs-uuidv4-sample.zip.

Results: server uuidv7() wins the index

Bar chart of insert throughput: uuidv4 188577 rows/s, uuidv7 276744 rows/s, Guid.CreateVersion7 290933 rows/s.

Insert throughput, median of three 1,000,000-row runs.

Bar chart of primary-key index size: uuidv4 38.3 MiB, uuidv7 30.1 MiB, Guid.CreateVersion7 43.0 MiB.

Primary-key index size after the load. Heap size was identical at 49.8 MiB for every arm.

Arm rows/s PK index WAL (LSN delta) avg_leaf_density leaf_fragmentation
uuidv4() 188,577 38.3 MiB 162.9 MiB 70.70% 49.82%
uuidv7() 276,744 30.1 MiB 148.9 MiB 89.98% 0.00%
Guid.CreateVersion7() 290,933 43.0 MiB 157.3 MiB 63.09% 47.24%

Across the three runs, uuidv4() ranged from 176,521 to 201,100 rows/s, uuidv7() from 263,274 to 288,294, and Guid.CreateVersion7() from 278,884 to 304,130. Index size and leaf density barely moved between runs for a given arm; the throughput spread is mostly client and OS noise on a shared VM.

Relative to uuidv4(), server uuidv7() was 1.47× the insert rate, 0.79× the index size, and 0.91× the WAL. Leaf fragmentation dropped from about 50% to 0%. Heap bytes did not move: the locality win is in the index and the WAL that records its page splits and full-page images.

Grouped bar chart of leaf density and fragmentation for the three arms.

Leaf density and fragmentation from pgstatindex after each load.

PostgreSQL’s own uuidv7() description in the 18.0 release notes calls the value “temporally sortable,” and the function docs say the timestamp is “UNIX timestamp with millisecond precision + sub-millisecond timestamp + random.” Sequential calls in one backend are monotonic — we checked with generate_series and lag(). That monotonicity is what keeps inserts appending at the right edge.

The .NET surprise: fast inserts, fragmented leaves

Guid.CreateVersion7() through Npgsql was the fastest arm on raw rows/s, yet its primary-key index was larger than v4’s and almost as fragmented. Sorting each batch before insert, and even INSERT … SELECT … ORDER BY id inside the batch, did not fix it.

The cause is how the two generators fill the bits after the millisecond timestamp. Per the CreateVersion7 remarks, .NET seeds rand_a and rand_b with random data. At ~250k–300k rows/s, many UUIDs share the same millisecond. Within that millisecond the random bits scatter keys across the current time window, so consecutive batches still do random leaf writes inside that window. Postgres uuidv7() adds a sub-millisecond timestamp component, so back-to-back calls stay ordered and pack leaves densely.

A follow-up on 50,000 rows made the difference obvious:

Generator avg_leaf_density leaf_fragmentation PK index
Guid.CreateVersion7() with a 1 ms delay between IDs 89.79% 0.00% 1.5 MiB
Guid.CreateVersion7() batched at full speed 64.66% 37.45% 2.1 MiB
Server uuidv7() 89.79% 0.00% 1.5 MiB

Slow the client enough that each UUID gets a distinct millisecond, and the index matches server v7. Generate them as fast as the network can take, and you keep v7’s sortable prefix without v7’s dense packing.

What we would do in an app

  1. Prefer DEFAULT uuidv7() on the primary key when the database assigns IDs. You get monotonic generation next to the index that consumes it, and the client stays simple.
  2. If the client must mint IDs, treat Guid.CreateVersion7() as “time-bucketed random,” not as a drop-in for Postgres uuidv7(). For bulk loads, either let Postgres generate the keys or use a generator with a monotonic counter / sub-ms component (RFC 9562 section 6.2).
  3. Measure with pg_relation_size, pg_wal_lsn_diff, and pgstatindex, not only with client stopwatches. Our .NET arm would have looked like a win on rows/s alone.
  4. Remember the privacy trade-off. uuid_extract_timestamp() recovers creation time from v7 values. That is useful for debugging and dangerous if the ID is exposed as an opaque public token.

Caveats

  • One client, one table, no secondary indexes, no foreign keys, autovacuum off. Concurrent writers and HOT updates change the picture.
  • The disk is a virtual spinning device (ROTA=1) in a shared VM. Absolute rows/s will not match a dedicated NVMe host; the ratios between arms are the claim.
  • WAL deltas include full-page writes after each checkpoint. That is realistic for crash-safe Postgres; it also amplifies the cost of scattered leaf dirties.
  • We did not test UUIDv4 from Guid.NewGuid(), nor Npgsql bulk COPY. Those are separate comparisons.

Takeaways

  • On this box, Postgres 18 uuidv7() primary keys inserted ~47% faster than uuidv4(), with a ~21% smaller index and ~9% less WAL, at ~90% leaf density versus ~71%.
  • Client-side Guid.CreateVersion7() can beat both on insert rate and still lose on index density, because random rand_a/rand_b inside the same millisecond reintroduces local scatter.
  • Stopwatch numbers without pgstatindex and WAL deltas can point at the wrong winner.

Reproduce with the sample zip, then run pgstatindex on your own primary key after a representative load. If leaf fragmentation stays high on “v7” keys you generate in the app, check whether your generator is monotonic inside a millisecond — or move ID creation to uuidv7() in Postgres.