DEV Community

Cover image for Stop Reaching for UUIDv4 Primary Keys: What Postgres 18's uuidv7 Fixes
Andrii B.
Andrii B.

Posted on AI-assisted

Stop Reaching for UUIDv4 Primary Keys: What Postgres 18's uuidv7 Fixes

Here's a table definition you've probably written, approved in review, or copied from a tutorial:

CREATE TABLE orders (
  id         uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  customer_id uuid NOT NULL,
  total_cents bigint NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);
Enter fullscreen mode Exit fullscreen mode

Nothing is wrong with it on day one. IDs are unguessable, you can generate them on any service without a round trip, and merging data from two databases never collides. It works fine at ten thousand rows. It works fine at a million.

Then the table outgrows memory, and that DEFAULT gen_random_uuid() starts costing you in a way that doesn't show up in any single query plan. Every insert lands on a random page of the primary key index. Pages split in half and stay half empty. Checkpoints turn into a flood of full-page images in the WAL. On a Postgres 18 test run further down, the v4 table wrote roughly 11 to 20 times more full-page images per minute than an identical table keyed by uuidv7(), and its primary key ended up about 30% bigger for the same row count.

Postgres 18 shipped a native uuidv7() in September 2025. It keeps everything you liked about UUIDs and gives the index back the one thing a primary key actually wants: new keys that sort after old keys. Let's break down why that matters, what the function really does under the hood, and when v4 is still the right answer.

What a random key does to a B-tree

A Postgres primary key is a B-tree index. Leaf pages are 8KB, sorted by key, and linked left to right. When you insert a row, Postgres walks down the tree to the one leaf page where the new key belongs and puts it there.

With a random v4 UUID, "where the new key belongs" is anywhere. The first 32 bits of a v4 value are uniformly random, so insert number 1,000,001 is as likely to land on page 3 as on page 38,000. That has three consequences, and they compound.

Every insert touches a random page. Your write working set is the whole index, not the last few pages. As long as the index fits in shared_buffers and the OS cache, you barely notice. Once it doesn't, inserts start reading index pages from disk just to write one 16-byte key into them.

Pages split down the middle and stay that way. When a leaf page is full, Postgres splits it into two pages. For a page in the middle of the index, it splits roughly evenly, leaving two half-full pages. With random keys, both halves will eventually fill up again, but new keys keep arriving everywhere, so the index settles into a state where the average leaf is only partly full. On the test run below, that steady state measured 69.36% average leaf density, so roughly a third of every leaf page is air.

Sequential keys get a special path. When the page being split is the rightmost page on its level, Postgres leaves the left page fillfactor% full instead of splitting it in half (the B-tree default is 90). The comment in nbtsplitloc.c spells out the intent: when you're "inserting successively increasing keys (consider sequences, timestamps, etc)" you end up with pages about fillfactor% full. A time-ordered key hits that path nearly every time.

Checkpoints make random writes expensive in WAL. With full_page_writes = on (the default), the first time a page is modified after a checkpoint, Postgres writes the entire 8KB page image into the WAL, not just the change. That's crash-safety against torn pages, and you want it. But with random keys, the set of "first touch after checkpoint" pages is enormous: thousands of different leaf pages each get a full image right after every checkpoint. With time-ordered keys, the inserts keep hitting the same handful of right-edge pages, so there are only a few new pages to image each cycle.

Think of it like a library shelving new books. With v4, every new book goes to a random shelf, so the librarian walks the whole building, and when a shelf overflows, half its books move to a new, half-empty shelf. With v7, every new book goes at the end of the last shelf. Same number of books, very different amount of walking.

Side-by-side B-tree diagram: UUIDv4 inserts land on scattered leaf pages that split 50/50 to about 69% full with many WAL full-page images, while UUIDv7 inserts all land on the rightmost leaf, older pages stay about 90% full and few full-page images are written

What the numbers look like on Postgres 18

