Developer Utilities

UUID v4 vs UUID v7: Which Should You Use?

Compare UUID v4 and v7, including random bits, timestamp leakage, index locality, ordering limits, and a safe migration plan.

uuidguiduuid-v4uuid-v7identifiersdatabases

UUID v4 vs UUID v7: Which Should You Use?

UUID v4 is random and easy to generate. UUID v7 puts a millisecond timestamp at the front, so newly generated values usually arrive close together in a B-tree index. That can improve index locality for insert-heavy workloads, but the size of any gain depends on the database, index, cache, and workload.

UUID v7 was standardized in RFC 9562. It fits the same 128-bit UUID column as v4, but changes ordering and reveals approximate creation time. This guide explains the tradeoff and how to migrate without treating UUID order as a perfect timestamp.

UUID Basics

A UUID (Universally Unique Identifier, also called a GUID in Microsoft-speak) is a 128-bit value usually written as 32 hex digits split into five groups:

xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
└── 8 ──┘└─4─┘└─4─┘└─4─┘└───── 12 ─────┘

Two fields have fixed positions regardless of version:

  • M — the version (1, 3, 4, 5, 6, 7, or 8). It's the first hex digit of the third group.
  • N — the variant (usually 8, 9, a, or b for the RFC 4122 / 9562 variant). First hex digit of the fourth group.

Many systems use v4; v7 is increasingly supported. Other versions, especially v1 and name-based v3/v5, also appear in production. Read the version digit rather than assuming the scheme.

UUID v4: Pure Randomness

UUID v4 fills 122 bits with cryptographically random data (the other 6 bits are taken by the version and variant markers):

fa2f0e31-d6f8-4b7c-9f8c-e47bd22b3b9e
         ^^^^ ^
         │    └── variant ('9' = RFC 4122 variant)
         └────── version (4)

Collision probability for properly generated v4 values is very small but not zero. The birthday bound reaches roughly 50% at about 2.7×10¹⁸ generated values. Use a database unique constraint and retry on conflict if duplicates would cause harm.

What v4 is good at:

  • Unpredictability when generated with a cryptographically secure random source. Even then, UUIDs are identifiers, not authorization tokens.
  • Statelessness. No clock, no counter, no coordination — any machine can mint one.
  • Simplicity. Every language's standard library has uuid.uuid4().

What v4 is bad at:

  • Database insert performance. Random inserts fragment B-tree indexes.
  • Natural sort order. UUIDs in a log or list are shuffled by creation order.
  • Index locality. Nearby insert times do not imply nearby v4 index keys; physical table-row layout depends on the database.

UUID v7: Time-Ordered Randomness

UUID v7 takes the same 128 bits but lays them out differently:

├─────── 48 bits ───────┤├ 12 ┤├──── 62 bits ────┤
 Unix milliseconds (BE)   rand   more random bits

The first 48 bits are a big-endian Unix timestamp in milliseconds. The remaining 74 bits may be random or include optional sub-millisecond precision and counters, as specified by RFC 9562. A sample v7 UUID:

01858def-3c8c-7b7c-9f8c-e47bd22b3b9e
└─── ms ───┘    ^
                └── version (7)

Because the timestamp leads the UUID, v7 values generally sort by generation time when compared using the same canonical format. Values created within the same millisecond are not necessarily ordered unless the generator implements a suitable monotonic counter. Clock skew and rollback can also break global time order.

What v7 is good at:

  • Better B-tree locality for many insert-heavy workloads; measure it on your own database.
  • Time-sortable across different milliseconds when clocks are sound.
  • Low collision probability when generated correctly, though uniqueness is not guaranteed.

What v7 gives up:

  • Timestamp privacy. A v7 identifier reveals its approximate generation time. Its random portion can still make the full value hard to guess.
  • Information disclosure. If you publish v7 IDs, you're publishing timestamps. That matters for rate limits, growth-metric leaks, or anti-enumeration defenses.

Side-by-Side Comparison

UUID v4 UUID v7
Standard RFC 4122 (2005) RFC 9562 (2024)
Total bits 128 128
Random bits 122 Up to 74; optional counter/precision can use some bits
Time component None 48-bit ms timestamp
Sortable No Yes (by time)
Unpredictable With a secure generator Random tail may be unpredictable; time is visible
DB index friendly Random key inserts Usually better insertion locality
Library support Everywhere Growing — mainstream in modern languages
Collision resistance Extremely high Extremely high

The B-Tree Problem (and Why v7 Solves It)

