UUID v4 vs UUID v7: Which Unique Identifier Should You Use for Database Keys?

Use UUID v7 for database primary keys and clustered indexes where time ordering prevents B-tree page splits and index fragmentation (RFC 9562). UUID v7 embeds a 48-bit millisecond timestamp followed by 74 entropy or counter bits. Use UUID v4 only when creation timestamps must remain secret to avoid leaking chronological metadata.
Universally Unique Identifiers (UUIDs) are standard 128-bit labels used across distributed software systems, database tables, and message queues to identify entities without centralized coordination. For nearly two decades, software developers defaulted to UUID version 4 (random) specified in RFC 4122. However, using randomly distributed 128-bit values as primary keys in relational databases introduces severe performance bottlenecks: massive B-tree index fragmentation, frequent page splits, and excessive random disk input/output (I/O).
In May 2024, the Internet Engineering Task Force (IETF) published RFC 9562: Universally Unique IDentifiers (UUIDs), officially obsoleting RFC 4122. RFC 9562 introduced UUID Version 7 (v7), an enhanced identifier format featuring time-ordered sortability tailored specifically for modern database indexing and distributed architectures.
You can generate both random v4 and time-ordered v7 identifiers in bulk and inspect decoded timestamps using our browser-based UUID Generator. If you are building authentication architectures or cryptographic tokens, you can also explore token payloads with our JWT Decoder or generate secure master secrets with our Password Generator.
What Standards Govern UUID v4 and UUID v7?
The authoritative standard for UUID architecture is RFC 9562, which obsoleted RFC 4122 in May 2024.
- UUID Version 4 (§5.4): Uses 122 bits of cryptographic randomness, a 4-bit version (
0100), and 2 variant bits (10). - UUID Version 7 (§5.7): Features a 48-bit Unix timestamp in milliseconds, a 4-bit version (
0111), 12 bits of counter or randomness (rand_a), 2 variant bits (10), and 62 bits of randomness (rand_b).
How Do the 128-Bit Layouts Compare?
Both UUID v4 and UUID v7 are 128-bit (16-byte) numbers formatted in the canonical 8-4-4-4-12 hexadecimal string representation with four hyphens (36 characters total). However, their internal bit allocations differ substantially.
The following table summarizes the precise bit allocation defined in RFC 9562:
| Property | UUID v4 (RFC 9562 §5.4) | UUID v7 (RFC 9562 §5.7) |
|---|---|---|
| Primary Purpose | Unguessable random identification | Time-ordered database primary keys |
| Timestamp Field | None (0 bits) | 48-bit unsigned integer (unix_ts_ms) |
| Timestamp Resolution | Not applicable | Millisecond precision |
| Version Nibble | 0100 (4 bits, value 4) | 0111 (4 bits, value 7) |
| Sub-Timestamp Field | Part of random payload | 12-bit rand_a (entropy or monotonic counter) |
| Variant Bits | 10 (2 bits, RFC variant) | 10 (2 bits, RFC variant) |
| Trailing Random Bits | 62 bits | 62-bit rand_b (entropy) |
| Total Entropy / Randomness | 122 bits | 74 bits (or 62 bits + 12-bit counter) |
| Lexicographical Sortable | No (random distribution) | Yes (chronological generation order) |
| Metadata Leakage | Zero (fully opaque) | Leaks creation timestamp |
Bit Breakdown of UUID v4
In UUID v4, every bit except the 4-bit version nibble and the 2-bit variant field is generated from a cryptographically secure pseudo-random number generator (CSPRNG):
- Octets 0–5 (48 bits):
random_a - Octet 6: High nibble
0100(version 4), low nibblerandom_b(4 bits) - Octet 7:
random_c(8 bits) - Octet 8: High 2 bits
10(variant), low 6 bitsrandom_d - Octets 9–15 (56 bits):
random_e
Total random entropy: $48 + 4 + 8 + 6 + 56 = 122$ bits.
Bit Breakdown of UUID v7
RFC 9562 §5.7 defines UUID v7 using five contiguous fields:
- `unix_ts_ms` (48 bits): Octets 0 through 5. Big-endian unsigned integer indicating milliseconds since the Unix epoch (1970-01-01T00:00:00Z). Supports dates up to year 10889 AD.
- `ver` (4 bits): Octet 6 high nibble set to
0111(binary 7). - `rand_a` (12 bits): Octet 6 low nibble and octet 7. Can contain random bits or a dedicated monotonic counter per RFC 9562 §6.2.
- `var` (2 bits): Octet 8 high 2 bits set to
10. - `rand_b` (62 bits): Octet 8 low 6 bits and octets 9–15, populated with CSPRNG entropy.