Talking about page splits is cheap, so here are the numbers from a real Postgres 18 instance: the official postgres:18-alpine Docker image (PostgreSQL 18.6) on an Apple Silicon laptop. They're single runs on one machine, so treat them as a demonstration of the shape of the problem, not a benchmark you can quote for your hardware. The script is short enough to run yourself.

Bulk load: 10 million rows into an empty table

Three tables, one column of payload, a primary key each. shared_buffers = 256MB, max_wal_size = 4GB, so no checkpoint fired mid-load.

bulk.sql

CREATE EXTENSION IF NOT EXISTS pgstattuple;

CREATE TABLE t_v4  (id uuid PRIMARY KEY DEFAULT uuidv4(), payload int);
CREATE TABLE t_v7  (id uuid PRIMARY KEY DEFAULT uuidv7(), payload int);
CREATE TABLE t_big (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, payload int);

INSERT INTO t_v4 (payload)  SELECT g FROM generate_series(1, 10000000) g;
INSERT INTO t_v7 (payload)  SELECT g FROM generate_series(1, 10000000) g;
INSERT INTO t_big (payload) SELECT g FROM generate_series(1, 10000000) g;

SELECT pg_size_pretty(pg_relation_size('t_v4_pkey')),
       (pgstatindex('t_v4_pkey')).avg_leaf_density,
       (pgstatindex('t_v4_pkey')).leaf_fragmentation;
Enter fullscreen mode Exit fullscreen mode
Key Insert time PK index size Avg leaf density Leaf fragmentation Leaf pages
uuidv4() 48.5 s 391 MB 69.36% 49.83% 49,765
uuidv7() 20.0 s 301 MB 89.99% 0% 38,315
bigint identity 25.0 s 214 MB 90.04% 0% 27,323

The v4 index is 30% bigger than the v7 index holding the exact same number of 16-byte keys. That's pure wasted space from half-split pages. The v7 and bigint indexes both sit at 90% density, which is the B-tree fillfactor, meaning every page got filled and then split off the right edge. The v4 insert took more than twice as long as v7 on the same data.

Don't read much into v7 beating bigint on time in this one run. A single bulk insert on a laptop is noisy, and the gap there doesn't tell you anything about keys. The index sizes and densities are the stable signal: bigint is still the smallest because its key is 8 bytes instead of 16.

Steady state: concurrent single-row inserts

Bulk loads are the friendly case. Production looks more like many connections inserting one row at a time. This second run used Postgres defaults (shared_buffers = 128MB, max_wal_size = 1GB) plus checkpoint_timeout = 60s so checkpoints actually happen during the test. Each table was pre-loaded with 5 million rows, then pgbench ran 8 clients for 60 seconds, each transaction inserting one row. Two alternating rounds per key type:

# ins_v7.sql contains: INSERT INTO t_v7 (payload) VALUES (1);
pgbench -n -c 8 -j 4 -T 60 -f ins_v7.sql postgres
Enter fullscreen mode Exit fullscreen mode
Round Key TPS WAL written Full-page images WAL per insert
1 uuidv4() 11,740 310 MB 31,620 ~460 bytes
1 uuidv7() 12,399 144 MB 1,569 ~200 bytes
2 uuidv4() 8,551 254 MB 28,931 ~520 bytes
2 uuidv7() 14,277 172 MB 2,638 ~210 bytes

The WAL and FPI numbers come from pg_stat_wal, reset after a manual CHECKPOINT before each round. Throughput swung a lot between rounds (v7 came out 6% ahead in one round and 67% ahead in the other), which is what you'd expect from a laptop. The WAL columns didn't swing: v4 wrote 11 to 20 times more full-page images and roughly 2.2 to 2.5 times more WAL per inserted row, both rounds.

That WAL number is the one I'd care about in production. WAL volume drives replication lag, archive storage, backup size, and how fast a replica can catch up after a hiccup. A primary key choice that more than doubles it is not a micro-optimisation.

