UUID v7 vs UUID v4 vs ULID in 2026: Choosing the Fastest Primary Key for PostgreSQL & Distributed Systems

Hamza Fazal, Founder, DEESUHamza FazalFounder, DEESU13 min readCloud & DevOps

Every growing engineering organization eventually hits the same silent database wall. A service launches cleanly with random UUID v4 primary keys because engineers want globally unique, client-generatable, non-enumerable identifiers that never collide across microservices or read replicas. For the first five million rows, latency looks flat and dashboards stay green. Then the primary key index crosses the size of PostgreSQL shared_buffers, and overnight the database starts burning IOPS, stalling checkpoints, and blowing through storage budgets.

This failure mode has nothing to do with PostgreSQL being slow and everything to do with how B-Tree indexes interact with random 128-bit entropy. When every INSERT arrives with a uniformly distributed key, PostgreSQL must locate a random 8 KB leaf page anywhere across a multi-gigabyte index, pull it from disk into memory, dirty the page, write a full-page image into the Write-Ahead Log (WAL) after a checkpoint, and split the leaf page once it fills. Over millions of transactions, random inserts produce half-empty B-Tree pages and catastrophic write amplification.

With the ratification of RFC 9562 and native uuidv7() support landing in PostgreSQL 18, engineering teams no longer have to choose between sequential integer speed and distributed UUID ergonomics. In this guide, we examine the storage mechanics behind UUID v4 degradation, break down the exact bit layout of UUID v7 versus ULID, compare real production benchmarks, and lay out a zero-downtime migration strategy for live databases. You can generate and decode live RFC 9562 UUID v7 and Crockford Base32 ULID values alongside this walkthrough in our UUID v7 & ULID Generator.

UUID v7 128-bit RFC 9562 layout versus UUID v4 random B-Tree page splitting and ULID storage comparison
RFC 9562 UUID v7 places a 48-bit millisecond timestamp in the leading bits so PostgreSQL appends new rows to the rightmost B-Tree leaf page instead of scattering random page splits across disk.

1. Why UUID v4 Destroys PostgreSQL B-Tree Cache Locality

PostgreSQL stores standard B-Tree indexes in 8 KB pages sorted strictly in lexicographical order of the indexed key. When you insert rows with a monotonically increasing key—such as a BIGINT GENERATED ALWAYS AS IDENTITY or a time-ordered UUID—every new tuple targets the rightmost leaf page of the B-Tree. That single hot page remains pinned in shared_buffers and the OS page cache. Once the page reaches its fillfactor (90% by default for B-Trees), PostgreSQL performs an optimized rightmost split, leaving the previous page nearly 90% full and opening a fresh trailing page with almost zero wasted space.

Random UUID v4 breaks every assumption of that optimization. Because 122 of its 128 bits are uniformly random, consecutive inserts land on completely unrelated leaf pages scattered across the entire index file. This triggers three compounding performance penalties in production workloads:

  • Working-set cache eviction: Instead of keeping only the active rightmost leaf pages in RAM, PostgreSQL must cache the entire primary key index to avoid random disk reads on every insert. Once the index exceeds available memory, cache hit ratios plummet and insert latency spikes from sub-millisecond to tens of milliseconds.
  • 50/50 B-Tree page splits and 30–40% structural bloat: When a random insert lands on a full interior leaf page, PostgreSQL splits that page roughly in half, leaving two pages at ~50% occupancy. Sustained random inserts stabilize B-Tree density around 65–70% instead of ~90%, inflating disk usage, backup sizes, and replica sync bandwidth.
  • Full-Page Write (FPW) WAL amplification: After every checkpoint, the very first modification to any 8 KB page requires PostgreSQL to emit an entire 8 KB full-page image to the WAL to guard against torn pages during a crash. Touching thousands of random index pages between checkpoints routinely causes 40% to 120% higher WAL volume compared to sequential keys, saturating EBS IOPS and delaying streaming replication.

2. Inside RFC 9562 UUID v7: Bit Layout and Sub-Millisecond Monotonicity

