UUID v4 vs v7: which should you use for database keys?
Every distributed system eventually needs identifiers that can be generated anywhere without coordination. UUIDs solve that. But the version you pick has real consequences for database performance, and the conventional answer changed recently.
What v4 gives you
A v4 UUID is 122 bits of pure randomness. Collisions are practically impossible, the value reveals nothing about when or where it was created, and every language can generate one in one line. For request IDs, file names, idempotency keys, and anything that is not a database index, v4 is the right default and will stay that way.
Generate UUIDsGenerate v4 UUIDs in bulk and secure random tokens with custom length and character sets.Why v4 hurts as a primary key
Databases keep primary keys in sorted indexes (B-trees). Sequential keys append to the end of the index, which is fast. Random keys land everywhere, which means page splits, cache misses, and indexes that grow faster than the data. On a table with millions of inserts, the difference between sequential and random keys is measurable in both write latency and index size.
What v7 changes
UUID v7, standardized in RFC 9562, puts a millisecond timestamp in the first 48 bits and randomness in the rest. Keys generated around the same time sort near each other, so the index grows mostly by appending, like an auto increment key, while staying globally unique and generatable anywhere. For new systems using UUIDs as primary keys, v7 is the better choice.
The honest comparison
- v4: maximum randomness, zero information leakage, index fragmentation. Use for everything except database keys.
- v7: time ordered, index friendly, leaks creation time. Use for database primary keys.
- Auto increment integers: smallest, fastest, but require central coordination and leak row counts. Still fine for single database applications.
One caveat on v7: the embedded timestamp means anyone who sees the ID knows roughly when the record was created. For most data that is harmless. For some (medical records, anonymous reports) it is not, and v4 remains the right call.