UUID v4 vs v7: Which Should You Use?
v4 is fully random. v7 embeds a timestamp so it sorts chronologically. The right choice depends almost entirely on whether you're using it as a database primary key.
How each version is built
UUID v4 is 122 bits of cryptographically random data (the other 6 bits are fixed version/variant markers). There's no structure to exploit and no information leakage - every v4 UUID looks completely unrelated to the next.
v4: 3fa85f64-5717-4562-b3fc-2c963f66afa6
\_______random_______/ \____random____/
UUID v7 packs the current Unix timestamp (milliseconds since epoch) into the first 48 bits, followed by 74 bits of randomness. Because the timestamp comes first, v7 UUIDs generated later always sort after ones generated earlier.
v7: 018f4d2e-1c3a-7abc-9def-1234567890ab
\__48-bit timestamp__/ \___random___/
Side-by-side comparison
| UUID v4 | UUID v7 | |
|---|---|---|
| Sortable by creation time | No | Yes |
| Leaks creation timestamp | No | Yes (to the millisecond) |
| Database index fragmentation | High - random inserts scatter across a B-tree | Low - inserts append roughly in order, like an auto-increment |
| Collision resistance | 122 random bits | 74 random bits (still effectively collision-free at normal scale) |
| Language/library support | Universal - every UUID library since the early 2000s | Growing fast, but not yet in every standard library (e.g. .NET, older Java) |
| Best for | Tokens, session IDs, anything where unpredictability matters | Database primary keys, event logs, anything inserted in high volume |
Why sortability matters for primary keys
Most relational databases store rows physically ordered by their primary key (a clustered index in SQL Server, the InnoDB primary key in MySQL). Inserting random v4 values means every insert lands in a random spot in that ordering, causing page splits and index fragmentation that get worse as the table grows. A v7 key, like an auto-increment integer, mostly appends to the end - much cheaper to maintain, while still giving you a globally unique, coordination-free ID.
Why v4 is still the safer default for anything user-facing
If a UUID is exposed externally - in a URL, an API token, a password-reset link - a v7 value leaks exactly when it was created, which can be a privacy or security concern (e.g. it reveals account creation order). For these cases, stick with v4.
Quick decision guide
- Database primary key, high insert volume → v7
- Public-facing token, session ID, or anything where timing shouldn't leak → v4
- Not sure / general purpose → v4 (the safe, universally-supported default)
Generate either version instantly with the UUID/GUID generator above, or see the UUID Format & Size page for how the bits are laid out.