UUID v4 vs v7: Sort Order, Index Locality and What Leaks
| v4 | v7 | v1 | |
|---|---|---|---|
| Content | 122 random bits | 48-bit Unix ms timestamp, then random bits | 60-bit Gregorian 100 ns timestamp, clock sequence, node id |
| Sorts by creation time | No | Yes (as text or as bytes) | No: the time fields are stored low-part first |
| Reveals creation time | No | Yes, to the millisecond | Yes, to 100 ns |
| Reveals the host | No | No | Traditionally the MAC address |
Use the decoder to see this for any value. The RFC 9562 example values decode to 2022-02-22T19:22:22Z for all three of its v1, v6 and v7 samples.
Why v7 suits primary keys
A B-tree index inserts a random v4 at a random leaf, so inserts touch the whole index and split pages everywhere. A v7 begins with the time, so new keys land at the right edge, as with an auto-increment integer. Measure it on your own database before relying on a figure: the effect depends on engine, page size and row width.
How the generator orders a batch
Within one millisecond a v7 has nothing time-like left to order by, so the generator uses the 12-bit rand_a field as a counter (RFC 9562 section 6.2, method 1), starting at a random value so the next batch does not begin at zero. If a batch outruns the counter inside one millisecond, the timestamp advances by one millisecond instead of repeating. The result is that values from one call are strictly increasing; values from different machines are ordered only to the millisecond.
What v7 leaks
The creation time is readable by anyone holding the UUID. If an identifier will be public and its creation time is sensitive (account creation, record insertion), a v4 reveals nothing and v7 reveals the time. That is a property of the format, not a flaw in a generator.
Collisions
v4 collisions are possible in theory and negligible in practice if the random source is a CSPRNG. A bad random source is the real risk, which is why the generator uses crypto.getRandomValues and not Math.random.