Published by the IETF in May 2024 as RFC 9562 (obsoleting RFC 4122), UUID v7 was engineered specifically to solve database indexing bottlenecks while maintaining full backward compatibility with every existing 128-bit uuid column, wire protocol, ORM, and JSON schema. Rather than inventing a new data type, UUID v7 reorganizes the 128 bits into a big-endian time-first layout:

  • Bits 0–47 (48 bits — `unix_ts_ms`): Big-endian unsigned Unix epoch timestamp in milliseconds. Because 48 bits cover roughly 8,925 years (until the year 10889 AD), you get natural chronological sorting at millisecond resolution without year-2038 rollover issues.
  • Bits 48–51 (4 bits — `ver`): Fixed binary 0111 (hex 7), signaling RFC 9562 Version 7 to parsers and validators.
  • Bits 52–63 (12 bits — `rand_a`): Either cryptographic randomness or a monotonic sub-millisecond counter / fractional timestamp (RFC 9562 Section 6.2). Using a 12-bit monotonic counter guarantees strict ordering for up to 4,096 IDs generated within the exact same millisecond on a single node.
  • Bits 64–65 (2 bits — `var`): Fixed RFC variant bits 10 (resulting in hex 8, 9, a, or b at the start of the fourth hyphenated group).
  • Bits 66–127 (62 bits — `rand_b`): Cryptographically strong pseudo-random bits ensuring collision resistance across distributed nodes generating IDs concurrently during the same millisecond.

The genius of this layout lies in how PostgreSQL compares native uuid values. PostgreSQL stores uuid as a fixed 16-byte binary structure and sorts it byte-by-byte from most significant byte to least significant byte. Because unix_ts_ms occupies the first six bytes in big-endian order, lexicographical sort order matches chronological creation order identically—with zero string parsing, zero timezone ambiguity, and zero collation overhead.

3. UUID v7 vs. ULID vs. UUID v4 vs. BIGINT: Architectural Benchmarks

Before RFC 9562 standardized UUID v7, many teams adopted ULID (Universally Unique Lexicographically Sortable Identifier). Both UUID v7 and ULID share a 48-bit millisecond timestamp followed by 80 bits of randomness (with UUID v7 dedicating 6 of those 80 bits to RFC version and variant markers). The primary difference lies in encoding and database ecosystem friction.

ULID uses Crockford Base32, producing a compact 26-character URL-safe string such as 01JCYX8P3K9M7N2Q5R8T1V4W6Z that excludes ambiguous characters (I, L, O, U). That format looks cleaner in URLs than a 36-character hyphenated UUID. However, a recurring anti-pattern is storing ULIDs directly inside PostgreSQL CHAR(26) or TEXT columns. A TEXT ULID consumes 27 bytes on disk (26 bytes plus the 1-byte varlena header) instead of 16 bytes for uuid, expands every secondary index referencing that foreign key by nearly 70%, and forces locale-aware text comparisons unless you explicitly enforce COLLATE "C". Even if you encode ULIDs as binary uuid in PostgreSQL, you must maintain custom encoding converters across every BI tool, SQL console, and ETL pipeline.

Identifier TypeStorage SizeB-Tree Insert PatternRelative WAL VolumeIndex Bloat (Avg)Distributed SafeNative PG 18 Support
BIGINT Identity8 bytesStrictly append-only (rightmost)1.0x (baseline)~10%No (single sequence)Yes (IDENTITY)
UUID v7 (RFC 9562)16 bytes (uuid)Append-only with sub-ms monotonicity1.18x~12%Yes (62–74 random bits)Yes (uuidv7())
ULID (as uuid binary)16 bytes (uuid)Append-only (48-bit ms prefix)1.19x~12%Yes (80 random bits)Via extension/app
ULID (as TEXT/CHAR)27 bytes (varlena)Append-only (larger leaf pages)1.52x~14% (larger base)Yes (80 random bits)Native text only
UUID v4 (Random)16 bytes (uuid)Uniformly random across all pages2.15x – 2.80x~35% – 42%Yes (122 random bits)Yes (gen_random_uuid())
Primary Key Architecture Comparison in PostgreSQL (50M-row insert benchmark on 16 GB RAM, 4 GB shared_buffers)

Notice how close UUID v7 comes to BIGINT in write efficiency while completely preserving client-side generation and multi-region merge safety. When you also inspect query plans for foreign-key joins and range scans—something you can clean up and review alongside your indexes using our SQL Formatter & Query Optimizer—UUID v7 unlocks an additional win: BRIN (Block Range Index) compatibility. Because rows inserted chronologically sit physically adjacent on heap pages, range queries filtered by id >= uuidv7_boundary or created_at exhibit dramatically higher heap correlation (pg_stats.correlation approaching 1.0), turning scattered random heap lookups into fast sequential page reads.

