UUID v4 vs v7: which should you use?

Short answer: v7 for database primary keys, v4 when creation time must stay secret. Here is the full reasoning.

The one-table summary

UUID v4UUID v7
Structure122 random bits48-bit Unix ms timestamp + 74 random bits
Sortable by creation timeNoYes (lexicographic = chronological)
B-tree index behaviorRandom inserts → page splits, cache missesAppend-mostly → compact, fast
Leaks creation timeNoYes (by design)
StandardRFC 4122 / RFC 9562RFC 9562 (2024)

Why v7 wins for database primary keys

Every insert with a purely random v4 key lands at a random position in the index. At scale this causes constant B-tree page splits, write amplification, and poor cache locality — a well-documented cause of slow inserts in PostgreSQL and MySQL. v7 keys are generated in (roughly) increasing order, so inserts append to the right-hand edge of the index like an auto-increment integer, while remaining globally unique and generatable on any client without coordination.

As a bonus, v7 keys make “recent items first” queries cheap: ordering by the primary key approximates ordering by creation time.

When v4 is still the right choice

Practical recommendation

Default to v7 for anything stored and indexed (primary keys, event IDs, log records) and v4 for anything secret or externally visible where timing shouldn't leak. Both are 128-bit standard UUIDs, so switching costs nothing at the schema level — a uuid column holds either.

Try both right now: generate UUID v7 or UUID v4 in your browser — free and offline.