For years, the advice was simple: if you want IDs that can be generated anywhere without coordination, use a random UUID (version 4). It’s still good advice for many systems. But in May 2024 the IETF published RFC 9562, which replaced the original UUID spec and standardized version 7: a UUID that starts with a timestamp, so new IDs sort after old ones. PostgreSQL 18, Python 3.14, and .NET 9 all generate it natively now.
This guide explains what’s actually inside each version, measures what the difference does to a real database index, and covers the cases where the old random v4 is still the better pick. Every code example was run before publishing, on Node.js 24, Python 3.14, .NET 10, PostgreSQL 18, MySQL 8.4, and SQL Server 2022.
The short answer#
What’s in a UUID#
A UUID is a 128-bit number, usually written as 32 hex digits in five groups: 01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17. Two small fields tell you how to read the rest. The 13th hex digit is the version (the 7 above), and the first one to three bits of the 17th digit are the variant, which is binary 10 for every UUID made to the RFC. That’s why the 17th digit of a standard UUID is always 8, 9, a, or b.
| Version | Built from | Status |
|---|---|---|
| 1 | A 60-bit timestamp in 100 ns steps since 1582, plus a MAC address or random node ID | Legacy. Its time fields are stored low bits first, so it doesn’t sort by time |
| 3 and 5 | An MD5 (v3) or SHA-1 (v5) hash of a namespace and a name | For IDs that must be the same every time, like a UUID for a URL |
| 4 | 122 random bits | The most widely used |
| 6 | v1’s fields reordered so it sorts by time | Only for systems that already use v1 |
| 7 | 48-bit Unix time in milliseconds, then 74 random bits | New in RFC 9562; the recommended time-based version |
| 8 | Anything you like, apart from the version and variant bits | For custom or experimental layouts |
RFC 9562 is explicit that v7 should be preferred over v1 and v6 for new systems. The real choice for most applications is therefore between the two in the title.
v4 and v7, bit by bit#
Version 4 (random)
Version 7 (time-ordered)
timestampversion (4 bits)variant (2 bits)random
Version 4 is 122 random bits plus the 6 fixed bits. Most platforms generate it from a cryptographically secure random number generator, and in JavaScript it’s one call:
// v4: 122 random bits from a cryptographic RNG.
// Built into Node.js, Deno, Bun and every modern browser.
const id = crypto.randomUUID();
console.log(id); // like 3b241101-e2bb-4255-8caf-4136c566a962 (13th digit: 4)Version 7 puts the current Unix time, in milliseconds, in the first 48 bits, most significant byte first. Because the timestamp comes first and is big-endian, comparing two v7 UUIDs byte by byte, or as lowercase strings, compares their creation times. Building one by hand shows how little there is to it:
// uuidv7.mjs: a UUIDv7 built by hand, to show the layout (RFC 9562, section 5.7).
export function uuidv7() {
const bytes = crypto.getRandomValues(new Uint8Array(16));
const ms = BigInt(Date.now());
for (let i = 0; i < 6; i++) bytes[i] = Number((ms >> BigInt(40 - 8 * i)) & 0xffn); // 48-bit big-endian time
bytes[6] = (bytes[6] & 0x0f) | 0x70; // version 7
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant: binary 10
const hex = Array.from(bytes, (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)}`;
}48 bits of milliseconds last until the year 10889, so running out isn’t a concern. The timestamp can also be read straight back out, which is handy when debugging and is also the main privacy trade-off, covered below:
// The first 48 bits of a v7 UUID are its creation time in Unix milliseconds.
const createdAt = (uuid) => new Date(parseInt(uuid.replace(/-/g, "").slice(0, 12), 16));
console.log(createdAt("01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17").toISOString()); // 2026-11-08T12:00:00.000ZOur UUID tool does the same: paste any UUID to see its version, variant, and, for v7, the moment it was made.
Why databases care about order#
Almost every relational database stores a primary key in a B-tree index: a sorted structure of fixed-size pages (8 KB in PostgreSQL, 16 KB in MySQL’s InnoDB, 8 KB in SQL Server). Where a new key lands in that sort order decides how much work an insert costs.
v4: inserts land anywhere
Every leaf page is “hot”, so the whole index must stay in memory; pages split in the middle and end up about 70% full.
v7: inserts go to the end
Only the last page is written. Full pages are left behind about 90% full and rarely touched again.
- Random keys (v4) spread writes over the whole index. Each insert goes to a different page, so to insert quickly the database needs the entire index in memory. Once the index is larger than the cache, most inserts start with a disk read.
- Pages split in the middle. When a page fills up, the database splits it into two half-full pages. Random inserts keep splitting pages all over the index, and the steady state is pages about 70% full. That makes the index larger, so it fits in memory even less.
- More write-ahead log. PostgreSQL writes a full copy of a page to its WAL the first time the page changes after a checkpoint. Touching many different pages means many full-page copies, which means more disk writes and more data for replicas and backups to ship.
- Time-ordered keys (v7) append. New keys are larger than all existing ones, so they go to the rightmost leaf page. The database can fill pages almost completely before moving to a new one, and the pages of older rows are left alone.
In MySQL’s InnoDB and in SQL Server tables with a clustered primary key, the effect is larger still, because the table’s rows are stored inside the primary key’s B-tree. A random key there scatters the rows themselves, not just the index entries. InnoDB also copies the primary key into every secondary index, so a 16-byte key makes every index on the table bigger.
Benchmark: 5 million rows#
To put numbers on it, we loaded two identical PostgreSQL 18 tables, one keyed by gen_random_uuid() (v4) and one by uuidv7(), with 5 million rows each, committed in batches of 10,000 the way an application would write them:
-- Insert 5 million rows into two identical tables, one keyed by v4 and one by v7, in batches of 10,000.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE TABLE t_v4 (id uuid PRIMARY KEY, n int NOT NULL);
CREATE TABLE t_v7 (id uuid PRIMARY KEY, n int NOT NULL);
CREATE PROCEDURE load(tbl text, gen text) LANGUAGE plpgsql AS $$
BEGIN
FOR b IN 0..499 LOOP
EXECUTE format('INSERT INTO %I SELECT %s, g FROM generate_series($1, $1 + 9999) g', tbl, gen) USING b * 10000;
COMMIT;
END LOOP;
END $$;
CHECKPOINT;
SELECT pg_current_wal_lsn() AS start \gset
\timing on
CALL load('t_v4', 'gen_random_uuid()');
\timing off
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'start')) AS wal_v4;
CHECKPOINT;
SELECT pg_current_wal_lsn() AS start \gset
\timing on
CALL load('t_v7', 'uuidv7()');
\timing off
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'start')) AS wal_v7;
SELECT i AS index, pg_size_pretty(pg_relation_size(i)) AS size, s.avg_leaf_density AS leaf_density
FROM unnest(ARRAY['t_v4_pkey', 't_v7_pkey']::regclass[]) AS i, pgstatindex(i) AS s;| 5,000,000 rows | v4 (random) | v7 (time-ordered) | Difference |
|---|---|---|---|
| Time to insert | 16.3–16.7 s | 7.0–7.2 s | v7 2.3× faster |
| Primary key index size | 191–194 MB | 150 MB | 23% smaller |
| Average leaf page fill | 70–71% | 90% | |
| WAL written | 899–901 MB | 743 MB | 17% less |
Two runs, PostgreSQL 18.6 in Docker with its default settings (128 MB of shared buffers), under Docker Desktop with 32 CPUs and 32 GB of memory. Treat the exact figures as an illustration rather than a prediction. The direction is consistent, though, and the gap grows as the index outgrows memory: at 5 million rows the v4 index is already larger than the buffer cache, and with hundreds of millions of rows it can decide whether the index fits in memory at all.
The 90% fill is not an accident: it’s PostgreSQL’s default B-tree fill factor, which it uses when it sees sequential inserts. The 70% for v4 is the classic figure for B-trees under random inserts.
Order within a millisecond#
A millisecond is a long time for a busy service. If two IDs are created in the same millisecond, the timestamp doesn’t decide their order and the random bits do. The hand-made uuidv7() above produced 49,859 out of 100,000 IDs that sorted before the ID made just before them, because a fast loop makes many IDs per millisecond.
That’s allowed by the spec, and a database index barely notices (the IDs still land on the same few pages). But if you want “sort by ID” to mean exactly “sort by creation order” within one process, RFC 9562 (section 6.2) describes three ways to get it: a counter in the bits after the timestamp, adding a small random increment to the previous ID, or using the 12 bits after the timestamp for sub-millisecond time. Good libraries use one of them. We checked the ones in this article:
| Generator | Strictly increasing? |
|---|---|
npm uuid 14, v7() | Yes, 1,000,000 in a row within one process |
Python 3.14, uuid.uuid7() | Yes, 1,000,000 in a row within one process |
PostgreSQL 18, uuidv7() | Yes, 1,000,000 in a row within one session |
| The hand-made function above | No, about half out of order within each millisecond |
No generator can promise order across several servers, since their clocks are never perfectly in step. IDs from different machines interleave roughly by time, which is all an index needs.
Generating v7 in your stack#
JavaScript and TypeScript
crypto.randomUUID() only makes v4. For v7, use the uuid package:
// In production, use a library that keeps IDs in order within the same millisecond (npm install uuid).
import { v7 as uuidv7, version } from "uuid";
const ids = Array.from({ length: 5 }, () => uuidv7());
console.log(ids.join("\n"));
console.log(version(ids[0])); // 7
console.log(ids.every((id, i) => i === 0 || ids[i - 1] < id)); // true: string order is creation orderPython
Python 3.14 added v6, v7, and v8 to the standard library. On older versions, use a package such as uuid6 or uuid-utils.
# Python 3.14 added uuid6(), uuid7() and uuid8() to the standard library.
import uuid
from datetime import datetime, timezone
a = uuid.uuid4()
b = uuid.uuid7()
print(a.version, b.version) # 4 7
print(datetime.fromtimestamp(b.time / 1000, tz=timezone.utc)) # for v7, .time is Unix millisecondsC# and .NET
.NET 9 added Guid.CreateVersion7() and the Version property:
// .NET 9 and later
Guid a = Guid.NewGuid(); // version 4
Guid b = Guid.CreateVersion7(); // version 7, using the current UTC time
Console.WriteLine($"{a.Version} {b.Version}"); // 4 7
Console.WriteLine(b);Java and Go
The JDK has no v7 generator yet; use a library such as uuid-creator or java-uuid-generator. In Go, the widely used github.com/google/uuid package has uuid.NewV7().
PostgreSQL
PostgreSQL 18 has uuidv7() built in (and uuidv4() as another name for gen_random_uuid()). The uuid type stores 16 bytes and compares them in order, so v7 keys sort by time:
-- PostgreSQL 18 generates v7 UUIDs natively.
CREATE TABLE orders (
id uuid PRIMARY KEY DEFAULT uuidv7(),
customer text NOT NULL,
total numeric(10, 2) NOT NULL
);
INSERT INTO orders (customer, total) VALUES ('ada', 19.99), ('alan', 5.00);
-- The creation time is in the key, so a separate created_at column is optional.
SELECT id, uuid_extract_version(id) AS version, uuid_extract_timestamp(id) AS created
FROM orders
ORDER BY id;In PostgreSQL 17 and earlier, generate the ID in your application and insert it; the column type and index work the same way.
MySQL and MariaDB
MySQL has no UUID column type, and its UUID() function makes version 1. Generate v7 in your application and store it as BINARY(16), not CHAR(36), which takes more than twice the space and compares more slowly:
-- MySQL has no uuid type: store the 16 bytes in BINARY(16), generated by your application.
CREATE TABLE orders (
id BINARY(16) PRIMARY KEY,
customer VARCHAR(100) NOT NULL
);
-- No "swap" flag: UUID_TO_BIN(?, 1) reorders v1 UUIDs, and would scramble the order of v7 ones.
INSERT INTO orders VALUES (UUID_TO_BIN('01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17'), 'ada');
SELECT BIN_TO_UUID(id) AS id, customer FROM orders;SQL Server
SQL Server’s uniqueidentifier type has an unusual sort order: it compares the last six bytes first. A v7 value’s timestamp is at the front, so it has almost no effect on the order:
-- SQL Server sorts uniqueidentifier by its LAST six bytes first, so v7 values don't sort by time.
SELECT CAST(v AS uniqueidentifier) AS id
FROM (VALUES
('01a1bb07-9a00-7c3d-9f1a-6b2d4e8c0a17'), -- 12:00:00.000
('01a1bb07-9a01-7a42-8e03-0c5f9b1d2e64'), -- 12:00:00.001
('01a1bb07-9a02-75b8-a6c4-3f8e7a9b0c21') -- 12:00:00.002
) AS t(v)
ORDER BY id;
-- Returns 001, 002, 000: sorted by the random last six bytes, not by time.On SQL Server, either store v7 values in a binary(16) column, which sorts byte by byte, or use NEWSEQUENTIALID() as the column default, which generates GUIDs that are sequential in SQL Server’s own order (though only per machine and only until a restart). Also note that .NET’s Guid.ToByteArray() writes the first three groups little-endian, so convert carefully when moving v7 bytes between .NET and a binary(16) column.
When v4 is the better choice#
v7 isn’t a free upgrade. It gives up two things that v4 has.
1. v7 tells everyone when it was made
Anyone who sees a v7 ID can read its creation time to the millisecond, as the createdAt function above shows. For an order ID, that’s usually harmless. For other IDs, it can leak more than you meant to:
- a user ID in a profile URL reveals when the account was created;
- IDs in an API reveal how many records you create per second, if someone collects enough of them;
- a document ID reveals when it was written, even if the page shows a different date.
If that matters, use v4 for anything you show outside your system. A common pattern is a v7 primary key for the database plus a separate v4 (or other random) public ID in its own indexed column.
2. Distributed databases want writes spread out
Databases that split a table into key ranges across many nodes, such as Google Spanner and CockroachDB, are the opposite case. There, time-ordered keys send every new row to the same range on the same node, which becomes a hotspot while the others sit idle. Both recommend random keys for this reason. Check your database’s guidance before switching: what helps a single B-tree can hurt a sharded one.
3. v7 depends on the clock
A server whose clock is wrong produces IDs that sort in the wrong place, and a clock that jumps backward can produce IDs that sort before ones already issued. Good libraries guard against backward steps within a process, but nothing can fix a clock that’s hours off. Keep your servers on NTP, and don’t use a v7 ID as the authoritative creation time for anything legal or financial: keep a proper timestamp column.
Neither one is a secret#
RFC 9562’s security section is blunt: don’t assume UUIDs are hard to guess, and don’t use them as security capabilities. That applies to both versions.
- v4 from a cryptographic random generator is very hard to guess in practice, but the spec doesn’t require a secure generator, and some older libraries didn’t use one.
- v7 gives away its first 48 bits to anyone who can estimate the time, leaving 74 random bits.
- IDs end up in logs, URLs, referrer headers, analytics, and screenshots. A secret needs to be treated as a secret.
For password-reset links, session IDs, and API keys, generate a token of at least 128 random bits for that purpose, and verify that the person using it is authorized. And never rely on an ID being unguessable as your only access control: check permissions on every request.
Collisions, in numbers#
Both versions have enough random bits that collisions aren’t a practical concern:
- v4 has 122 random bits. You’d need to generate about 2.7 × 1018 of them for a 50% chance of a single duplicate: a billion IDs per second for 86 years.
- v7 has 74 random bits per millisecond. Even a million IDs in one millisecond have about a 1 in 38 billion chance of a duplicate, and the next millisecond starts fresh. Libraries that use a counter make it impossible to create duplicates within a single process.
The real-world causes of duplicate UUIDs are bugs: a random generator seeded with the same value in every forked process, a container image with a frozen seed, or code that copies an ID instead of making a new one. A unique constraint on the column catches all of them.
Checklist#
FAQ#
Can I switch an existing v4 table to v7?
Yes, for new rows. Both are ordinary UUIDs in the same column type, so you can start inserting v7. Old rows keep their random positions in the index, but new rows go to the end, and the benefits apply from then on. Don’t rewrite existing IDs: they’re referenced from other tables, logs, and URLs.
Is v7 the same as ULID?
The idea is the same: a 48-bit millisecond timestamp followed by random bits. A ULID is written as 26 characters of Crockford base32 and has 80 random bits. v7 is an IETF standard, fits every existing UUID column and library, and gives up 6 bits for the version and variant.
Should I use a bigint instead?
An auto-incrementing bigint is 8 bytes instead of 16 and perfectly ordered, and it’s still a fine choice when one database hands out all the IDs. UUIDs win when IDs are created in many places (several services, offline clients, or before the row reaches the database) and when you don’t want IDs that count your rows.
What about v6?
v6 is v1 rearranged to sort by time. It exists for systems that already depend on v1’s layout. For anything new, RFC 9562 recommends v7.
Can two servers generate the same v7?
Only with odds like those in the collisions section, provided each uses a proper random generator. The timestamp doesn’t need to be unique: the 74 random bits are what keep IDs apart.
Try it in your browser
- UUID & GUID Generator: generate v4 or v7 UUIDs in bulk, or paste any UUID to see its version, variant and, for v7, the time it was made.