Many databases use a B-tree index for a UUID primary key. Random v4 keys can touch many index pages; time-ordered v7 keys tend to touch a narrower active range. PostgreSQL does not physically store table rows in primary-key order by default; its primary-key B-tree is separate. MySQL InnoDB and other storage engines have different layouts. See PostgreSQL's CLUSTER documentation for the distinction between index order and physical table order.

In a workload with a large index and many random inserts, this can cause:

  1. Lower cache locality. More index leaf pages may need to stay in memory.
  2. Page splits. Random insert positions can increase index maintenance.
  3. More I/O. The impact varies with cache size, fill factor, and write pattern.

v7 values usually cluster new index entries by time. They are not strictly monotonic across clocks or within the same millisecond, so inserts do not always land on one rightmost page.

Benchmark your own schema and query workload before migrating. A faster primary-key index does not automatically improve all reads or writes.

When v4 Is Still the Right Choice

Don't switch to v7 reflexively. v4 wins in these cases:

1. Public-facing IDs. A v7 UUID reveals its approximate generation time. If that is sensitive, consider v4 or a separate public identifier. Neither version replaces authorization checks.

2. Security tokens. Session IDs, password reset tokens, and API keys need a dedicated, high-entropy random token with an appropriate lifetime and server-side validation. Do not treat either UUID version as an access-control primitive; use an API key generator for test tokens.

3. Range-based sharding. A range partition keyed by v7 time can concentrate new writes in the newest shard. Hash-based sharding can distribute them, so examine your actual partitioning scheme.

4. Distributed systems with loose clock sync. v7 depends on clocks being roughly correct. If your system has nodes with significant clock skew, v7 UUIDs generated on different nodes may sort out of physical order.

When v7 Wins

1. Internal database primary keys. v7 is worth considering for write-heavy tables with a UUID B-tree. Check timestamp privacy and measure the effect before changing a working schema.

2. Event logs and append-only stores. Anything where rows are ordered by creation time benefits from sortable IDs.

3. Replacing auto-increment integers. v7 lets services generate IDs without a central sequence while retaining approximate time order. Storage and performance still differ from BIGSERIAL.

4. Approximate time-ranged queries. A v7 boundary may help, but keep created_at when exact event time, backfilled records, or clock skew matter.

Migrating from v4 to v7

You don't need a big-bang migration. A gradual approach works well:

  1. Generate new rows with v7. Leave existing v4 rows alone.
  2. Both versions have the same 128-bit layout, so no schema change is required (UUID columns don't care about version).
  3. New v7 values cluster in a time range of the index, while old v4 values remain scattered. Measure the result; a mixed index is not guaranteed to improve immediately.
  4. If you need consistent ordering, add a created_at column — don't rely on ORDER BY id in a mixed table.

ULID and Other Alternatives

Before v7 was standardized, several popular "sortable UUID" alternatives emerged:

  • ULID — 128 bits, Crockford-Base32 encoded, 48-bit timestamp + 80-bit randomness. Extremely popular from 2017–2023. Same idea as v7 but with a different text encoding.
  • KSUID (Segment) — 160 bits, timestamp + random, Base62 encoded. Not a UUID.
  • Snowflake (Twitter) — 64 bits, timestamp + machine ID + sequence. Much shorter but requires coordination.
  • UUID v6 — a re-ordering of the old v1 MAC-address-based UUID. Sortable, but v7 is simpler and doesn't leak MAC addresses.

For a new project, choose based on index behavior, time privacy, language support, and operational needs. v7 is attractive for time-ordered keys; v4 remains a simple default where ordering is not useful.

Generating UUIDs

In most languages, the standard library now supports both. Pseudocode:

import uuid

# v4 — pure random
id = uuid.uuid4()

# v7 — time-ordered (Python 3.13+)
id = uuid.uuid7()
import { v4 as uuidv4, v7 as uuidv7 } from "uuid";

const v4 = uuidv4();
const v7 = uuidv7();

The UUID Generator produces both in the browser — useful for seeding test data or picking the shape of an ID before committing to it.

Quick Reference

  • UUID v4 — 122 random bits from a secure generator. Inserts distribute across a B-tree. Use when time order is unnecessary or timestamp privacy matters.
  • UUID v7 — 48-bit millisecond timestamp plus up to 74 random/counter bits. Usually improves time locality in a B-tree, while revealing approximate generation time.
  • Both are 128 bits, the same length, and interchangeable at the column level.
  • New projects: default to v7 for internal IDs, v4 for public/security-sensitive ones.
  • Existing projects: a UUID column can hold both versions, but benchmark and review ordering assumptions before changing generators.
  • Don't use UUIDs as security tokens. Use API keys or cryptographically random strings.
  • Generate test UUIDs instantly with the UUID Generator.