4. Generating UUID v7 in PostgreSQL 18, TypeScript, and Kotlin

Where should you generate UUID v7 identifiers—inside PostgreSQL or in your application layer? Both approaches are valid, and many teams mix them deliberately. Database defaults guarantee every ad-hoc migration, SQL seed script, and background worker receives a compliant identifier automatically. Application-side generation enables optimistic UI updates, idempotent API retries, and batch inserts without waiting for RETURNING id round-trips.

PostgreSQL 18 Native uuidv7() and Older PG Fallback

PostgreSQL 18 ships a native C implementation of uuidv7() that goes beyond basic millisecond resolution: it packs a sub-millisecond timestamp fraction into the rand_a bits and guarantees strict monotonicity within a backend process even if the system clock steps backward slightly via NTP adjustment. It even accepts an optional interval offset (uuidv7('-1 hour')) for generating deterministic test fixtures or time-partition boundaries.

-- PostgreSQL 18+: native monotonic RFC 9562 UUID v7
CREATE TABLE ledger_entries (
  id          uuid PRIMARY KEY DEFAULT uuidv7(),
  account_id  uuid NOT NULL,
  amount_cents bigint NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now()
);

-- Extract the embedded UTC timestamp directly from any UUID v7 in PG 18
SELECT
  id,
  uuid_extract_timestamp(id) AS embedded_ts,
  uuid_extract_version(id)   AS uuid_version
FROM ledger_entries
ORDER BY id DESC
LIMIT 10;
PostgreSQL 18 native UUID v7 primary key with timestamp extraction

If your production cluster is still running PostgreSQL 15, 16, or 17, you do not need to wait for a major upgrade. You can install the pg_uuidv7 extension or create a lightweight, pure-SQL uuidv7() helper using clock_timestamp() and gen_random_bytes() from pgcrypto, then swap seamlessly to the native function when you upgrade to PostgreSQL 18.

TypeScript (Node.js / Edge) and Kotlin Generation

In Node.js 22+, Bun, Deno, and Kotlin backend services, use a battle-tested RFC 9562 library that enforces monotonicity within the same millisecond rather than naive random-only implementations. Naive UUID v7 generators fill rand_a with pure randomness, meaning two records created inside the same millisecond during a bulk loop can sort out of order. Libraries like uuid (v11+) in TypeScript or uuid-creator in JVM/Kotlin maintain an atomic per-millisecond counter so rapid batch inserts stay strictly sequential.

import { v7 as uuidv7 } from "uuid";

// Optional state object ensures strict monotonicity across same-ms calls
let lastMsecs = 0;
let lastSeq = 0;

export function nextEntityId(): string {
  const now = Date.now();
  if (now === lastMsecs) {
    lastSeq = (lastSeq + 1) & 0x7fffffff;
  } else {
    lastMsecs = now;
    lastSeq = 0;
  }
  return uuidv7({ msecs: now, seq: lastSeq });
}

// Batch insert: IDs remain strictly increasing in the PostgreSQL B-Tree
const batch = events.map((evt) => ({
  id: nextEntityId(),
  payload: evt,
}));
Monotonic RFC 9562 UUID v7 generation in TypeScript with Node.js crypto

5. Security Implications: Timestamp Leakage vs. Opaque External IDs

Every engineering trade-off has a sharp edge, and UUID v7's trade-off is metadata visibility. Because the first 12 hexadecimal characters encode the exact creation millisecond in plaintext, anyone who sees a UUID v7 in a browser URL (/invoices/0193a8f2-4c10-7b2e-9a4f-31c8d7e90412) can trivially decode when that record was created down to the millisecond. While UUID v7 still prevents sequential enumeration attacks—an attacker cannot guess id + 1 thanks to the 62+ random trailing bits—exposing timestamps can still leak sensitive business intelligence.

Consider a B2B SaaS platform or healthcare portal. If a competitor creates two trial accounts a week apart, they cannot count total users from UUID v7 alone (unlike auto-incrementing integers), unless you also leak a monotonic counter that resets infrequently or exposes burst rates. More subtly, exposing an account's exact creation timestamp in a support ticket URL or password reset token could assist social-engineering attackers or correlate anonymous submissions with real-world activity logs.

6. Zero-Downtime Migration from UUID v4 to UUID v7

