API & Backend

UUID v4 vs v7: Which to Use for Database Primary Keys

UUIDv7 vs UUIDv4 for database keys: RFC 9562 layout, a 2M-row PostgreSQL benchmark we ran, how to generate v7, and when v4 is still the right call.

TechLogHub Editorial
November 25, 2026
15 min read
0 views

Share Article

TechLogHub cover: UUIDv7 bit layout with a 48-bit timestamp, and v7 keys appending to the right edge of a B-tree

UUID v4 vs v7: Which to Use for Database Primary Keys

Quick answer: Use UUIDv7 for new primary keys and UUIDv4 for anything that must not reveal when it was created. Both are 128 bits and both are standard under RFC 9562, but v7 puts a millisecond timestamp in its first 48 bits, so new keys land at the end of a B-tree instead of at random spots. In our PostgreSQL 16.15 test with 2 million rows, the v7 index was 60 MB with 0% leaf fragmentation against 76 MB and 49.91% for v4, and the bulk load took about half as long.

UUIDv4 has been the default "random ID" for two decades, and it is still the right answer for tokens, public identifiers and anything where guessability or timing matters. For database primary keys it was always a compromise: you got IDs that any service could mint without coordination, and you paid for it with a scattered, bloated index. UUIDv7 removes most of that cost. This guide shows what changed, what we measured, and where v7 is the wrong choice.

Everything below was checked against the primary sources on 25 November 2026, and every number in the benchmark and code blocks came from runs we did that day.

What RFC 9562 changed

For 19 years the UUID standard was RFC 4122. In May 2024 the IETF published RFC 9562, which obsoletes RFC 4122 and adds three new versions. The full set now looks like this:

VersionWhat it isUse it today?
1Gregorian timestamp plus node (often a MAC address)Legacy only
2Reserved for DCE SecurityNo
3Name-based, MD5Only for deterministic IDs from names
4Random or pseudorandomYes: tokens, public IDs, anything opaque
5Name-based, SHA-1Deterministic IDs; prefer over v3
6v1 with the timestamp fields reordered for sortingOnly to migrate v1 systems
7Unix epoch milliseconds plus random bitsYes: database keys, event IDs
8Custom, vendor-defined layoutOnly with a written spec of your own

The RFC also defines two special values, the Nil UUID (all 128 bits zero) and the Max UUID (all 128 bits one). It says new systems that would have used v1 or v6 should use v7 instead.

The practical news is v7. It is the version the RFC points new database keys at: sortable by creation time, generated without coordination, and still a plain 128-bit uuid column in every database that already supports UUIDs.

How UUIDv7 is laid out

A UUIDv7 is 128 bits split into five fields, read left to right in big-endian order:

BitsFieldContent
0–47unix_ts_msMilliseconds since 1970-01-01 UTC, 48 bits
48–51ver0111 (7)
52–63rand_a12 bits: random, or a counter, or sub-millisecond time
64–65var10 (the RFC variant)
66–127rand_b62 bits: random, or part of a counter

That leaves at least 62 bits of randomness per ID and up to 74 if an implementation fills rand_a with random data too. Compare that with v4, which has 122 random bits and no structure beyond the version and variant bits.

Because the timestamp is the most significant part, sorting v7 values as raw bytes, or as lowercase hex strings, sorts them by creation time. You can see the timestamp in the text form: the first 12 hex digits are the milliseconds.

$ node -e "const {v7}=require('uuid'); const id=v7(); console.log(id); \
  console.log(new Date(parseInt(id.replace(/-/g,'').slice(0,12),16)).toISOString())"
01a21060-b94c-765c-a9e7-c285f4eae3e2
2026-11-25T01:45:04.076Z

That is the trade-off in two lines. Anyone who sees a v7 ID knows to the millisecond when it was minted. We return to that in the section on when not to use it.

What happens inside one millisecond

A database under load can create hundreds of rows in one millisecond. If rand_a and rand_b were purely random, IDs created in the same millisecond would sort randomly among themselves. Section 6.2 of the RFC describes three optional ways to keep them in order: a fixed-length counter in rand_a, a randomly seeded counter that increments by a random amount, or extra sub-millisecond timestamp bits in rand_a. Implementations pick one, and they do not all pick the same one:

  • PostgreSQL 18 uuidv7() documents its layout as millisecond Unix timestamp plus a sub-millisecond timestamp plus random bits, per the PostgreSQL 18 UUID functions page.
  • Python 3.14 uuid.uuid7() "uses a 42-bit counter to guarantee monotonicity within a millisecond", per the Python 3.14 uuid docs.
  • The npm uuid package keeps internal state between calls to improve uniqueness and accepts a 32-bit seq option, per its README. Passing your own options bypasses that internal state.

