UUID v4 vs UUID v7
UUID v4 has been the default unique identifier for a decade, but UUID v7 (standardized in RFC 9562) is rapidly replacing it for database keys - PostgreSQL 18 even ships a native uuidv7() function. The difference comes down to one question: should your IDs sort by creation time?
How each version is built
UUID v4 fills 122 of its 128 bits with random data - every ID is completely independent of every other.
UUID v7 spends its first 48 bits on a Unix millisecond timestamp and fills the rest with random data. Two v7 IDs generated a millisecond apart will sort in generation order; the random tail keeps them unique within the same millisecond.
Why v7 is better for database keys
Databases store primary keys in B-tree indexes, which perform best when new entries land near the end of the index. Random v4 keys insert at random positions, splitting pages and bloating the index as tables grow. v7 keys arrive in near-sequential order, so inserts stay fast and the index stays compact - the same reason auto-increment integers perform well, without giving up global uniqueness.
This is not theoretical: index fragmentation from v4 primary keys is a well-documented cause of write slowdowns in large PostgreSQL and MySQL tables.
When v4 is still the right choice
A v7 UUID reveals exactly when it was created - anyone who sees the ID can decode the timestamp. For invite codes, password-reset tokens, or public identifiers where creation time is sensitive, v4's opacity is a feature. v4 also remains the safe choice when your platform has no v7 support and pulling a dependency isn't worth it.
- New database primary keys → v7
- Distributed events that need time-ordering → v7
- Public tokens where creation time must not leak → v4
- Maximum compatibility with old libraries → v4
Doing it in code
// Node 20+ / modern runtimes
import { v7 as uuidv7 } from 'uuid';
uuidv7(); // "0197b3f0-5e7a-7cc3-a2ae-5c2fbe23d3b4"Frequently Asked Questions
Is UUID v7 an official standard?
Yes. RFC 9562, published in May 2024, defines UUID versions 6, 7, and 8 and obsoletes the original RFC 4122. UUID v7 is the recommended time-ordered version for new applications.
Can I mix v4 and v7 UUIDs in the same column?
Technically yes - both are valid 128-bit UUIDs and any uuid column accepts them. But you lose the ordering benefit for the v4 rows, so pick one version per table and stick with it.
Does UUID v7 leak information?
Only its creation timestamp (millisecond precision) - the remaining 74 bits are random. If knowing when a record was created is acceptable, v7 is safe; if not, use v4.