ToolsWhisper

UUID v7 vs v4 as a Database Primary Key

Random v4 UUIDs scatter writes across your index and cause page splits. Version 7 sorts by time and fixes it, without giving up global uniqueness.

FrankUpdated 4 min read
Two bar charts: random UUID v4 bars in red and steadily rising UUID v7 bars in green, comparing database key ordering

If you use random UUIDs as primary keys on a large table, your index is doing significantly more work than it needs to. Version 7 fixes this with a small change to how the bytes are laid out.

The problem with v4

A version 4 UUID is 122 bits of randomness. That is excellent for uniqueness — you can generate them on any machine with no coordination and never collide in practice.

It is also the worst possible ordering for a B-tree index.

Database indexes store rows in sorted order across fixed-size pages. Insert sequential keys and every new row lands at the end: one page stays hot in memory, it fills, a new one is allocated. Cheap.

Insert random keys and every write lands in a different, arbitrary page. That means:

  • Random I/O instead of sequential. The page you need is rarely the one already in memory.
  • Page splits. Inserting into a page that is already full splits it in two, leaving both half-empty.
  • Index bloat. Half-empty pages mean the index consumes far more space than the data warrants.
  • A cache that cannot help you. With writes spread across the whole index, no working set fits in the buffer pool.

On a small table none of this matters. At tens of millions of rows it is very noticeable.

What v7 changes

Version 7 puts a 48-bit big-endian Unix millisecond timestamp in the first six bytes, then fills the rest with randomness.

0192f8a4-3d2e-7c91-b4a5-6f8e2d1c9b3a
└──────┬──────┘ │
   timestamp    └ version

Because the timestamp is first and big-endian, sorting the identifiers sorts them by creation time. New rows append to the end of the index, exactly like an auto-increment integer — but you keep the properties that made UUIDs attractive:

  • Generate them anywhere, with no round trip to the database
  • No coordination between services
  • No sequence to leak your row count to users

You can generate both versions with our UUID generator and compare the shapes directly.

What is inside a v7 UUID

The layout is defined in RFC 9562, which replaced the older RFC 4122. Of the 128 bits, 48 are the timestamp, 4 are the version, 2 are the variant and the remaining 74 are random. A v4 UUID has 122 random bits, so v7 trades some randomness for ordering. Because the timestamp already separates identifiers created in different milliseconds, only the ones created within the same millisecond depend on those 74 random bits to stay distinct, and that is still an enormous space.

You can read the creation time straight out of the first twelve hex digits:

const ms = parseInt(uuid.replace(/-/g, "").slice(0, 12), 16);
new Date(ms).toISOString();
// the example above: 2024-11-04T19:26:06.126Z

Several IDs in one millisecond

Two v7 UUIDs generated in the same millisecond share a timestamp and differ only in their random bits, so their order within that millisecond is arbitrary. For index locality this does not matter. If you need strict ordering, RFC 9562 describes optional methods for keeping a generator monotonic, such as a counter, and many libraries offer a monotonic mode. Check that yours does before relying on it, and never use the identifier as the only record of insertion order.

Storage matters as much as the version

A UUID is 16 bytes, but its familiar text form is 36 characters, more than twice the size. Store it in the database's native type, such as uuid in Postgres or BINARY(16) in MySQL, not in a text column. In engines like InnoDB every secondary index carries a copy of the primary key, so a bulky key makes every index larger. Switching from v4 to v7 will not recover that space if the column is stored as text.

How much does it matter for your table

If the whole index fits in memory, random inserts are cheap and you may never notice a problem. The pain starts when the index outgrows the buffer pool and each insert has to fetch a cold page from disk. The honest way to find out is to insert a few million rows with each version on your own hardware and compare insert time and index size. That is more convincing than any rule of thumb, including the one in this article.

The trade-offs

A v7 UUID leaks its creation time. Anyone holding one can read the millisecond it was generated. Usually harmless, occasionally not — if the identifier is exposed publicly and creation time is sensitive, that matters.

Ordering is only as good as the clock. Identifiers generated on different machines interleave according to those machines' clocks. Fine for index locality, not a substitute for a real ordering column.

Not every database has native support. Postgres added uuidv7() in version 18; before that you generate it in the application or with a small SQL function. Either works — the format is just bytes.

Practical guidance

Use v7 for anything that becomes a primary key or is written in volume.

Use v4 when the value is a public token, a session identifier, or anything where an embedded timestamp would tell someone something you would rather they did not know.

And if you are on an existing table with billions of v4 keys, migrating is rarely worth it on its own. Apply v7 to new tables and move on.

Other time-sortable options

UUID v7 is not the only answer to the ordering problem. ULIDs pack a 48-bit timestamp and 80 random bits into a sortable 26-character string. Snowflake-style IDs fit a timestamp, a worker number and a sequence into 64 bits, which suits systems that want a plain integer key. All of them rely on the same idea: put the time first so new rows land at the end of the index. v7 has the advantage of being a standard UUID, so existing UUID columns, drivers and tooling accept it unchanged.

Tools used in this article

Read next