Developer Guides

UUID v4 vs. UUID v7: Collision Probability, B-Tree Index Fragmentation & The RFC 9562 Upgrade

Try & Tool Database Architecture Team• Published: 2026-10-13• 15 min read
Why random UUID v4 creates catastrophic B-Tree index fragmentation in PostgreSQL and MySQL InnoDB, and how timestamp-ordered UUID v7 (RFC 9562) restores write throughput while maintaining global uniqueness and sub-millisecond sorting.

The Evolution of Universally Unique Identifiers

For over two decades, software engineers building distributed cloud databases have relied on UUID v4 (Universally Unique Identifier Version 4) as the default primary key of choice. Unlike traditional auto-incrementing sequential integers (1, 2, 3...), UUIDs can be minted asynchronously across thousands of distributed microservices, edge lambdas, and client devices without coordinating through a centralized database sequence or exposing internal business metrics (such as revealing daily sales volume to competitors via predictable order IDs like /orders/1042).

However, as database tables scale past several million rows, UUID v4 introduces a severe architectural penalty: catastrophic B-Tree index fragmentation, rampant buffer pool cache evictions, and massive write amplification.

In May 2024, the Internet Engineering Task Force (IETF) officially ratified RFC 9562, deprecating RFC 4122 and standardizing UUID v7. By combining a 48-bit Unix millisecond epoch timestamp with cryptographic randomness, UUID v7 provides time-ordered sorting while preserving the decentralized, collision-proof advantages of UUID v4.

In this guide, we examine the mathematics of UUID collision probability, analyze the internal database mechanics of index page splits in PostgreSQL and MySQL InnoDB, compare alternative identifier systems (ULID, Snowflake, NanoID), and demonstrate how to implement UUID v7 in production.

Generate collision-resistant, cryptographically secure UUIDs in bulk with our free UUID / GUID Generator.


The Complete RFC 9562 UUID Version Landscape

RFC 9562 defines seven primary UUID versions, each tailored for specific architectural requirements:

VersionIdentifier TypeCore Components & EntropyPrimary Advantages & Modern Status
UUID v1Timestamp + Node MAC60-bit 100ns timestamp + 48-bit MAC addressTime-sortable, but deprecated for web apps due to hardware MAC privacy leaks.
UUID v3Namespace MD5 Hash128-bit MD5 digest of namespace + stringDeterministic name-based generation. Deprecated due to MD5 cryptographic weaknesses.
UUID v4Cryptographic Random122 bits of pseudo-random entropyUniversal standard, zero coordination. Severe B-Tree index fragmentation at scale.
UUID v5Namespace SHA-1 Hash160-bit SHA-1 digest truncated to 128 bitsDeterministic name-based generation. Preferred over v3 when deterministic hashing is required.
UUID v6Reordered Field Timestamp60-bit Gregorian timestamp reorganized + randomCorrects UUID v1 field order for B-Tree locality; backward-compatible with v1.
UUID v7Unix Epoch Millisecond48-bit Unix Epoch (ms) + 74 bits entropyThe modern industry standard. Time-ordered, cache-friendly, high write throughput.
UUID v8Custom / Vendor SpecificUser-defined formatReserved for experimental or domain-specific custom identifier implementations.

What is a UUID v4 and How is It Formatted?

A standard UUID is a 128-bit (16-byte) label formatted as 32 hexadecimal characters separated by four hyphens (the canonical 8-4-4-4-12 layout):

f47ac10b-58cc-4372-a567-0e02b2c3d479
              ^    ^
              |    |__ Variant (RFC 4122 / 9562 variant indicated by '8', '9', 'a', or 'b')
              |_______ Version (Version 4 indicated by '4')

In UUID v4, 122 of the 128 bits are purely random:

  • 4 bits specify the Version (0100 = 4)
  • 2 bits specify the Variant (10 = RFC variant)
  • $128 - 6 = 122$ bits of cryptographic entropy.

Collision Probability: The Birthday Paradox Mathematics

A common objection raised by database administrators when moving away from auto-increment integers is the fear of duplicate primary key collisions. How probable is a collision with UUID v4?

The total number of possible UUID v4 values is: $$2^{122} approx 5.3169 imes 10^{36}$$

Using the Birthday Paradox approximation, the probability $P$ of encountering at least one collision among $N$ generated identifiers is: $$P(N) approx 1 - e^{- rac{N^2}{2 imes 2^{122}}}$$

Number of Generated UUIDs ($N$)Exact Collision Probability ($P$)Real-World Context & Comparison
1,000,000 (1 Million)$approx 9.4 imes 10^{-26}$Mathematically indistinguishable from zero
100,000,000 (100 Million)$approx 9.4 imes 10^{-22}$Billions of times less likely than cosmic ray CPU bitflips
1,000,000,000 (1 Billion)$approx 9.4 imes 10^{-20}$100,000x less likely than winning two consecutive lotteries
1,000,000,000,000 (1 Trillion)$approx 9.4 imes 10^{-14}$Less likely than an unrecoverable asteroid impact
$2.71 imes 10^{18}$ UUIDs50% (0.50)To reach a coin-flip chance, you must generate 1 billion UUIDs every second for 86 continuous years!

