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 v4 | UUID v7 | |
|---|---|---|
| Structure | 122 random bits | 48-bit Unix ms timestamp + 74 random bits |
| Sortable by creation time | No | Yes (lexicographic = chronological) |
| B-tree index behavior | Random inserts → page splits, cache misses | Append-mostly → compact, fast |
| Leaks creation time | No | Yes (by design) |
| Standard | RFC 4122 / RFC 9562 | RFC 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
- The timestamp is sensitive. A v7 ID reveals when the row was created to anyone who sees the ID. Password-reset tokens, invite codes, or IDs exposed in URLs where creation time could leak business information are better served by v4.
- Unpredictability matters. v4's 122 random bits make guessing adjacent IDs hopeless. v7 narrows the search space for an attacker who knows the approximate creation time (74 random bits is still a lot — but it is a smaller margin).
- Legacy constraints. Some libraries and databases only recognize v4 validation patterns.
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.