UUID Selection Guide: v1 vs v4 vs v7 and ULID Comparison

Three questions settle the choice: does it need time ordering, will the ID reach users, and can you trust every node's clock? The construction differences between ULID and UUID v7, plus the sorting-versus-privacy trade-off, live in ULID versus UUID. This guide stays on the version landscape and primary-key selection.

The short answer

Use UUID v7 for a new table's primary key: standard format, sortable, generatable without coordination. Use UUID v4 for unique identifiers that will never be sorted. Keep whatever an existing system uses — migrating a primary key for modernity is rarely worth the cost. Any UUID beats an auto-increment ID on a public endpoint, provided you know whether it leaks time. And security tokens are not UUID work.

128 bits, with the version nibble setting its character

A UUID is a 128-bit value written as an 8-4-4-4-12 hex string. Its value is uniqueness without central coordination. The specification moved to RFC 9562 in May 2024, superseding RFC 4122 and adding v6, v7 and v8.

Version Prefix Sortable Privacy When to use
v1 timestamp + MAC yes hardware fingerprint legacy compatibility only
v4 122 random bits no none general IDs, never a key
v6 reordered v1, time first yes still carries MAC fixing v1 ordering in place
v7 48-bit ms + 74 random bits yes millisecond time only new primary keys
v8 fully custom implementation-dependent implementation-dependent embedding business data

v1: the MAC address travels with the ID

Sixty timestamp bits at 100 ns precision, 48 MAC bits, 14 clock-sequence bits. It sorts by time and needs no random source, but it writes the generating machine's hardware fingerprint into every row. IDs from one host cluster together and correlate behaviour across systems; the MAC prefix reveals the NIC vendor; virtualised hosts may duplicate or reassign MACs and break uniqueness outright. Multiple threads on one machine also have to coordinate the clock sequence. New systems should not use v1 — v6 and v7 absorb the sorting requirement.

v4: randomness is fine, random keys are not

122 random bits, with six reserved for version and variant. Simplest to implement, no privacy surface, and collisions are ignorable: the probability only reaches 50% after 2.71×10¹⁸ values, roughly 85 years at a billion per second. The problem is the index. In InnoDB's clustered index, rows are physically ordered by key, so a random key means a new row can land anywhere in the B+ tree. A full target page then splits and half its rows move; fill factor drops and the index inflates; each insert pulls a different page into the buffer pool; hit rates fall. That makes v4 right for message IDs and temporary identifiers, and wrong for a write-heavy table's key.

v7: a millisecond prefix turns inserts back into appends

The first 48 bits are Unix milliseconds and the remaining 74 are random. Lexicographic order equals chronological order, so new rows append to the end of the index and both page splits and random I/O disappear. It is still a standard 128-bit UUID, fits a native UUID column, and needs no machine ID. Two edges matter: uniqueness inside one millisecond rests on randomness, and a clock moving backwards breaks monotonicity, so the generator must either keep incrementing within the millisecond or refuse the rollback.

v6 and v8: the transition and the escape hatch

v6 is v1 with the timestamp moved to the front: order finally matches time, but the MAC exposure remains, which is why adoption stayed low. v8 hands the whole 128 bits to the implementer for cases such as embedding business fields; ordinary projects have no reason to reach for it.

Five primary-key options

Auto-increment wins on index locality but requires a single writer. UUID v4 decentralises at the cost of index behaviour. v7 and ULID both sort and decentralise. Snowflake halves storage but adds machine-ID allocation and clock dependence. Existing systems should not migrate a primary key; selection only applies to new tables.

Security: random source, tokens, exposure

The random portion of v4 and v7 must come from a CSPRNG. Math.random() is predictable and unusable; reach for crypto.randomBytes() in Node, secrets rather than random in Python, SecureRandom in Java, crypto/rand in Go.

UUIDs optimise for uniqueness, not unpredictability, so never use one as a session token, CSRF token or API key: a time prefix narrows the guess space and the value carries no expiry, revocation or binding. Tokens need CSPRNG output of adequate length plus expiry and single-use handling.