We checked the ordering claim directly. In Python 3.14.6 we generated 100,000 v7 IDs in a loop and compared the generated order with the sorted order:

$ python3.14 -c "
import uuid; from collections import Counter
xs=[uuid.uuid7() for _ in range(100000)]
print('sorted==generated:', xs==sorted(xs),
      'strsorted:', [str(x) for x in xs]==sorted(str(x) for x in xs))
c=Counter(x.time for x in xs)
print('distinct ms:', len(c), 'max per ms:', max(c.values()))"
sorted==generated: True strsorted: True
distinct ms: 215 max per ms: 605

Up to 605 IDs shared a single millisecond and the order still held, both as UUID objects and as strings. The same check with uuid 14.0.3 on Node 22.23.5 (100,000 calls to v7()) also came back sorted. That guarantee is per generator, though. Two app servers minting IDs in the same millisecond will interleave, and clock skew between machines can put a newer ID before an older one. That is fine for index locality. It is not a reliable event order across machines.

Benchmark: 2 million rows, v4 vs v7 vs bigint

Why random keys hurt a B-tree

A primary key index in PostgreSQL, MySQL InnoDB or SQL Server is a B-tree kept in key order. With a sequential key, every insert goes to the rightmost leaf page. When that page fills, the database starts a new one and the old page stays full.

A v4 key has no order, so each insert lands on a random leaf. Once the index is larger than memory, many of those inserts need a page read first. When a page in the middle fills, it splits in two, and both halves end up about half full. Over time the index settles at a lower average fill, so it is larger, caches worse and writes more pages per insert. v7 behaves like a sequential key at the page level, because new IDs are always greater than old ones from the same generator.

That is the theory. Here is what it looked like on real data.

The test setup

Setup, all run on 25 November 2026 in a Linux container:

  • PostgreSQL 16.15 with default settings (128 MB shared_buffers). Version 16 has no built-in uuidv7(), so we generated the IDs outside the database.
  • 2,000,000 IDs each from Python 3.14.6 uuid.uuid4() and uuid.uuid7(), written to text files.
  • Tables with a single uuid PRIMARY KEY column, loaded with \copy so the index is maintained row by row during the load.
  • A third table with bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY and one int column, filled with INSERT ... SELECT generate_series(...), as a baseline for index size.
  • pgstatindex() from the pgstattuple extension for leaf density and fragmentation.
CREATE TABLE t4 (id uuid PRIMARY KEY);
CREATE TABLE t7 (id uuid PRIMARY KEY);
\copy t4 FROM '/tmp/pgd/v4.txt'
COPY 2000000
Time: 6266.619 ms (00:06.267)
\copy t7 FROM '/tmp/pgd/v7.txt'
COPY 2000000
Time: 3120.110 ms (00:03.120)
KeyLoad timeIndex sizeHeap sizeAvg leaf densityLeaf fragmentation
UUIDv46.27 s76 MB85 MB71.77%49.91%
UUIDv73.12 s60 MB85 MB90.04%0%
bigint identity3.97 s*43 MB84 MB90.08%0%

*The bigint load used INSERT ... SELECT rather than \copy and wrote an extra column, so compare its index size and density, not its time.

Three things stand out:

1. v7 halved the load time. Same row count, same column type, same command. The only difference was key order. 2. The v4 index was 27% bigger than v7 (76 MB against 60 MB) with identical data volume, because its leaf pages averaged 72% full against 90%. 3. v7's index had the same page density as bigint. It was still 40% bigger in absolute terms, because each key is 16 bytes instead of 8. pg_column_size() reports 16 for a uuid, 8 for a bigint and 40 for the same UUID stored as text. Never store UUIDs as strings.

This test is a best case for v4. The whole index fits in RAM, so v4 never pays the random read that hurts most in production. On a table whose index is larger than memory, the gap usually gets wider. Run it on your own hardware before quoting our ratios. The setup above is short enough to copy, and you can tidy the SQL with the SQL formatter before committing it to a migration.

Generating v7 in your stack

PostgreSQL 18 and later

PostgreSQL 18 added native functions, documented on the UUID functions page:

CREATE TABLE orders (
  id uuid PRIMARY KEY DEFAULT uuidv7(),
  created_at timestamptz NOT NULL DEFAULT now()
);

SELECT uuidv7();                          -- time-ordered
SELECT uuidv4();                          -- alias of gen_random_uuid()
SELECT uuidv7(interval '-1 hour');        -- timestamp shifted by the interval
SELECT uuid_extract_timestamp(id) FROM orders LIMIT 1;  -- works for v1 and v7
SELECT uuid_extract_version(id) FROM orders LIMIT 1;