After both rounds, the v4 primary key was 248 MB at 68% leaf density. The v7 one was 199 MB at 90%, while holding about 380,000 more rows.

What uuidv7() actually puts in those 128 bits

UUIDv7 is defined in RFC 9562, published in May 2024, which replaced the old RFC 4122. The layout is simple:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        unix_ts_ms (32 of 48)                  |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|  unix_ts_ms (16 of 48)        |  ver  |       rand_a (12)     |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|var|                   rand_b (62)                             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                          rand_b                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Enter fullscreen mode Exit fullscreen mode

The first 48 bits are a big-endian Unix timestamp in milliseconds. Because it's big-endian and at the front, byte-wise comparison of two v7 UUIDs orders them by creation time, and Postgres compares uuid values byte-wise. That's the whole trick. The RFC even calls out the database angle directly in its section on sorting: time-ordered UUIDs "benefit from greater database-index locality because the new values are near each other in the index."

The interesting part is what goes in rand_a. The RFC gives implementations a few options for staying monotonic when many UUIDs are generated inside the same millisecond. Postgres picks what the RFC calls Method 3, "Replace Leftmost Random Bits with Increased Clock Precision." Those 12 bits store a sub-millisecond fraction of the clock (1/4096 of a millisecond), so two v7 values generated microseconds apart still sort correctly. The remaining 62 bits of rand_b are random.

There's one more detail in the Postgres source (src/backend/utils/adt/uuid.c) that's easy to miss. The generator remembers the last timestamp it used and, if the clock hasn't advanced enough, bumps the new one forward by a minimum step. The comment says that guarantee holds "on this backend." So:

  • Within one connection, uuidv7() values are strictly increasing, even in a tight loop. The 10-million-row bulk load above came out in perfect order.
  • Across different connections, there's no shared counter. Two backends inserting in the same fraction of a millisecond can produce values that interleave. That's fine for index locality, since they still land within a page or two of each other, but it means you should not treat v7 order as a strict global sequence.

The source also notes that on macOS and Windows, the clock only gives microsecond precision, so Postgres fills just 10 of the 12 sub-millisecond bits from the clock and randomises the last two. Your Linux production box gets all 12.

The functions you actually get

The Postgres 18 docs list these in the UUID functions table:

SELECT uuidv7();                          -- time-ordered, version 7
SELECT uuidv4();                          -- new explicit alias for gen_random_uuid()
SELECT uuidv7(interval '-1 hour');        -- timestamp shifted by an interval
SELECT uuid_extract_timestamp(uuidv7());  -- timestamptz, or NULL for non-v1/v7
SELECT uuid_extract_version(uuidv7());    -- 7
Enter fullscreen mode Exit fullscreen mode

A few things worth knowing:

  • uuidv4() is new in 18 too, just as an alias. gen_random_uuid() still works and still means v4. The release notes say the alias was added "to explicitly generate version 4 UUIDs", which is nice for readability when a schema mixes both.
  • uuidv7(shift interval) shifts the embedded timestamp. The docs say the result has to stay inside the 48-bit millisecond range, from the 1970 epoch to "approximately year 10889", and infinite intervals are rejected. It's useful for backfilling rows with a historical-looking key, or for tests.
  • uuid_extract_timestamp() works on v1 and v7 and returns NULL for everything else, including v4. The docs add a warning worth taking seriously: the extracted timestamp "is not necessarily exactly equal to the time the UUID was generated; this depends on the implementation that generated the UUID."

That last point is a gotcha. It's tempting to drop your created_at column because "the ID already has the timestamp." Don't. The shift parameter alone means a v7 value can carry any time you like, application-generated v7 values carry the app server's clock rather than the database's, and the precision is milliseconds. Keep created_at as the real record. Use the embedded time for ordering, not for business logic.

Bit layout of a Postgres 18 uuidv7 value: 48-bit Unix millisecond timestamp, 4-bit version 7, 12-bit sub-millisecond clock fraction, 2-bit variant and 62 random bits, mapped onto the example 019535d9-3df7-79fb-b466-fa907fa17f9e

