A primary key looks like the most boring choice in a schema, until the table has fifty million rows and every insert is slow. The reason is often the ID. This article opens up three common formats, UUID v4, UUID v7 and ULID, shows which bits are random and which are a clock, and gives the numbers behind two things people argue about: collisions and index performance.
Three formats, one 128-bit space
All three are 128 bits. They differ in how those bits are filled.
| UUID v4 | UUID v7 | ULID | |
|---|---|---|---|
| Layout | 122 random bits, 6 fixed bits | 48-bit time, 12-bit counter, 62 random bits, 6 fixed bits | 48-bit time, 80 random bits |
| Sorts by creation time | no | yes | yes |
| Text form | 36 characters, hex and hyphens | 36 characters, hex and hyphens | 26 characters, Crockford Base32 |
| Standard | RFC 9562 (earlier RFC 4122) | RFC 9562 | a community specification |
| Reveals the creation time | no | yes | yes |
The UUID Generator makes all three, up to 1,000 at a time. Here is what the text of each means.
UUID v4: read the version in the text
A v4 UUID looks like xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx. The 4 in the third group is the version. The y is the variant and is always one of 8, 9, a or b. Everything else, 122 bits, comes from a random source. That is why you can check at a glance whether a string is a v4: the character after the second hyphen group must be 4 and the first character of the fourth group must be 8, 9, a or b.
UUID v7: a timestamp first
A v7 UUID is tttttttt-tttt-7mmm-yrrr-rrrrrrrrrrrr. The first twelve hex digits are the time in milliseconds since 1970. After the version 7 comes a 12-bit counter, the variant, and 62 random bits. These three, made for the instants 1,700,000,000,000, 1,700,000,000,001 and 1,700,000,000,002 milliseconds, show the shape:
018bcfe5-6800-7000-8911-0859aa69af2a
018bcfe5-6801-7001-ba6f-fae8e2ea7727
018bcfe5-6802-7002-aa32-643d96abf6f1
Read the first twelve hex digits as one number: 018bcfe56800 is 1,700,000,000,000. Put that into the Unix timestamp converter and it prints 2023-11-14T22:13:20.000Z. The second and third IDs are one and two milliseconds later, and the three sort in order even as plain text. The counter (000, 001, 002 after the 7) keeps the IDs of one millisecond in order too, which matters when a program creates many IDs in a loop.
ULID: the same idea in a shorter text
A ULID is a 48-bit millisecond timestamp followed by 80 random bits, written in Crockford Base32 (digits and capital letters without I, L, O and U). The same instant as above, with the random part set to zero to show the structure, is:
01HF7YAT000000000000000000
01HF7YAT010000000000000000 <- one millisecond later
The first ten characters are the time and the last sixteen are the random part, so ULIDs also sort in time order as text. They are 26 characters instead of 36, which is nicer in URLs, but a database uuid type will not accept them.
Why the order matters for a database
Most databases keep a primary key in a B-tree index. If new keys are random, as with v4, each insert goes to a random place in the tree: the page that holds it has to be read from disk if it is not in memory, and a full page is split in two. On a large table most pages are not in memory, so every insert pays for a read, and the index grows half empty after the splits. With a time-ordered key such as v7, new keys are larger than all older ones and always go to the end of the index: the page being written stays in memory, pages fill completely, and range queries on “recent rows” read pages that sit next to each other.
How big the effect is depends on the database, the row size and the memory, so measure it on your own workload. The rule that holds everywhere is the direction: random keys cost more as the table outgrows memory, and time-ordered keys do not.
How likely is a collision?
With b bits of randomness, the number of IDs you must create for a 50% chance of one collision is about 1.18 × 2^(b/2) (the birthday problem). For the 122 random bits of v4 that is 1.18 × 2^61, about 2.7 × 10^18, or 2.7 quintillion. If you created a billion UUIDs every second, it would take about 86 years to reach that point. For the 62 random bits that v7 has in every millisecond, a collision needs a few billion IDs within the same millisecond and the same counter value, which no single machine does.
So collisions from chance are not a design problem. Collisions from bad setups are: two virtual machines cloned from one image with the same random state, or a library that seeds a weak generator with the time. Use a generator that takes its bytes from the operating system’s secure source, which is what the browser’s crypto.getRandomValues does.
What a time-ordered ID gives away
A v7 or a ULID tells anyone who sees it when the row was created, to the millisecond. In a public URL that can reveal when an account was made or how fast you create orders. It is also not a secret: the time and the counter are predictable and only 62 bits are random. Use v4 for identifiers that should say nothing, and use a long random token (see the password generator for the idea) for anything that grants access.
Choosing
- New table, one database, you want fast inserts: UUID v7.
- The ID must not reveal its age, or you need the most random format: UUID v4.
- You want a shorter text for URLs and the column is a string anyway: ULID.
- You already have v4 keys: you do not need to migrate. Add v7 for new tables, and keep v4 where an old system expects it.
Store whichever you pick in a native uuid column (16 bytes), not as a 36-character string. For related background on numbers and bytes, read JSON, CBOR, MessagePack and Protobuf, where the same 16 bytes take a very different amount of space in text and in binary.
Everything you generate or paste into these tools is processed in your browser and never uploaded.
Frequently asked questions
Which should I use as a primary key: UUID v4, UUID v7 or ULID?
For a new table, UUID v7: it sorts by creation time, so new rows land at the end of the index, and it is the standard format (RFC 9562) that databases and libraries support. Use v4 when the ID must not reveal when it was created. A ULID is a good choice when a shorter text form (26 characters) matters, but it is not a UUID, so a uuid column type will not accept it.
Can two UUID v4 values collide?
In theory yes, in practice no. With 122 random bits you would have to create about 2.7 quintillion (2.7 × 10^18) of them for a 50% chance of a single collision. The real risk is not the maths but a bad random source: a generator that is seeded the same way on two machines produces the same IDs.
Does a UUID v7 reveal when a row was created?
Yes. The first 48 bits are the Unix time in milliseconds, so anyone who sees the ID can read the creation time with a timestamp converter. If the creation time is sensitive, or you do not want users to see how many records you create per day, use v4.
Is a UUID a good secret, for example in a password-reset link?
Not v7: only 62 of its bits are random, and the rest is a clock and a counter. A v4 from a secure random source has 122 random bits, which is enough, but some libraries fill it from a weak generator such as Math.random. For a token that grants access, generate random bytes with a cryptographic source and treat the length as a security setting.
How should I store a UUID in a database?
In a native uuid column or as 16 bytes of binary, not as a 36-character string. The text form takes more than twice the space in every table and index and compares more slowly. Convert to the hyphenated text only at the edges, in logs and APIs.
More guides
- CIDR notation: why a /31 has two usable hosts, what a /32 is for, and the subnet mistakes to avoid
- Hashing is not encryption: what a hash can do, and why passwords need bcrypt
- Unix timestamps: seconds, milliseconds or microseconds, and the dates where they go wrong
- Base64 is not encryption: what it does, and the bugs it causes
- JSON, CBOR, MessagePack and Protobuf: the same data in four sets of bytes
- Regex backtracking: how one innocent pattern can freeze a server (ReDoS)
- URL encoding pitfalls: %20 or +, double encoding, and the characters that break links
- Cron and time zones: why your 02:30 job runs twice or never
- CSV edge cases: quotes, newlines, delimiters and the leading zero
- Why JSON silently changes your big numbers (and how to stop it)
- JWT pitfalls: decoding a token is not verifying it
- YAML surprises: the Norway problem, octal numbers and version strings