Conclusion: When minted using a cryptographically secure pseudo-random number generator (such as crypto.getRandomValues() in modern web browsers or /dev/urandom in Linux), UUID v4 collisions are mathematically impossible in practical production engineering.


The Hidden Database Cost: Index Fragmentation & Cache Thrashing

While UUID v4 is immune to collisions, its uniform randomness wreaks havoc on relational database indexing engines (PostgreSQL, MySQL InnoDB, SQLite, and Microsoft SQL Server).

1. B-Tree Page Splits Explained

Relational databases index primary keys using balanced search trees (B-Trees or B+ Trees). Data pages on disk are fixed in size (typically 8KB in PostgreSQL and 16KB in MySQL InnoDB). Keys inside each leaf page are strictly ordered.

When you insert auto-increment integers (1, 2, 3...), new rows always append to the rightmost leaf page of the tree. The previous pages are never touched.

With UUID v4, every incoming primary key is uniformly random. An insert might belong in leaf node 12, the next in leaf node 948, and the next in leaf node 3:

PostgreSQL B-Tree Primary Key Index Insertion:
├── Key 0a4f... -> Inserts into Leaf Page 1
├── Key f9e2... -> Inserts into Leaf Page 500
├── Key 4b11... -> Inserts into Leaf Page 220
└── Key 1a99... -> Inserts into Leaf Page 45 (PAGE FULL! Triggers Page Split!)

When an 8KB index page is full and a random UUID needs to be inserted in the middle of it:

  1. The database engine must allocate a brand-new page.
  2. It moves 50% of the existing rows from the full page to the new page (Page Split).
  3. It rewrites internal parent pointer nodes up the tree.
  4. Internal Fragmentation: Both pages are now only 50% full. The index file on disk consumes double the required storage.

2. RAM Buffer Pool Cache Eviction

As a database grows beyond server RAM, the database engine maintains an in-memory buffer pool of frequently accessed pages.

  • With sequential IDs, only the most recent index pages need to reside in memory.
  • With UUID v4, every write and read operation targets a random disk page across the entire multi-gigabyte index. The database constantly evicts cached pages from RAM to fetch pages from SSD/NVMe disk.
  • Result: Disk I/O spikes to 100%, and write throughput plunges by 60% to 85%.

3. MySQL InnoDB Clustered Index Disaster

In MySQL InnoDB, tables are organized as a clustered index where the table's actual row data is physically stored inside the leaf pages of the primary key. When a page split occurs on a UUID primary key, InnoDB doesn't just split a lightweight index—it physically rewrites the entire row payload across disk blocks! Furthermore, every secondary index in InnoDB stores the primary key as its row pointer, compounding write amplification across every single index on the table.


The Solution: UUID v7 (RFC 9562)

Ratified in RFC 9562, UUID v7 solves index fragmentation by placing a standard Unix Epoch timestamp in the most significant bits:

UUID v7 Wire Structure (128 bits):
[ 48-bit Unix Timestamp (ms) ] [ 4-bit Ver ] [ 12-bit Counter/Rand ] [ 2-bit Var ] [ 62-bit Random Entropy ]
  • Bits 0–47 (48 bits): Big-endian unsigned 48-bit integer recording milliseconds since Unix Epoch (Jan 1, 1970). This field provides time-ordering until the year 10,889 AD!
  • Bits 48–51 (4 bits): Version field set to 0111 (binary 7).
  • Bits 52–63 (12 bits): Monotonic sub-millisecond sequence counter or extra random bits.
  • Bits 64–65 (2 bits): Variant field set to 10 (RFC variant).
  • Bits 66–127 (62 bits): Cryptographically secure pseudo-random entropy.

Performance Advantages of UUID v7 in Production:

  1. Append-Only Write Efficiency: Because the leading 48 bits represent chronological time, new records are inserted sequentially at the right-hand edge of the B-Tree index. Page splits are virtually eliminated.
  2. Warm Buffer Pool Memory: The active working set of the index remains compact and stays pinned in server RAM, maintaining high write speeds even as tables grow to hundreds of millions of rows.
  3. Decentralized Generation: Like UUID v4, UUID v7 can be minted independently on client browsers, background workers, or mobile apps without network roundtrips.
  4. Embedded Creation Time: You can extract the exact creation timestamp directly from the primary key, eliminating the need for an indexed created_at column.

Convert millisecond epoch timestamps to human dates with our Unix Timestamp Converter.


Distributed Identifier Shootout: UUID v4 vs. UUID v7 vs. ULID vs. Snowflake

Identifier SystemBit Length / String RepSortable?Time ResolutionRandom EntropyNative SQL Type Support
UUID v4128-bit / 36-char Hex❌ No (Random)None122 bitsNative uuid (PostgreSQL, MSSQL)
UUID v7128-bit / 36-char Hex✅ Yes (Chronological)1 Millisecond74 bitsNative uuid / RFC Standard
ULID128-bit / 26-char Crockford Base32✅ Yes1 Millisecond80 bitsRequires custom string/binary mapping
Twitter Snowflake64-bit / 19-char BigInt✅ Yes1 Millisecond~22 bits (Worker ID)Native BIGINT (requires coordinator)
NanoIDConfigurable / URL-safe string❌ No (Random)NoneConfigurableStored as VARCHAR (string overhead)

