UUID v4 vs. UUID v7 (RFC 9562): Why Time-Ordered Identifiers Fix Database Index Fragmentation
Brian De Vivar
• Tech Contributor at BrainyToolsReviewed by Brian De Vivar — software developer & computer science educator with 20+ years of experience building software and teaching networking & systems engineering.

For over a decade, backend engineers faced an uncomfortable trade-off when choosing primary keys: use auto-incrementing 64-bit integers (BIGSERIAL) for fast B-tree inserts—at the cost of leaking record counts and complicating distributed sharding—or use random UUID v4 strings for zero-coordination uniqueness—at the cost of thrashing database B-tree indexes.
In May 2024, IETF RFC 9562 formally standardized UUID v7, combining a millisecond-precision Unix timestamp with cryptographically random bits. You can generate and inspect both versions locally with the UUID v4 & v7 Generator. In this guide, we examine the exact bit layouts of UUID v4 and UUID v7 and explain why UUID v7 has rapidly become the default primary key for modern relational databases.
Anatomy of a 128-Bit UUID
Every standard UUID is a 128-bit (16-byte) value formatted as 32 hexadecimal characters grouped in an 8-4-4-4-12 pattern:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
^ ^
| └── Variant nibble (8, 9, a, or b -> binary 10xx for RFC 9562)
└─────── Version nibble (4 for UUID v4, 7 for UUID v7)
UUID v4 (Fully Random)
UUID v4 reserves 4 bits for the version (0100) and 2 bits for the RFC variant (10), leaving 122 bits of pure cryptographic randomness.
- Pros: Unpredictable, reveals zero timing metadata, impossible to enumerate sequentially.
- Cons: Completely unordered. Every new insert lands at a random leaf page in your database index.
UUID v7 (Unix Epoch Time + Random)
UUID v7 places a 48-bit big-endian Unix timestamp in milliseconds in the most significant bits, followed by the 4-bit version (0111), 12 bits of randomness (or sub-millisecond counter), the 2-bit variant (10), and 62 more bits of cryptographic randomness (74 random bits total).
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| unix_ts_ms |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| unix_ts_ms | ver | rand_a |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|var| rand_b |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| rand_b |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Because the timestamp occupies the leading bits, lexicographical sorting of UUID v7 strings (or raw 16-byte UUID columns) naturally orders records chronologically.
Why UUID v4 Hurts B-Tree Index Performance
Relational databases like PostgreSQL, MySQL (InnoDB), and SQLite store primary keys in B-tree indexes organized into fixed-size pages (typically 8 KB in PostgreSQL and 16 KB in InnoDB).
When you insert millions of rows with UUID v4 keys:
- Random Page Lookups: Each incoming key lands in an arbitrary location across the entire index rather than the rightmost leaf page. Once the index exceeds available RAM (
shared_buffers/innodb_buffer_pool_size), nearly every insert triggers a random disk read. - Frequent Page Splits: Inserting into the middle of full leaf pages forces the database to split pages in half, leaving pages around 50%–70% full (index bloat) instead of tightly packed at ~90%+.
- Write Amplification (WAL): In PostgreSQL, modifying scattered index pages triggers Full Page Writes (FPW) in the Write-Ahead Log after checkpoints, dramatically increasing disk I/O and replication lag.
With UUID v7, inserts arrive monotonically at the right edge of the B-tree—just like BIGSERIAL—keeping the hot working set inside memory and minimizing page splits.
Head-to-Head Comparison: UUID v4 vs. UUID v7 vs. Auto-Increment
| Feature | Auto-Increment (BIGINT) |
UUID v4 | UUID v7 (RFC 9562) |
|---|---|---|---|
| Storage Size | 8 bytes | 16 bytes (native UUID) |
16 bytes (native UUID) |
| Client-Side / Distributed Generation | No (requires DB round-trip or coordinator) | Yes (zero coordination) | Yes (zero coordination) |
| B-Tree Insert Locality | Excellent (append-only) | Poor (random page splits) | Excellent (time-ordered append) |
| Hides Creation Timestamp | No (monotonically leaks volume) | Yes (fully opaque) | Partial (exposes ms timestamp) |
| Collision Resistance | Exact (DB sequence) | 122 random bits | 74 random bits per millisecond |
When Should You Still Choose UUID v4 Over UUID v7?
UUID v7 is superior for internal database primary keys, event logs, and distributed traces, but UUID v4 remains the right choice for security-sensitive tokens:
- Session IDs, password-reset tokens, API keys, and magic links: Never expose creation timestamps or use predictable prefixes in bearer credentials. Use UUID v4 or dedicated high-entropy CSPRNG strings from the Password & Key Generator.
- Public URLs where creation timing is confidential: If exposing the exact millisecond an invoice or user account was created leaks competitive intelligence, keep UUID v7 as the internal clustered primary key and expose a separate random UUID v4
public_idcolumn (or hash) in external APIs.
Extracting the Timestamp from a UUID v7
One practical advantage of UUID v7 in debugging and incident response is that every primary key embeds its exact creation time (down to the millisecond, valid until the year 10,889 AD because $2^{48}$ milliseconds $\approx 8{,}925$ years from the 1970 Unix epoch).
Consider a sample UUID v7:
01938a4f-7c20-7d1a-9f4e-3b2c1a0d5e6f
^^^^^^^^^^^^^
First 12 hex characters = 48-bit Unix epoch milliseconds
Converting 0x01938a4f7c20 from hexadecimal to decimal gives 1733192416288 milliseconds since 1970-01-01T00:00:00Z. You can inspect this directly in JavaScript without touching a database query:
function extractUuidV7Timestamp(uuid: string): Date {
const hex = uuid.replace(/-/g, "").slice(0, 12);
const unixMs = Number.parseInt(hex, 16);
return new Date(unixMs);
}
console.log(extractUuidV7Timestamp("01938a4f-7c20-7d1a-9f4e-3b2c1a0d5e6f").toISOString());
Want to inspect the exact hex-to-decimal conversion or check Unix epoch timestamps manually? Cross-check values with the Number Base Converter and Unix Timestamp & Date Converter.
SQL Schema Examples: PostgreSQL and MySQL
PostgreSQL (Native uuid Type)
PostgreSQL 18 introduces native uuidv7() support, and earlier versions (13–17) can either generate UUID v7 in the application layer (Node.js, Python, Go, Java) or via a lightweight PL/pgSQL helper or pg_uuidv7 extension:
CREATE TABLE orders (
id UUID PRIMARY KEY, -- Populate with RFC 9562 UUID v7
customer_id UUID NOT NULL,
total_cents BIGINT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Range queries and cursor pagination sort chronologically on the PK
SELECT id, total_cents
FROM orders
WHERE id > '01938a4f-7c20-7000-8000-000000000000'
ORDER BY id ASC
LIMIT 50;
MySQL 8+ (Clustered InnoDB Primary Key)
In InnoDB, the primary key is the physical table order (a clustered B+ tree), and every secondary index stores a copy of the primary key as its row pointer. That makes random UUID v4 especially painful in MySQL—both the clustered table and secondary indexes fragment heavily. Storing UUID v7 in BINARY(16) preserves sequential inserts and cuts key size by more than half compared to CHAR(36):
CREATE TABLE events (
id BINARY(16) PRIMARY KEY, -- Store via UUID_TO_BIN(uuid_v7_str)
event_type VARCHAR(64) NOT NULL,
payload JSON NOT NULL
) ENGINE=InnoDB;
Migrating an Existing Table from UUID v4 to UUID v7
You do not need a risky big-bang primary-key rewrite to benefit from UUID v7:
- Both share the exact same 128-bit
UUIDtype: Existing foreign keys, ORMs, GraphQL schemas, and API contracts continue working without any column type change. - Switch new inserts first: Update your application generator from
crypto.randomUUID()(v4) to a standards-compliant UUID v7 generator. All historical UUID v4 rows remain valid, while all newly inserted rows cluster cleanly at the right edge of the B-tree. - Reclaim historical bloat once: After switching new writes, schedule a non-blocking
REINDEX INDEX CONCURRENTLY(PostgreSQL) orOPTIMIZE TABLE(MySQL) during a low-traffic window to compact old fragmented pages.
Implementation Best Practices
- Store as Native
UUID, NotVARCHAR(36): Storing hyphenated text in aVARCHAR(36)column consumes 36+ bytes and forces UTF-8 collation comparisons. PostgreSQL's nativeuuidtype (and MySQL'sBINARY(16)withUUID_TO_BIN) stores the compact 16-byte binary form. - Use Monotonic Sub-Millisecond Counters for High Throughput: If a single service generates thousands of UUID v7 values inside the same millisecond, use RFC 9562's optional monotonic counter in
rand_aso batch inserts remain strictly ordered. - Watch for Clock Skew Across Distributed Nodes: Because UUID v7 relies on wall-clock milliseconds, configure NTP/chrony on backend servers. Even if two servers drift by a few milliseconds, the 74 random bits prevent collisions—ordering simply becomes approximate within the skew window.
- Seed Realistic Test Fixtures: Need bulk UUID v7 or v4 records alongside realistic names, timestamps, and emails to benchmark your database schema? Combine the UUID v4 & v7 Generator with the Mock Data Generator to export ready-to-import SQL, CSV, or JSON datasets locally.
Frequently Asked Questions (FAQ)
What is the collision probability of UUID v7?
Inside the same millisecond, UUID v7 provides 74 bits of randomness ($2^{74} \approx 1.89 \times 10^{22}$ combinations). By the birthday paradox, you would need to generate over 1.9 billion UUIDs in a single millisecond just to reach a 1-in-10,000 collision probability.
How does UUID v7 compare to ULID and KSUID?
ULID uses Crockford Base32 (26 characters) and KSUID uses Base62 (27 characters). Both solve the B-tree locality problem, but neither fits natively into SQL UUID columns without custom serialization. UUID v7 gives you the exact same 48-bit millisecond time-ordering inside the official IETF RFC 9562 standard supported by every database, driver, and JSON validator.
Does UUID v7 leak sensitive user information?
UUID v7 exposes the creation timestamp (to the millisecond) of the identifier, which is acceptable for orders, logs, and internal records, but undesirable for bearer tokens or anonymous public handles. For security secrets, always stick to UUID v4 or a dedicated Cryptographic Password Generator.