The optional shift argument moves the embedded timestamp. The docs say infinite intervals are rejected and the result must fit the 48-bit field. uuid_extract_timestamp() returns null for versions other than 1 and 7. On PostgreSQL 13 to 17 you can generate v7 in the application, or use an extension such as pg_uuidv7.

Python 3.14

import uuid
order_id = uuid.uuid7()
order_id.version   # 7
order_id.time      # milliseconds since the Unix epoch for v7
uuid.NIL, uuid.MAX # new constants in 3.14

uuid6(), uuid7(), uuid8(), NIL and MAX are all marked "Added in version 3.14". On older Pythons you need a third-party package.

JavaScript and TypeScript

import { v7 as uuidv7, v4 as uuidv4, version } from 'uuid';
const id = uuidv7();      // '01a2105d-0090-777f-b157-71d6c51376d3'
version(id);              // 7
crypto.randomUUID();      // built in, but version 4 only

The README says uuid dropped CommonJS starting with version 12, so use ESM imports. The built-in crypto.randomUUID() in Node and browsers only produces v4. If your IDs travel through JSON payloads, generate the types with JSON to TypeScript or a runtime schema with JSON to Zod, then tighten the id field to a UUID check.

Database default or application code?

Both work, and they fail differently. A column default such as DEFAULT uuidv7() keeps one clock in charge, so IDs from every app server come from the database's clock and stay in a single order. It also means an ID does not exist until the insert returns, so the application has to read it back with RETURNING id.

Generating in the application gives you the ID before anything touches the database. That is useful when you write a parent row and its children in one batch, when a client retries a request and you want the retry to reuse the same ID, or when you publish an event and write the row in the same step. The cost is that every app server's clock now feeds the key order. A server whose clock runs a few seconds fast creates IDs that sort ahead of everyone else's, which is harmless for the index and confusing if anyone reads order into the IDs.

A reasonable rule: let the database generate the ID unless you need it before the insert. If you do generate in the application, use the same library and version everywhere, so every service follows the same monotonicity method.

Validating a v7 string

Version and variant live in fixed positions, so a strict regex is short:

^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$   (case-insensitive)

01a2105d-0090-777f-b157-71d6c51376d3  True
7504525a-3456-416e-93b2-495757d3ae66  False   (a v4)
01A2105F-7BFF-7234-99C9-5C7AF18137DA  True    (uppercase)
00000000-0000-0000-0000-000000000000  False   (Nil)

Paste it into the regex tester with your own samples before shipping it. Accept uppercase input but store and emit lowercase, because mixed case breaks string sorting.

v4 vs v7 vs bigint vs v6: the decision table

NeedUUIDv4UUIDv7bigint identityUUIDv6
Generate anywhere without coordinationYesYesNo (database sequence)Yes
Index locality on insertPoorGoodBestGood
Storage per key16 bytes16 bytes8 bytes16 bytes
Reveals creation timeNoYes, to the millisecondNo, but reveals order and volumeYes
Safe as an unguessable tokenClosest (122 random bits)NoNoNo
Merge data from several databasesEasyEasyCollisionsEasy
Built into PostgreSQL 18YesYesYesNo
Python stdlibYes3.14+n/a3.14+

How to read it:

  • Single database, internal IDs only, no plan to shard or merge: bigint identity is still smaller and faster. v7 is not a reason to migrate a working bigint schema.
  • IDs created in many services, offline clients, or before the row reaches the database: v7.
  • IDs exposed in URLs or APIs where timing is sensitive: v4 for the public ID, even if v7 stays as the internal key.
  • An existing v1 system you cannot replace: v6 keeps the v1 fields but reorders them so they sort. The RFC points new work at v7.

If you are comparing database or ORM tools that make this choice for you, the developer tools directory and the open-source listings are the quickest way to see what each one generates by default.

When not to use UUIDv7

v7 fixes the index problem. It also introduces three problems v4 never had.

It reveals when a record was created. We decoded a timestamp from an ID with one line of JavaScript above. If your URLs look like /invoices/01a2105d-..., anyone with one invoice link knows when that invoice was created, and with two links they can estimate how many you issue per hour. For user IDs, that also reveals sign-up dates. RFC 9562's security section warns against treating UUIDs as hard-to-guess secrets, and v7 makes that warning concrete. Use v4, or an opaque public ID, for anything a stranger can see.

It is not a security token. v7 has 62 to 74 random bits instead of 122, and its first 48 bits are predictable. Do not use it for password-reset links, session IDs, API keys or invite codes. Those need a cryptographically random value, and v4 from a CSPRNG or plain random bytes are both better. The same thinking applies to the jti claim in a token. Our guide to how JWTs work covers what that claim does and does not protect.