Switching an existing table is one line, with a catch

If you've got a v4-keyed table today, you don't need to rewrite a single existing ID. A uuid column holds v4 and v7 values side by side, so switching is just a new default:

ALTER TABLE orders ALTER COLUMN id SET DEFAULT uuidv7();
Enter fullscreen mode Exit fullscreen mode

Old rows keep their v4 IDs, new rows get v7. Foreign keys, APIs, and anything that stored those IDs elsewhere keep working. That's a big deal compared to moving to bigint, which touches every foreign key and every external consumer.

The ALTER itself is a catalog-only change, but it still needs an ACCESS EXCLUSIVE lock on the table, so on a busy table set a short lock_timeout first. Migrating a Large Table Without Locking Production covers why a DDL statement stuck waiting for that lock can stall every query queued behind it.

Here's the catch. All v7 values generated today start with nearly the same bytes, so they land in one narrow band of the keyspace. But that band sits in the middle of an index already full of random v4 keys, not at the right edge. The rightmost-page optimisation doesn't apply there, so pages in that band split evenly, the same way v4 splits do.

A small test on Postgres 18 shows the effect. Take two tables with 5 million rows each, one keyed v4 and one keyed v7. Switch the v4 table's default to uuidv7(), then insert 2 million more rows into each:

Table Index pages before Index pages after +2M v7 rows Growth
Was v4, now defaults to v7 24,514 38,402 +13,888
Always v7 19,253 26,954 +7,701

Same 2 million v7 keys, about 1.8 times as many new index pages when they're appended into the middle of an old v4 index. You still get the locality win (the inserts hit a small, hot set of pages instead of the whole index, so the cache and FPI story improves), but you don't get the density win for free.

The fix is cheap: once the new rows dominate, rebuild the index without blocking writes.

REINDEX INDEX CONCURRENTLY orders_pkey;
Enter fullscreen mode Exit fullscreen mode

A fresh build packs every leaf to the fillfactor regardless of key order, so you get a dense index back. The v4 rows stay scattered in key order, but for most tables the recent rows are the ones that get read and written, and those are now together.

The timestamp is public now

This is the tradeoff you're actually making. A v4 UUID tells an outsider nothing. A v7 UUID tells anyone who sees it when it was created, to the millisecond. Paste one into any online decoder or run uuid_extract_timestamp() and there it is.

Whether that matters depends on where the ID shows up:

  • A signup ID in a public profile URL reveals when the account was created.
  • Order IDs on receipts or tracking pages let someone who collects a few of them estimate your order volume over time.
  • Document or invite IDs reveal when a thing was made, which can matter in legal or HR contexts.

RFC 9562 is measured about this. Its security section says the embedded timestamp poses "a very small attack surface" because it signals creation order without saying anything about the data itself. It also says plainly that if a UUID is used for any security operation, v4 should be used. That rules v7 out for anything that works as a secret: password reset tokens, API keys, magic links, unguessable share links. Those need their randomness in all 122 bits, not 74.

And the shift parameter is not a privacy feature. It adds the same interval to every value, so anyone who knows the real creation time of one record can work out the offset and apply it to the rest. If creation time is sensitive, the honest options are a random public ID or a separate opaque token, not a disguised timestamp.

Warning
"Unguessable" was never a property you should lean on for authorization, even with v4. But plenty of apps do exactly that with share links. If yours does, those IDs must stay v4 or become a separate random token. Switching them to v7 cuts the random portion from 122 bits to 74.

When v4 is still the right call

I'd make v7 the default for new UUID primary keys on Postgres 18. It's not a universal replacement, though. Keep v4 when:

  1. The value is a secret or capability. Tokens, invite codes, share links. Covered above, and it's the one case that isn't a judgment call.
  2. Creation time is sensitive and the ID is visible. If the ID leaves your system and the timestamp would tell someone something you'd rather they didn't know, v7 is a leak.
  3. The table is small and stays small. If the whole index fits comfortably in memory forever, the page-split and WAL costs are real but tiny. A 50,000-row lookup table won't care.
  4. You're keying something that isn't insert-heavy. The v4 penalty is mostly paid at insert time. A table written once and read a lot pays it once.

