Why UUIDv7 Is Replacing UUIDv4 for Database Keys

Learn how UUIDv7 solves B-tree index fragmentation and buffer pool churn caused by UUIDv4, delivering sequential write performance with distributed uniqueness.

Choosing a primary key strategy often comes down to an uncomfortable compromise between sequential integers and globally unique identifiers. For over two decades, UUIDv4 served as the default standard for distributed architectures, offering collision-free generation without requiring central coordination. However, as tables scale into tens of millions of rows, the pseudo-random nature of UUIDv4 exacts a heavy performance penalty on relational storage engines. The ratification of RFC 9562 and the arrival of UUIDv7 fundamentally resolve this long-standing trade-off.

The Hidden B-Tree Tax of Random UUIDs

Most modern relational databases—including PostgreSQL, MySQL with InnoDB, and SQLite—rely on B-tree or B+tree indexes to manage primary keys. B-trees are optimized for sequential or monotonically increasing data. When keys arrive in sequential order, new rows append cleanly to the rightmost leaf page of the tree index. Because that active leaf page remains resident in the database buffer pool in RAM, insertion operations require minimal disk I/O, and index pages consistently achieve an optimal fill factor of 90% to 100%.

UUIDv4 breaks this optimization entirely. Because UUIDv4 contains 122 bits of pseudo-random entropy, every incoming record targets an unpredictable, random position across the entire index tree. When an insert hits a page that is not currently cached in memory, the engine must fetch that cold page from disk, causing severe I/O stalls.

Sequential / Monotonic Keys (Append-Only Writes):
[Leaf Page 1: Full] -> [Leaf Page 2: Full] -> [Leaf Page 3: Hot in RAM] <-- New writes

UUIDv4 Keys (Scattered Random Writes):
[Page 1] <-- Write    [Page 2]    [Page 3] <-- Write    [Page 4] <-- Write
(Results in frequent 50/50 page splits, cold disk reads, and index bloat)

Once a target page reaches capacity, the engine must execute a B-tree page split. It allocates a new storage block, migrates roughly half the entries to the new page, and rewrites parent directory pointers. Because writes arrive randomly across all nodes, leaf pages frequently end up only 50% to 60% full on average. This fragmentation inflates index storage by 25% to 40%, drives up Write-Ahead Logging (WAL) bandwidth, and evicts frequently queried application data from the shared memory cache.

Anatomy of UUIDv7: Time-Ordered Structure

Comparison diagram showing sequential B-tree leaf node appends versus scattered random inserts causing page splits

Standardized under RFC 9562, UUIDv7 maintains the standard 128-bit footprint and 36-character hexadecimal format of traditional UUIDs while restructuring the bit layout to enforce chronological sorting:

  • 48 bits (Unix timestamp): Milliseconds elapsed since the Unix epoch, ensuring monotonic sorting until the year 10889.
  • 4 bits (Version): Binary value 0111 (decimal 7).
  • 12 bits (Sub-millisecond or Sequence Counter): Provides sub-millisecond precision or monotonic counter increment within the same millisecond tick.
  • 2 bits (Variant): Standard RFC layout 10.
  • 62 bits (Random Entropy): Cryptographically strong random entropy ensuring collision resistance across distributed nodes.
-- Example of a generated UUIDv7 value
-- 018e32a4-bc80-7a31-b1e4-9d51e7c5b190
-- |--- 48 bits ms timestamp ---| 7 | sub/seq | var | --- 62 random bits ---|

Because the most significant 48 bits encode chronological time, newly minted UUIDv7 identifiers sort naturally in ascending lexicographical and binary order. When written to a database table, incoming rows land consistently on the active, hot rightmost edge of the B-tree index, restoring compact page density and eliminating random disk lookups.

Performance and Operational Benefits

In high-throughput transactional systems, migrating from UUIDv4 to UUIDv7 delivers measurable operational advantages once the index size exceeds the server's working memory:

  1. Index Compaction: Because B-tree pages fill sequentially without premature splits, UUIDv7 primary key indexes consume 20% to 30% less disk space and memory compared to UUIDv4 equivalents.
  2. Predictable Insert Latency: UUIDv4 insert latency degrades exponentially as tables grow beyond the buffer pool. UUIDv7 maintains a flat, near-constant write latency profile comparable to native 64-bit auto-incrementing integers.
  3. Cache Efficiency: The database buffer pool no longer wastes memory thrashing cold index pages in and out of RAM, preserving cache capacity for user queries and analytical workloads.
  4. Decentralized Generation: Unlike centralized auto-increment sequences, client applications, message consumers, and microservices can generate UUIDv7 primary keys independently before executing database transactions.

Practical Implementation and Considerations

Generating UUIDv7 identifiers requires no external coordination cluster or ticket service. Modern application runtimes support UUIDv7 natively or via lightweight libraries:

import { v7 as uuidv7 } from 'uuid';

interface OrderRecord {
  id: string;
  customerId: string;
  totalAmount: number;
  createdAt: Date;
}

export function createOrder(customerId: string, totalAmount: number): OrderRecord {
  return {
    id: uuidv7(), // Encodes current Unix timestamp with random entropy
    customerId,
    totalAmount,
    createdAt: new Date(),
  };
}

Before standardizing UUIDv7 across all schemas, evaluate two specific operational considerations:

  • Timestamp Exposure: Because the high-order bits encode the exact millisecond of generation, anyone with access to the identifier can determine when the row was created. If creation velocity or volume represents sensitive business intelligence, avoid exposing internal UUIDv7 keys in public-facing URLs or use dedicated public tokens.
  • Storage Footprint: At 16 bytes, UUIDv7 requires twice the storage of an 8-byte BIGINT. However, for modern distributed systems requiring independent client-side key generation and seamless database replication, UUIDv7 delivers the best possible balance between distributed safety and hardware-level storage performance.

Sources

  1. datatracker.ietf.org

GENERATED · REVIEWED BY PKN · 2026-09-05

0

Responses

Loading comments…