One of the biggest operational advantages of UUID v7 over migrating to BIGINT or TEXT ULIDs is complete binary schema compatibility. A PostgreSQL uuid column happily holds existing UUID v4 rows alongside brand-new UUID v7 rows without altering a single table column, foreign key constraint, or API contract.

You should almost never rewrite historical UUID v4 primary keys on a live production database. Rewriting primary keys forces cascading updates across every child table, invalidates cached webhooks, breaks bookmarked URLs, and invalidates external partner references. Instead, adopt a forward-only switch: update your column default and application generators to emit UUID v7 for all new rows, then run REINDEX INDEX CONCURRENTLY once the working set shifts to remove legacy v4 fragmentation.

  • Verify every ORM, API schema validator (Zod, Joi, OpenAPI), and downstream warehouse accepts RFC 9562 version 7 in the 13th hex position (some legacy regex validators hardcode [1-5] instead of [1-8]).
  • Switch application ID factories and PostgreSQL DEFAULT expressions from gen_random_uuid() to monotonic uuidv7() in a standard rolling deployment with zero schema locks.
  • Leave existing historical UUID v4 rows untouched; confirm that application code never assumes ORDER BY id sorts legacy v4 records chronologically before the cutover timestamp.
  • Monitor pg_stat_bgwriter, WAL generation bytes/hour, and B-Tree leaf density using the pgstattuple extension (pgstatindex('table_pkey')) over the following 14 days.
  • Schedule REINDEX INDEX CONCURRENTLY during a low-traffic window after cutover to reclaim legacy UUID v4 page-split bloat without blocking production reads or writes.
  • Audit external-facing URLs and ensure bearer tokens, webhook secrets, and invitation links continue using pure CSPRNG tokens rather than UUID v7.

Frequently asked questions

Yes, they are completely compatible at the storage and wire-protocol level. Both formats occupy exactly 16 bytes inside a standard PostgreSQL uuid column, and existing foreign keys, joins, and equality lookups continue working without interruption. The only caveat is that sorting by id will only reflect chronological order for rows created after your cutover date, so keep an explicit created_at column if you need historical timeline queries across legacy v4 records.

Not necessarily. If your database runs on a single primary cluster and you never generate IDs on clients, offline mobile apps, or distributed ingestion pipelines before hitting PostgreSQL, an 8-byte BIGINT GENERATED ALWAYS AS IDENTITY remains the smallest and fastest primary key possible. Adopt UUID v7 when you need globally unique, non-enumerable, distributed identifiers without sacrificing B-Tree write performance or paying the 2x WAL penalty of UUID v4.

For PostgreSQL-backed systems, RFC 9562 UUID v7 is now the clear default choice. While ULID offers an attractive 26-character Crockford Base32 text representation, UUID v7 enjoys native 16-byte storage, zero custom encoding glue, built-in uuidv7() and uuid_extract_timestamp() functions in PostgreSQL 18, and first-class support across every ORM, GraphQL scalar, and OpenAPI schema. If you want compact URLs, you can Base62-encode a UUID v7 at the API edge while keeping native uuid storage internally.

Clock skew—such as an NTP step backward of a few milliseconds—can cause naive UUID v7 generators to produce timestamps slightly earlier than previously emitted IDs. Production-grade implementations, including PostgreSQL 18's native uuidv7() and RFC 9562 Section 6.2 compliant libraries, mitigate minor backward jumps by holding the last observed timestamp and incrementing the monotonic sub-millisecond counter until wall-clock time catches up, preserving strict local ordering.

No, you should still store an explicit created_at timestamptz column on core domain tables. Although PostgreSQL 18 lets you extract timestamps with uuid_extract_timestamp(id), relying solely on the primary key for business timestamps couples domain semantics to identifier generation. Keeping created_at preserves clarity for analytics queries, supports backfilled historical imports with custom dates, and avoids surprising behavior when client-generated IDs experience clock skew.

Sources

ShareLinkedInX
Hamza Fazal, Founder, DEESU

Written by

Hamza Fazal

Founder, DEESU

Muhammad Hamza Fazal is the Founder of DEESU. An Android and full-stack web developer and digital marketer based in Islamabad, he founded DEESU in May 2022 and leads its engineering operations, product strategy, and client software delivery.

More from Hamza

Need help with this?

Reply within 1 business day

Tell us what you're building.

Send the problem, not a polished brief. We'll tell you what it actually takes to ship it: stack, timeline and cost, before you commit to anything.