Public endpoints deserve their own note: auto-increment IDs are enumerable and leak volume, while UUIDs hide counts but v1, v6 and v7 leak generation time.

Decision tree

Need a globally unique ID?
├── Need time-based sorting?
│   ├── Want standard UUID format? → UUID v7 ✅
│   └── Want shorter strings? → ULID ✅
├── No sorting needed?
│   └── UUID v4 (general purpose)
└── Need max performance and short ID?
    └── Snowflake (requires machine ID allocation)

Reproducible Results

The boundary between "random" and "deterministic" in one script:

import uuid
print(str(uuid.uuid4()))   # → fa933724-67af-42e0-908f-58cf0531f1b3 (different every run)
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'x') == uuid.uuid5(uuid.NAMESPACE_DNS, 'x'))
# → True (uuid5 is deterministic: same name, same value — a hash, not random)

So the choice sits between the two calls: uuid4 when you need unpredictability (session IDs, unguessable resource identifiers, with CSPRNG backing), uuid5 when you need stable recomputable IDs derived from a domain or URL. v1 leaks the MAC; v7 is the time-ordered variant. Generate and compare in the UUID generator.

Frequently Asked Questions

Should a new project pick UUID v7 or ULID?

Both use a timestamp prefix plus randomness, so both fix the index-fragmentation problem of random primary keys, and the practical difference is small. UUID v7 is part of RFC 9562 with growing native support (PostgreSQL 18 ships uuidv7(), with Java and Python ecosystems following) and fits a native UUID column. ULID uses Crockford Base32: 26 characters instead of 36, case-insensitive and friendlier in URLs. Rule of thumb: choose v7 when your database has a native UUID type or you need standards compliance; choose ULID when you want shorter strings and can store them as char(26)/text. Never pick v4 for a primary key.

Why does a random UUID (v4) primary key hurt index performance?

Because a B+Tree index stores rows physically in primary-key order. With auto-increment IDs every new row appends to the rightmost page: sequential writes, high cache hit rate. A v4 value is pure randomness, so each new row inserts at an arbitrary position, which costs you three ways: page splits, when the target page is full it is split in two and half the rows move; random I/O, since each insert must first pull a different index page into the buffer pool; and fragmentation, because page fill factor drops and the index grows, slowing both full scans and range queries. On tables in the millions of rows, v4 insert throughput can be a fraction of auto-increment. The timestamp prefix of v7/ULID makes new values monotonic, turning inserts back into sequential writes, so you get distributed generation and sequential writes at once.

Can I use a UUID as a security token such as a session ID or password-reset link?

Not recommended. A security token must be unpredictable, and only v4 with its 122 random bits comes close: v1, v6 and v7 all start with an inferable timestamp, so leaking a single value lets an attacker narrow the guess space for tokens issued in the same window. Even with v4 there are three problems: the token is generated by your own code, so quality depends on the implementation and a non-cryptographic source like Math.random() is indefensible; a UUID carries no built-in expiry, revocation or binding, all of which a session token needs; and UUIDs show up in logs, URLs and Referer headers, so the leak surface is wider than for a purpose-built token. Use a CSPRNG to generate at least 128 random bits (crypto.randomBytes(32).toString('hex') or the equivalent) plus expiry and single-use handling.

What are the risks of using the MAC address in UUID v1?

UUID v1 encodes the host MAC address directly into the final 12 hex digits, so every generating machine carries a globally unique hardware fingerprint, and that fingerprint travels with the ID into your logs, database and public APIs. Three risks follow: privacy and tracking, since IDs from one machine can be clustered to correlate user behaviour across systems (the Melissa virus was traced to its source machine through the MAC in a v1 UUID); information disclosure, because the MAC prefix reveals the NIC vendor and hints at your infrastructure; and broken uniqueness in virtualised environments where MACs may be duplicated or assigned by the host. Modern alternatives are v4 (pure random) or v7 (timestamp plus random, no MAC).

← Back to Blog