UUID v4 vs v7 vs ULID: Which ID Format Should You Use?
Not all unique identifiers are created equal. Understand UUID v4, v7, ULID, and CUID — and how each choice affects your database performance.
Why Not Just Use Auto-Increment?
A database sequence is the simplest ID generator, and for a single database it is often the right one. It stops fitting when IDs must be created in several places at once — multiple services, shards, offline mobile clients, or a browser that creates a record before it reaches the server — or when you don't want URLs like /invoices/1042 to reveal how many invoices exist. A 128-bit identifier that any machine can generate without coordination solves those problems; the open question is which format.
Reading a UUID
A UUID is 128 bits written as 32 hex digits in groups of 8-4-4-4-12. Two positions are fixed by the standard: the first digit of the third group is the version, and the first digit of the fourth group holds the variant (8, 9, a or b for standard UUIDs).
01a1c059-90b1-7fe0-a92a-085069df9f1b
^ ^
| variant: a (binary 10xx)
version: 7The current specification is RFC 9562 (May 2024), which obsoletes RFC 4122. It keeps versions 1–5, adds versions 6, 7 and 8, and defines the Nil UUID (all zeros) and the Max UUID (all f). Reading the version in code:
const version = (uuid) => parseInt(uuid[14], 16);
version("01a1c059-90b1-7fe0-a92a-085069df9f1b") // 7
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
UUID_RE.test(crypto.randomUUID()) // true
UUID_RE.test("00000000-0000-0000-0000-000000000000") // false: Nil has no versionIf your system uses the Nil UUID as a sentinel, allow it explicitly — this regex rejects it.
The Versions at a Glance
| Version | Built from | Sortable by time | Status |
|---|---|---|---|
| v1 | 60-bit timestamp (100 ns since 1582) + clock sequence + node ID (often the MAC) | Not as a string: the low time bits come first | Legacy; leaks the host's MAC address |
| v2 | DCE Security: v1 with a local user/group ID | No | Rarely implemented |
| v3 | MD5 of namespace + name | No (deterministic) | Prefer v5 |
| v4 | 122 random bits | No | The default almost everywhere |
| v5 | SHA-1 of namespace + name | No (deterministic) | Use for stable IDs derived from names |
| v6 | v1 fields reordered, most significant time first | Yes | Only for systems migrating from v1 |
| v7 | 48-bit Unix time in ms + 74 random bits | Yes (millisecond) | Recommended for new time-ordered IDs |
| v8 | Layout defined by the vendor | Up to you | Experimental or custom formats |
UUID v4: Random and Simple
Version 4 fills every bit except the six version and variant bits with random data. Modern platforms generate it from a cryptographically secure source:
crypto.randomUUID()
// e.g. "4b23f547-0e63-4230-89d8-3a667c6aca18"crypto.randomUUID() is available in all current browsers and in Node.js (as a global since Node 19). In browsers it only exists in secure contexts, so a page served over plain http:// from a LAN IP will throw crypto.randomUUID is not a function; localhost counts as secure.
How likely is a collision?
With 2122 possible values, the birthday bound gives the number of v4 UUIDs you must generate before a duplicate becomes likely. For a 50% chance it is about 2.7 × 1018; for a one-in-a-billion chance it is about 1014 — a hundred trillion IDs. In practice duplicates come from bugs, not from the math: generators built on Math.random(), VM or container snapshots that restore the same RNG state, or code that copies an ID instead of creating a new one. A unique constraint on the column turns those bugs into errors instead of silent data corruption.
Unique is not the same as secret. RFC 9562 says implementations should not assume UUIDs are hard to guess, and you cannot tell from the outside whether a given UUID came from a secure generator. For password-reset links or API keys, use a dedicated random token (for example 32 bytes from crypto.getRandomValues).
UUID v7: Time-Ordered
Version 7 puts the Unix timestamp in milliseconds in the first 48 bits, then the version, 12 random bits, the variant and 62 more random bits. Because the timestamp comes first, v7 UUIDs generated later sort later, both as bytes and as lowercase strings. Generating one by hand shows the layout:
function uuidv7() {
const bytes = crypto.getRandomValues(new Uint8Array(16));
const ms = BigInt(Date.now());
for (let i = 0; i < 6; i++) bytes[i] = Number((ms >> BigInt(8 * (5 - i))) & 0xffn);
bytes[6] = (bytes[6] & 0x0f) | 0x70; // version 7
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10xx
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}And reading the creation time back out of any v7 UUID:
const uuidv7Time = (uuid) =>
new Date(parseInt(uuid.replace(/-/g, "").slice(0, 12), 16));
uuidv7Time("01a1c059-90b1-7fe0-a92a-085069df9f1b").toISOString()
// "2026-11-09T12:47:37.649Z"The first 12 hex digits are a millisecond Unix timestamp you can paste into the timestamp converter. Two consequences follow:
- v7 IDs reveal when a record was created. For internal primary keys that rarely matters; for IDs shown to users (order numbers, account IDs) consider whether it does.
- Order inside one millisecond is random with the simple generator above. Three IDs created in the same millisecond on our test machine came out as
…7de2…,…7762…,…71de…— not in creation order. RFC 9562 (section 6.2) describes fixes such as using the 12rand_abits as a counter; good libraries implement one of them. If strict ordering matters, check that yours does.
Native support is spreading: PostgreSQL 18 includes a uuidv7() function and Python 3.14 added uuid.uuid7(). In Node.js, the uuid npm package exports v7().
UUID v5: The Same Input Always Gives the Same ID
Version 5 hashes a namespace UUID plus a name with SHA-1 and keeps 122 bits of the result. It is useful when several systems must derive the same ID for the same thing without talking to each other — a URL, a DNS name, an external product code. Verified against Python's uuid.uuid5:
const crypto = require("node:crypto");
function uuidv5(name, namespace) {
const ns = Buffer.from(namespace.replace(/-/g, ""), "hex");
const b = crypto.createHash("sha1")
.update(Buffer.concat([ns, Buffer.from(name, "utf8")]))
.digest().subarray(0, 16);
b[6] = (b[6] & 0x0f) | 0x50; // version 5
b[8] = (b[8] & 0x3f) | 0x80; // variant
const h = b.toString("hex");
return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
}
const DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; // namespace from the RFC
uuidv5("python.org", DNS) // "886313e1-3b8a-5372-9b90-0c9aee199e5d"Because the output is predictable from the input, never use v5 for anything that should be unguessable, and remember that the name is exact: Example.com and example.com give different UUIDs, so normalise before hashing.
ULID: Same Idea, Different Text Format
ULID predates v7 and has nearly the same layout: 48 bits of millisecond timestamp and 80 random bits. The difference is presentation — 26 characters of Crockford Base32 (digits and uppercase letters without I, L, O and U), such as 01HZ9VKPD4R5F6G7H8JK9MABCD. That is shorter than a 36-character UUID, has no hyphens, and sorts correctly as a plain string. The ULID spec also defines a monotonic mode for IDs created in the same millisecond.
ULID is a community specification, not an RFC, so databases have no ULID type. Since both formats are 128 bits, many teams store ULIDs in a native uuid column and only render them as Base32 at the edges. For a new project with no existing ULID usage, v7 gives the same ordering benefits with wider native support.
Why Ordering Matters in Databases
Most primary keys are stored in a B-tree index. With random v4 keys, each insert lands on a random leaf page, so the whole index must stay in memory to keep inserts fast, pages split in the middle and end up partly empty, and recently created rows are scattered across the index. With v7 or ULID keys, new rows go to the right-most pages, much like an auto-increment column. The size of the effect depends on the database, table size and available memory, so measure with your own workload rather than trusting a single benchmark figure — but for large, write-heavy tables the difference is real enough that time-ordered IDs are the usual recommendation.
Storage mistakes that cost more than the version choice
- Storing UUIDs as text.
VARCHAR(36)uses more than twice the 16 bytes of PostgreSQL'suuidtype or MySQL'sBINARY(16), in the table and in every index that includes it. - MySQL's
UUID()is version 1. Its string form is not time-ordered;UUID_TO_BIN(UUID(), 1)swaps the time fields so the binary value is. Do not apply that swap flag to v4 or v7 values. - Case-sensitive comparisons. Some tools print uppercase (SQL Server shows
uniqueidentifiervalues that way). Normalise to lowercase before comparing strings, or compare parsed values. - Microsoft GUID byte order. .NET's
Guid.ToByteArray()stores the first three groups little-endian, so the same GUID has different raw bytes in .NET and in RFC order. This shows up as “the IDs don't match” when exchanging binary UUIDs between platforms.
Which One Should You Use?
| Situation | Choose |
|---|---|
| New table, IDs generated by the app or database | UUID v7 |
| Small tables, or IDs that must not reveal creation time | UUID v4 |
| Same input must always map to the same ID | UUID v5 (with normalised names) |
| Existing system already using ULIDs | Keep ULID; store as 128-bit binary |
| Security tokens, reset links, API keys | None of these — use a random token |
| Single database, internal IDs, no client-side creation | A sequence/identity column is still fine |
For test fixtures and quick experiments, the UUID generator creates version 4 UUIDs in bulk in your browser with crypto.getRandomValues. For realistic rows that need IDs alongside names and emails, see the guide to generating fake test data.
Generate UUIDs in your browser
Create one or hundreds of random v4 UUIDs, copy them or download them — nothing is sent to a server.