And sometimes neither UUID is the right primary key. If the ID never leaves the database and you don't need to generate it outside Postgres, bigint GENERATED ALWAYS AS IDENTITY is still smaller: the test above had it at 214 MB against 301 MB for v7 on the same 10 million rows. The common pattern is a bigint primary key internally plus a separate uuid column with a unique index for anything exposed publicly. That's more moving parts, though. For systems where IDs are created across many services, or where you want to know an ID before the insert, v7 gets you most of the bigint locality without giving up the UUID properties.

Generating v7 outside the database

One of the reasons people use UUIDs at all is to generate the ID in the application before touching the database. You can keep doing that with v7. The mainstream libraries support it:

:::tabs
@tab TypeScript

import { v7 as uuidv7 } from 'uuid';

const orderId = uuidv7(); // e.g. '01941f29-7c00-73e4-a310-744d2167fc5b'
await db.query(
  'INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3)',
  [orderId, customerId, totalCents],
);
Enter fullscreen mode Exit fullscreen mode

@tab Go

import "github.com/google/uuid"

id, err := uuid.NewV7()
if err != nil {
    return err
}
_, err = db.ExecContext(ctx,
    `INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3)`,
    id, customerID, totalCents)
Enter fullscreen mode Exit fullscreen mode

@tab Python

import uuid  # uuid.uuid7() needs Python 3.14+

order_id = uuid.uuid7()
cur.execute(
    "INSERT INTO orders (id, customer_id, total_cents) VALUES (%s, %s, %s)",
    (order_id, customer_id, total_cents),
)
Enter fullscreen mode Exit fullscreen mode

:::

Two things change when the app generates the IDs instead of Postgres.

First, each library makes its own monotonicity promise, and they differ. Python's docs say uuid7() uses a 42-bit counter to stay monotonic within a millisecond. Go's github.com/google/uuid documents NewV7 as millisecond-based; its source does put a sub-millisecond fraction in rand_a and keeps values increasing within one process, but that lives in comments on an unexported function, not in the documented API. Postgres uses the 12-bit clock fraction. For index locality none of that matters much; for "is this ordering strict," read your library's docs rather than assuming.

Second, ordering now depends on your app servers' clocks, not the database's. Ten servers with clocks a few milliseconds apart will produce keys that interleave slightly. That's still a tight cluster at the right edge of the index, so locality survives. A server with a badly skewed clock is a different story: its keys land further back in the index, and anything reading uuid_extract_timestamp() from them gets that server's idea of the time. One more reason to keep a real created_at populated by the database.

If you're on Postgres 17 or older and generating in the app today, there's no rush to change anything. The moment you're on 18, putting DEFAULT uuidv7() on the column gives you a sensible fallback for any insert path that doesn't supply an ID.

The short version

A primary key's job, from the index's point of view, is to make new rows cheap to insert and recent rows cheap to find. Random v4 keys do the opposite on both counts once a table outgrows memory: inserts go everywhere, pages split in half, and every checkpoint turns into a burst of full-page writes. On the Postgres 18 runs above, that meant a primary key about 30% bigger and more than twice the WAL per insert.

uuidv7() fixes that by putting a millisecond timestamp in front and a sub-millisecond clock fraction right behind it, so new keys pile up on the right edge like a sequence would. You keep global uniqueness and app-side generation, and you pay with a visible creation time.

So: new UUID primary key on Postgres 18, reach for uuidv7(). Existing v4 table, change the default and schedule a REINDEX CONCURRENTLY. Anything that works as a secret, leave on v4. And keep your created_at column, because the timestamp inside the ID was built for sorting, not for telling you when something happened.


Originally published at andriiboyko.com.

Top comments (0)