Why Does Database B-Tree Index Locality Matter?
Relational databases such as PostgreSQL, MySQL (InnoDB), SQLite, and Microsoft SQL Server use B-Tree (or B+ Tree) structures to index primary keys. Understanding how B-Trees organize disk storage explains why UUID v4 creates severe performance penalties at scale.
How Random UUID v4 Degrades B-Tree Performance
In a B-Tree, keys are stored in sorted leaf pages (typically 8 KB or 16 KB blocks). When you insert a new record with a randomly generated UUID v4:
- Random Insertion Points: Because UUID v4 hashes uniformly across the entire 128-bit numeric space, every consecutive insert targets an arbitrary leaf page scattered across the storage file.
- Cache Eviction and Thrashing: When the table index grows larger than the database memory buffer pool (PostgreSQL
shared_buffersor MySQLinnodb_buffer_pool_size), the database must continuously evict active pages and read arbitrary pages from persistent disk storage. - 50/50 B-Tree Page Splits: When a target leaf page becomes full, the engine must split it into two half-empty pages, write both pages back to disk, and update parent node pointers. In random insert patterns, page splits occur continuously across the entire tree, resulting in an average index fill factor of only 50% to 65%. This doubles disk storage overhead and degrades index scan performance.
How Monotonic UUID v7 Restores Index Locality
UUID v7 resolves index degradation by encoding the timestamp in the most significant 48 bits:
- Right-Appended Inserts: Because each newly generated UUID v7 has a timestamp greater than or equal to preceding records, insertions occur almost exclusively at the rightmost edge of the B-Tree index.
- Maximum Buffer Locality: The database engine keeps only the current trailing leaf page in RAM. Thousands of consecutive rows are written into the same in-memory block without touching older parts of the index.
- Optimal 90%+ Page Fill Factor: Because pages fill sequentially before a new page is allocated, B-Tree leaf pages achieve natural 90% to 95% fill factors. This prevents page splits, minimizes index bloat on disk, and speeds up read queries.
How Does Monotonic Sorting Work in RFC 9562 §6.2?
When high-throughput systems generate thousands of UUIDs within the same millisecond, simple random bits in rand_a can cause values created later in the batch to sort lexicographically before values created earlier.
To guarantee that UUIDs generated within the same process sort in strict chronological sequence, RFC 9562 §6.2 specifies formal monotonic mechanisms:
- Method 1 (Fixed-Bit-Length Dedicated Counter): A portion of the random bits—specifically the 12-bit
rand_afield—is allocated as an integer counter. When the millisecond timestamp advances (now_ms > last_ms), the counter is reset to 0 (or a random 12-bit start integer). When a subsequent UUID is created within the identical millisecond,counterincrements by 1. - Method 2 (Monotonic Random): A random integer increment is added to the preceding random value.
- Method 3 (Sub-Millisecond Precision): Sub-millisecond time intervals (microsecond or nanosecond fractional offsets) are mapped directly into the leading bits of
rand_a.
Our upgraded UUID Generator implements RFC 9562 §6.2 Method 1 (Fixed-Bit-Length Dedicated Counter). For any batch generated in your browser, every UUID v7 sorts strictly in chronological sequence:
$$\text{UUID}_{n-1} < \text{UUID}_n \quad \forall \; n \in [1, 1000]$$
If the 12-bit counter reaches its maximum capacity (4,095 increments within a single millisecond), the generator rolls the timestamp forward to the next millisecond, ensuring zero order inversion and zero counter overflow.
What Are the Collision Probabilities of UUID v4 and v7?
Cryptographic collision risk is calculated using the birthday problem.
UUID v4 Collision Formula
A UUID v4 contains 122 bits of independent random entropy ($2^{122} \approx 5.31 \times 10^{36}$ states). The probability $p$ of a collision among $n$ generated identifiers is:
$$p(n) \approx 1 - e^{-\frac{n^2}{2 \times 2^{122}}} \approx \frac{n^2}{2^{123}}$$
To reach a $10^{-9}$ (one in a billion) collision probability, a system must generate roughly $3.26 \times 10^{15}$ UUIDs.
UUID v7 Collision Formula
UUID v7 separates collision risk into two tiers:
- Inter-Millisecond: UUIDs created across different milliseconds have unique 48-bit timestamps and cannot collide.
- Intra-Millisecond: Within the same millisecond, uniqueness depends on 74 random and counter bits ($2^{74} \approx 1.88 \times 10^{22}$ states):
$$p_{\text{ms}}(n) \approx 1 - e^{-\frac{n^2}{2 \times 2^{74}}}$$
When using RFC 9562 §6.2 Method 1 with a 12-bit dedicated counter, collisions within a single process are 0 for up to 4,096 items per millisecond. For distributed multi-node clusters, 62 bits of CSPRNG entropy in rand_b provide strong cross-node isolation.
What Security and Privacy Information Does UUID v7 Leak?
While UUID v7 provides superior database performance, it introduces a privacy consideration that software architects must evaluate: creation time leakage.
Because the first 48 bits of a UUID v7 encode the exact Unix epoch millisecond:
- Anyone who reads an entity's UUID v7 can determine the exact date, hour, minute, second, and millisecond that the entity was inserted.
- Sequential counters can expose business growth velocity. For example, if a multi-tenant platform uses UUID v7 for public user accounts or order URLs, an external competitor could register two accounts one week apart and calculate the precise number of orders or users created during that interval.
- Where to avoid UUID v7: Never use UUID v7 for security-critical tokens where unpredictability is mandatory, such as password reset tokens, unguessable magic login links, or session IDs. For unguessable values, use high-entropy UUID v4 or cryptographic digests generated with our Hash Generator.
Worked Example: How Do You Decode a UUID v7 Identifier?
Consider the following canonical UUID v7 value generated by our upgraded browser tool:
01a16d90-3f7c-7000-a261-a3493bb39c4a
Let us break down each segment character by character according to RFC 9562 §5.7:
01a16d90 - 3f7c - 7 000 - a 261 - a3493bb39c4a
[-- unix_ts_ms -] [v]ran [v]ran [--- rand_b --]1. Extracting the Timestamp (unix_ts_ms)
The first 12 hexadecimal characters (octets 0 through 5) contain the 48-bit Unix epoch millisecond timestamp:
- Hex string:
0x01a16d903f7c - Base-10 integer: $1,792,839,532,412$ milliseconds
- Unix epoch seconds: $1,792,839,532.412$
- Decoded UTC Date:
2026-10-24 10:58:52.412 UTC
Any application can inspect these 12 hex characters and instantly reconstruct the exact moment of generation.
2. Validating the Version Nibble
The 13th hexadecimal character (the first character of the third group) is 7:
- Binary:
0111 - Indicates compliance with RFC 9562 UUID Version 7.
3. Reading the Monotonic Counter (rand_a)
The next 3 hexadecimal characters (000) represent the 12-bit rand_a field:
- Binary:
0000 0000 0000 - Value:
0. This confirms the identifier was the first UUID generated within that millisecond under RFC 9562 §6.2 Method 1. Subsequent items generated in the same millisecond increment to001,002, and so forth.
4. Validating the Variant Bits
The 17th hexadecimal character (the first character of the fourth group) is a:
- Binary:
1010 - The most significant 2 bits are
10, confirming compliance with the standard RFC variant (Variant 1). The remaining 2 bits (10) form the leading bits ofrand_b.
5. Inspecting Random Entropy (rand_b)
The remaining characters (261-a3493bb39c4a) constitute the 62 bits of cryptographically secure random entropy ensuring global uniqueness.
When formatting data structures for API distribution or storage, ensure your payloads adhere to valid schema specifications as detailed in our guide on JSON formatting best practices.
Summary: Which Identifier Should You Choose?
When deciding between UUID versions:
- Choose UUID v7 when generating database primary keys, table rows indexed by B-Trees, event-stream messages, or audit log entries where query performance, index compaction, and temporal sorting are paramount.
- Choose UUID v4 when identifiers are publicly accessible in URLs and creation timestamps must remain strictly confidential, or when generating security tokens, password resets, and ephemeral session handles.
Frequently asked questions
What is the primary difference between UUID v4 and UUID v7?+
UUID v4 is completely random across 122 bits, producing unordered identifiers. UUID v7 encodes a 48-bit big-endian Unix timestamp in milliseconds followed by 74 random and counter bits, producing naturally time-ordered, sortable identifiers.
Why does RFC 9562 obsolete RFC 4122?+
Published in May 2024, RFC 9562 formalizes modern identifier requirements by introducing time-ordered UUID versions 6, 7, and 8, resolving the database B-tree index degradation and timestamp precision issues of the older RFC 4122 specification.
Does UUID v7 leak sensitive creation timestamps?+
Yes. Because the first 48 bits encode the Unix epoch millisecond timestamp, anyone who inspects a UUID v7 can extract the exact creation date and time. Do not use v7 for unguessable password reset tokens or secret session cookies.
What is the collision probability of UUID v4 compared to UUID v7?+
UUID v4 has 122 random bits with an astronomical collision threshold (over 3 billion billion generated before a 50% collision probability). UUID v7 guarantees global ordering by millisecond; within the same millisecond, 74 entropy and counter bits prevent intra-millisecond collisions.
How does UUID v7 improve database write performance?+
Because UUID v7 values increase monotonically, database engines insert new rows into the rightmost leaf page of a B-tree index. This eliminates random I/O, prevents page splits, preserves 90%+ page fill factors, and keeps active index buffers hot in RAM.
Prashant Sharma · Founder & Technology Strategist
Prashant Sharma is the founder of Zynocode IT Solutions, specializing in web development, SEO tooling and generative AI workflows.