Why UUID v7 Wins Over ULID

While ULID (Universally Unique Lexicographically Sortable Identifier) pioneered timestamp-ordered 128-bit keys, it lacks formal IETF RFC standardization and uses Crockford's Base32 encoding. UUID v7 delivers identical sorting and entropy benefits while adhering to standard RFC 9562 hexadecimal formatting, making it natively compatible with existing PostgreSQL uuid column types, ORMs (Prisma, Hibernate, Drizzle), and JSON schemas without custom serializers.


Implementation Guide: Generating UUID v7

1. Modern TypeScript / JavaScript Implementation

import crypto from 'crypto';

export function generateUUIDv7(): string {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);

  // Current Unix timestamp in milliseconds (48 bits)
  const now = Date.now();
  bytes[0] = (now / 0x10000000000) & 0xff;
  bytes[1] = (now / 0x100000000) & 0xff;
  bytes[2] = (now / 0x1000000) & 0xff;
  bytes[3] = (now / 0x10000) & 0xff;
  bytes[4] = (now / 0x100) & 0xff;
  bytes[5] = now & 0xff;

  // Version 7: Set bits 48-51 to 0111
  bytes[6] = (bytes[6] & 0x0f) | 0x70;
  // Variant: Set bits 64-65 to 10
  bytes[8] = (bytes[8] & 0x3f) | 0x80;

  // Format as 8-4-4-4-12 hex string
  const hex = Array.from(bytes).map(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)}`;
}

2. PostgreSQL DDL Schema

-- Native PostgreSQL 16+ support or community extensions
CREATE EXTENSION IF NOT EXISTS "pg_uuidv7";

CREATE TABLE customer_orders (
    order_id UUID PRIMARY KEY DEFAULT uuid_generate_v7(),
    user_id UUID NOT NULL,
    total_amount NUMERIC(12, 2) NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

Compare code diffs and schema migrations safely using our Text Diff Checker.


Frequently Asked Questions (FAQ)

Does UUID v7 expose the exact time of record creation? Is this a security concern?

Yes, the first 48 bits of a UUID v7 encode the millisecond Unix timestamp when the ID was generated. In 99% of web applications (such as order IDs, blog posts, transaction logs, or chat messages), exposing creation time is completely harmless. However, if your application treats creation time as classified business intelligence (for example, hiding auction bid submission times), or if you need to prevent competitors from calculating your precise creation velocity, use pure random UUID v4 or encrypt/hash identifiers before exposing them in public URLs.

What happens if multiple UUID v7 keys are generated within the same millisecond?

RFC 9562 defines explicit sub-millisecond monotonicity requirements. When multiple identifiers are minted within the same millisecond on a single server, the implementation increments the 12-bit sequence counter. This guarantees that IDs generated within the same millisecond remain strictly ordered and completely collision-free. If generating IDs across distributed independent machines in the same millisecond, the 74 bits of cryptographic entropy guarantee uniqueness.

Can I migrate an existing database table from UUID v4 to UUID v7 without downtime?

Yes! Because both UUID v4 and UUID v7 share the identical 128-bit layout and canonical 36-character hexadecimal format, existing database columns (UUID in PostgreSQL or BINARY(16) in MySQL) can store both versions simultaneously. You can update your application code to start generating UUID v7 for all new incoming records immediately. The existing historical UUID v4 rows remain completely valid and queryable. Over time, as new rows accumulate sequentially, the top layers of your B-Tree index will naturally stabilize.

Why does MySQL 8 offer UUID_TO_BIN(..., 1) and how does it compare to UUID v7?

MySQL 8 introduced UUID_TO_BIN(uuid, 1) to rearrange the timestamp bytes of legacy UUID v1 so that high-order time components appear first, mitigating index fragmentation. However, UUID v1 still leaks the host machine's physical MAC address (a significant security and privacy flaw) and uses an antiquated 100-nanosecond Gregorian epoch from 1582. UUID v7 is far superior: it uses standard Unix epoch milliseconds, provides 74 bits of true cryptographic entropy, leaks zero hardware information, and works universally across all modern database systems.

What is the performance difference between storing UUIDs as UUID vs. VARCHAR(36)?

Storing UUIDs as formatted strings (VARCHAR(36)) requires 36 bytes of storage per row, plus character encoding overhead. Storing UUIDs as native 128-bit integers (UUID type in PostgreSQL or BINARY(16) in MySQL) requires only 16 bytes—a 55% reduction in disk and memory space. This size difference directly affects how many index leaf pages fit into server RAM, making native binary storage more than twice as fast for large-scale table joins and primary key lookups.

Generate collision-resistant, cryptographically secure UUIDs in bulk with our free UUID / GUID Generator.