UUID v4 vs UUID v7: Database Indexing Performance Explained

Compare UUID v4 and UUID v7 for primary keys. Learn why time-ordered UUID v7 eliminates B-Tree index fragmentation and cuts insert latency.

Using completely random UUID v4 values as database primary keys can significantly degrade write performance on large tables, because inserts land on random B-Tree pages. To solve this architectural bottleneck, the IETF standardized UUID v7 in RFC 9562. UUID v7 embeds a millisecond-precision Unix timestamp into the most significant 48 bits, producing time-ordered identifiers that insert monotonically into B-Tree leaf pages while preserving global uniqueness.

Why UUID v4 breaks database B-Tree indexes

Relational databases such as PostgreSQL, MySQL InnoDB, and SQL Server organize primary key indexes using balanced tree structures (B-Trees or B+Trees). In a healthy B-Tree:

  • Sequential keys (such as auto-incrementing integers) always append to the rightmost leaf page of the tree.
  • Once a leaf page fills to capacity, the database closes it and allocates a fresh page at the end of the sequence without disturbing existing index pages.

UUID v4 consists of 122 bits of pseudo-random data. Because values scatter randomly across the entire 128-bit address space:

  • Every new insert targets an arbitrary, unpredictable leaf page somewhere within the tree.
  • When an insert hits a leaf page that is already 100 percent full, the storage engine must execute an expensive page split: it allocates a new page, copies half the rows over, and updates parent node pointers.
  • As the dataset grows larger than available RAM (the Buffer Pool), random inserts force continuous, random read-write disk I/O, causing cache thrashing and degraded write throughput.

Structure comparison: UUID v4 vs UUID v7

The differences between v4 and v7 (both now defined in RFC 9562) show why v7 restores append-mostly indexing performance:

Specification Metric UUID v4 (RFC 9562, previously RFC 4122) UUID v7 (RFC 9562)
Primary Ordering Purely random (No ordering) Monotonic time-ordered (Unix epoch)
Timestamp Resolution None 48-bit millisecond timestamp
Random Bits 122 bits 74 bits
B-Tree Index Locality Poor (Random writes across all pages) Excellent (Appends to rightmost edge)
Primary Key Fragmentation High (random inserts typically leave pages only about 70% full on average) Low (compact pages, close to the configured fill factor)
Storage Size 16 bytes (128 bits) 16 bytes (128 bits)
Collision Resistance Virtually zero Virtually zero within millisecond bins

Generating UUID v7 in JavaScript and Python

UUID v7 encodes the current Unix timestamp in milliseconds as a 48-bit big-endian integer in the first six bytes, followed by version number 7 and random bits:

// Lightweight UUID v7 generator in modern JavaScript
function generateUUIDv7() {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);

  const timestamp = Date.now();
  
  // Write 48-bit timestamp into bytes 0-5
  bytes[0] = (timestamp / 0x10000000000) & 0xff;
  bytes[1] = (timestamp / 0x100000000) & 0xff;
  bytes[2] = (timestamp / 0x1000000) & 0xff;
  bytes[3] = (timestamp / 0x10000) & 0xff;
  bytes[4] = (timestamp / 0x100) & 0xff;
  bytes[5] = timestamp & 0xff;

  // Set version to 7 (bits 4-7 of byte 6)
  bytes[6] = (bytes[6] & 0x0f) | 0x70;
  // Set variant to 2 (bits 6-7 of byte 8: RFC 4122 variant)
  bytes[8] = (bytes[8] & 0x3f) | 0x80;

  // Format into standard 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)}`;
}

console.log(generateUUIDv7());
// Example output: "0192e4a1-8d2b-7c19-9c55-76abf3c4c4ca"

Production Pro-Tip: UUID v7 timestamp extraction without extra columns

Because UUID v7 stores a Unix millisecond timestamp in its first 48 bits, you can read an approximate creation time directly from the primary key. Treat it as the time the ID was generated, not a guaranteed audit timestamp: generators may adjust or shift it (RFC 9562 allows this), and IDs can be generated by clients with inaccurate clocks. Keep a separate created_at column when the exact time matters.

PostgreSQL 18 provides uuidv7() and uuid_extract_timestamp() for this. On older versions you can decode the first 48 bits manually:

-- Extract creation timestamp directly from a UUID v7 primary key
SELECT 
    id,
    to_timestamp(('x' || lpad(substr(replace(id::text, '-', ''), 1, 12), 16, '0'))::bit(64)::bigint / 1000.0) AS created_at
FROM orders;

When generating randomized tokens, UUIDs, or QA boundary strings for test environments, use a client-side random value generator to produce valid identifiers directly inside your browser. To format arrays of generated UUIDs into valid database query parameters without manual text editing, use a dedicated SQL list formatter.

Frequently Asked Questions (FAQ)

Is UUID v7 officially approved by standards bodies?

Yes. In May 2024, the Internet Engineering Task Force (IETF) officially published RFC 9562, which formally obsoletes RFC 4122 and standardizes UUID versions 6, 7, and 8.

Can UUID v7 leak sensitive creation time information?

Yes. Because the first 48 bits expose the timestamp of creation to millisecond precision, public-facing URLs containing UUID v7 identifiers allow external parties to determine when a record or user account was generated. If creation timestamps are considered sensitive business data, use UUID v4 or HMAC-derived identifiers for external references.

How does UUID v7 compare to ULID and NanoID?

ULID (Universally Unique Lexicographically Sortable Identifier) uses a similar time-ordered design but relies on Crockford Base32 encoding (26 characters). NanoID focuses on compactness (21 characters) but defaults to random ordering. UUID v7 matches ULID performance while maintaining 100 percent compatibility with native 16-byte UUID database types.

References & Official Sources