It is not a reliable clock. The embedded time comes from whatever machine generated the ID. Clocks drift, containers start with bad clocks, and the RFC itself advises treating UUIDs as opaquely as possible. Keep a real created_at column and do not parse business logic out of the ID. PostgreSQL's uuid_extract_timestamp() is handy for debugging. It is not a substitute for a timestamp column.

There is a smaller trade-off too. Time-ordered keys send every insert to the rightmost index page, which is exactly what you want on a single PostgreSQL primary. If you run a distributed database that splits tables into key ranges, the same property sends every new row to one range. Check that database's own guidance before you assume v7 helps there.

Migrating an existing v4 table

You do not have to rewrite existing keys. v4 and v7 share the same column type, so you can change the default and let new rows use v7:

-- PostgreSQL 18
ALTER TABLE orders ALTER COLUMN id SET DEFAULT uuidv7();

Old rows keep their v4 IDs scattered through the index, and new rows append at the right edge. The index stops getting worse from that point on. A REINDEX (or REINDEX CONCURRENTLY) afterwards compacts the old pages if size matters. Nothing that reads the IDs needs to change, unless some code checks the version nibble or sorts by ID and expects random order. Search your codebase for both before deploying.

Measure your own index first

Before you change anything, find out whether you have the problem. The same pgstattuple functions we used in the benchmark work on any existing index, and on PostgreSQL 18 you can also count which UUID versions a table already holds:

CREATE EXTENSION IF NOT EXISTS pgstattuple;

SELECT avg_leaf_density, leaf_fragmentation,
       pg_size_pretty(index_size) AS size
FROM pgstatindex('orders_pkey');

-- PostgreSQL 18+: how many keys of each version
SELECT uuid_extract_version(id) AS v, count(*)
FROM orders GROUP BY 1 ORDER BY 1;

Read the numbers against our baseline. A freshly loaded v4 index sat at about 72% leaf density and 50% fragmentation, while sequential keys sat at about 90% and 0%. If your index is close to the sequential numbers, or small enough to live comfortably in memory, the switch will not buy much and you can skip it. If it is large, low-density and on a write-heavy table, that is where v7 pays off. pgstatindex() reads the whole index, so run it on a replica or outside peak hours for anything big.

Watch two other things after the switch: insert latency at the 99th percentile, and the volume of write-ahead log per insert. Both should drop on a write-heavy table once new keys stop landing on random pages. If neither moves after a week, the index was never your bottleneck.

Do the same in application code that sets IDs before insert: swap the generator, keep the column. If you encode IDs for URLs, 16 bytes become a 22-character base64url string without padding. Our post on Base64 encoding explains why, and the Base64 tool will show you the result for a sample ID. Encoding hides the hyphens. It does not hide the timestamp, because anyone can decode it again.

FAQ

Is UUIDv7 an official standard?

Yes. UUIDv7 is defined in RFC 9562, published by the IETF in May 2024, which obsoletes RFC 4122. The same document defines versions 6 and 8, plus the Nil and Max UUIDs.

Is UUIDv7 faster than UUIDv4 in PostgreSQL?

For inserts into a B-tree primary key, usually yes. In our PostgreSQL 16.15 test with 2 million rows, loading v7 keys took 3.12 seconds against 6.27 seconds for v4, and the v7 index was 60 MB against 76 MB. Lookups by key cost about the same.

Can someone get the creation time from a UUIDv7?

Yes. The first 48 bits are milliseconds since the Unix epoch, so the first 12 hex digits of the string decode to the creation time. Do not use v7 for IDs where creation time or volume is sensitive.

Does PostgreSQL support UUIDv7 natively?

Yes, starting with PostgreSQL 18, which adds uuidv7(), uuidv4(), uuid_extract_timestamp() and uuid_extract_version(). Older versions need application-side generation or an extension.

Should I replace bigint identity keys with UUIDv7?

Usually not. A bigint key is half the size and our test showed its index at 43 MB against 60 MB for v7. Switch only if you need IDs created outside the database, merges across databases, or keys that do not reveal row counts.

Is UUIDv7 safe to use as an API key or reset token?

No. It has 62 to 74 random bits and a predictable timestamp prefix. Use a cryptographically random value such as UUIDv4 or random bytes for anything that must be unguessable.


Benchmarks and outputs were produced on 25 November 2026 with PostgreSQL 16.15, Python 3.14.6 and uuid 14.0.3. Rerun them on your own hardware before you quote the ratios.

Stay Updated

Get the next deep dive in your inbox

Subscribe for product analysis, engineering explainers, and practical guides published on TechLogHub.

See what launched this week

One email a week: new and trending developer tools, fresh comparisons, and what shipped. Unsubscribe in one click.