How UUID versions differ, the real collision odds of v4, why random UUIDs hurt database indexes, and when time-ordered v7 is the better choice.
A UUID (universally unique identifier) is a 128-bit value usually written as 32 hexadecimal digits in five groups: 8-4-4-4-12. Its purpose is to let independent systems create identifiers without coordinating with a central counter, so two services, two devices or two offline clients can mint IDs that will not clash when their data is merged.
The first digit of the third group is the version. In 550e8400-e29b-41d4-a716-446655440000, the 4 marks a version 4 UUID. The first digit of the fourth group encodes the variant, which for standard UUIDs is 8, 9, a or b.
Version 4 fills 122 of the 128 bits with random data. It is the default in most libraries and the right choice when you need an unguessable identifier with no embedded information. Generate it from a cryptographically secure source (crypto.randomUUID() in browsers and Node.js, uuid.uuid4() in Python); Math.random()-based implementations are not safe for identifiers that must not be predicted.
Collision risk is negligible in practice. You would need to generate roughly 2.7 quintillion v4 UUIDs before reaching a 50% chance of a single collision. A broken random number generator is a far more realistic risk than chance.
Version 1 combines a 60-bit timestamp with a clock sequence and the generating machine's MAC address. It was popular because IDs from one machine sort roughly by creation time. Its downsides are that it leaks the hardware address and creation time of every record, and its timestamp bits are laid out in an order that does not sort correctly as a string.
New systems rarely have a reason to choose v1. If you want time ordering, v7 provides it without exposing hardware details.
Version 7, standardized in RFC 9562 in 2024, puts a 48-bit Unix timestamp in milliseconds at the front and fills the rest with random bits. IDs created later sort after IDs created earlier, both numerically and as strings, while remaining practically unique across machines.
That ordering matters for databases. Random v4 primary keys insert at random positions in a B-tree index, which causes page splits, poor cache locality and index bloat on large tables. Time-ordered v7 keys append near the end of the index like an auto-increment integer, which keeps writes fast.
Use v7 for database primary keys and any ID you will sort or range-scan by creation time. Use v4 for tokens, public identifiers where creation time should not be inferable, and anywhere ordering does not matter. Avoid v1 in new designs. Versions 3 and 5 are deterministic (a hash of a namespace and a name) and are useful when the same input must always map to the same ID.
Whichever version you choose, store UUIDs in a native UUID column or as 16 raw bytes rather than a 36-character string. It halves storage, speeds up comparisons and prevents case and formatting inconsistencies.