UUID v4 vs v7: which one to use for database keys
UUIDs are popular primary keys: any server, phone or browser can create one without asking the database, and they don’t reveal how many orders or users you have. But teams that switch from auto-increment integers to random UUIDs often notice inserts slowing down as a table grows into the millions. The cause is not UUIDs in general — it is random UUIDs. Version 7 fixes that, with one trade-off you should understand before adopting it.
Anatomy of a UUID
A UUID is a 128-bit number, usually written as 32 hex digits in five groups: 8-4-4-4-12. The current standard is RFC 9562 (2024), which replaced RFC 4122 and added versions 6, 7 and 8. Two fields are fixed in every modern UUID:
- Version — 4 bits, the first hex digit of the third group. A
4there means v4, a7means v7. - Variant — the top 2 bits of the fourth group are
10, so its first hex digit is always8,9,aorb.
7a8d7dc8-90c5-429d-9850-667f47584c94 ← v4 (version 4, variant digit 9)
01a0e105-0e00-7014-8d82-8f82c27a30ca ← v7 (version 7, variant digit 8)
That leaves 122 bits for the actual content. What goes into those bits is the whole difference between v4 and v7.
v4: 122 random bits
A v4 UUID is pure randomness from a cryptographically secure generator. How likely is a collision? By the birthday problem, with n UUIDs the probability of any duplicate is about n² / (2 × 2¹²²):
| UUIDs generated | Chance of at least one duplicate |
|---|---|
| 1 billion (10⁹) | about 9.4 × 10⁻²⁰ |
| 1 trillion (10¹²) | about 9.4 × 10⁻¹⁴ |
| 2.7 × 10¹⁸ | about 50% |
Reaching a 50% chance would take a billion UUIDs per second for roughly 86 years. In practice, v4 collisions come from bugs — a badly seeded or non-cryptographic random generator, or cloned virtual machines — not from the math. Always use your platform’s secure generator, never Math.random().
Why random keys hurt B-tree indexes
Most databases store primary keys in a B-tree, kept in sorted order in fixed-size pages. With an auto-increment key, each new row goes at the right-hand end of the tree: the same few pages stay hot in memory and fill up completely. With v4 keys, each insert lands on a random page anywhere in the index. That causes:
- Page splits. When a full page receives a new key in the middle, the database splits it into two half-full pages. The index gets bigger and more fragmented than it needs to be.
- Poor locality. Because any page may be needed next, the whole index must fit in memory to stay fast. Once it doesn’t, inserts start waiting on disk reads.
- More write volume. Touching many different pages means more dirty pages to flush and, in PostgreSQL, more full-page images in the write-ahead log.
In MySQL’s InnoDB the effect is stronger, because the table itself is stored in primary-key order (a clustered index), and every secondary index stores the primary key too.
When does it matter? For a table with a few hundred thousand rows, almost never — the index fits in memory and you won’t measure a difference. It starts to matter with tens of millions of rows, high insert rates, or indexes larger than RAM. Don’t rewrite a small app for this; do choose carefully for a new high-volume table.
v7: timestamp first, then randomness
A v7 UUID starts with a 48-bit Unix timestamp in milliseconds, followed by the version, then random bits (74 in total after the version and variant). Because the time is at the front, new UUIDs sort after old ones, and inserts go to the end of the index — like auto-increment, but still generated anywhere without coordination.
| Bits | Field |
|---|---|
| 48 | Unix time in milliseconds (big-endian) |
| 4 | Version (0111 = 7) |
| 12 | Random, or extra sub-millisecond precision / counter |
| 2 | Variant (10) |
| 62 | Random |
48 bits of milliseconds lasts until the year 10889, so overflow is not a concern. Two details to know:
- Order inside one millisecond is not guaranteed unless your generator uses the optional counter method from RFC 9562. Treat v7 as “roughly time-ordered”, not as a strict sequence.
- It leaks creation time. Anyone who sees the ID can read when it was created. For public IDs such as an invoice or a user profile URL, decide whether that is acceptable.
// Read the creation time from a v7 UUID
const id = "01a0e105-0e00-7014-8d82-8f82c27a30ca";
new Date(parseInt(id.replace(/-/g, "").slice(0, 12), 16)).toISOString();
// "2026-09-27T04:00:00.000Z"
Alternatives in brief
- Auto-increment integers — smallest (4 or 8 bytes) and fastest, but need the database to assign them, and they reveal counts. Still the right choice for many internal tables.
- ULID — the same idea as v7 (48-bit millisecond time + 80 random bits), written as 26 Crockford Base32 characters. It predates v7; for new work, v7 has the advantage of fitting native UUID columns and tools.
Generating UUIDs
// JavaScript: v4 is built in (browsers in secure contexts, Node.js)
crypto.randomUUID(); // "7a8d7dc8-90c5-429d-9850-667f47584c94"
// v7 by hand, following the RFC 9562 layout
function uuidv7() {
const bytes = crypto.getRandomValues(new Uint8Array(16));
let ms = BigInt(Date.now());
for (let i = 5; i >= 0; i--) { bytes[i] = Number(ms & 0xffn); ms >>= 8n; }
bytes[6] = (bytes[6] & 0x0f) | 0x70; // version 7
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10
const hex = [...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)}`;
}
In production, the widely used uuid npm package also provides v7().
-- PostgreSQL
SELECT gen_random_uuid(); -- v4, built in since PostgreSQL 13
SELECT uuidv7(); -- v7, PostgreSQL 18 and later
CREATE TABLE orders (
id uuid PRIMARY KEY DEFAULT uuidv7(),
created_at timestamptz NOT NULL DEFAULT now()
);
# Python
import uuid
uuid.uuid4() # every version of Python 3
uuid.uuid7() # Python 3.14 and later
Store them as 16 bytes, not text
The text form is 36 characters; the value is 16 bytes. Storing text more than doubles the size of the key and of every index and foreign key that contains it, and string comparison is slower than byte comparison.
- PostgreSQL: use the native
uuidtype (16 bytes). - MySQL: use
BINARY(16)withUUID_TO_BIN()andBIN_TO_UUID(). Don’t pass the “swap” flag for v7 — it reorders the bytes for v1 and would break v7’s time ordering. - JSON and APIs: the standard lowercase hyphenated string is fine; convert at the database boundary.
FAQ
Should I migrate my existing v4 keys to v7?
Usually not. Changing primary keys means rewriting every foreign key. If inserts are fine today, keep v4 and use v7 for new tables. Migrate only if you’ve measured an index problem.
Is v7 less secure than v4?
It has fewer random bits (74 vs 122), which is still far too many to guess. The real difference is the readable timestamp. Neither version should be used as a secret, such as a password-reset token — use a dedicated random token for that.
Can I sort by a v7 UUID instead of a created_at column?
Roughly, yes, at millisecond precision — but clocks on different servers drift, and order within one millisecond may be random. Keep a real timestamp column if exact ordering or reporting matters.