All entries
Chapter VIII
Journal · 23 Nov 2026 · 12 min read

UUIDv7 vs ULID in Postgres 18: 10M Rows Tested

UUIDv7 vs ULID vs UUIDv4 as Postgres primary keys, tested on 10M rows: index size, WAL, the en_US collation trap, and where v7 breaks payment IDs.

Store a ULID in a Postgres text column under the default en_US.utf8 collation and inserts run 2.5 times slower than the same values under COLLATE "C". On a million rows that fitted entirely in memory, that made the ULID table slower to fill than one keyed on random UUIDv4.

Most pages ranking for "uuidv7 vs ulid" compare bit layouts and stop there. Of the dozen top results I checked, none had numbers measured at scale, none named the three monotonicity methods in RFC 9562, and none mentioned that a UUIDv7 fails schema validation as an ISO 20022 UETR. One still says you need Postgres 17 and an extension. So I loaded 10 million rows per key type into Postgres 18.6 and measured what each one costs.

What Is the Difference Between UUIDv7 and ULID?

Both are 128 bits with a 48-bit Unix millisecond timestamp at the front, so both sort by creation time. The differences sit in the remaining 80 bits and in how they are written down.

UUIDv7ULID
SpecificationRFC 9562 (May 2024), IETF Standards TrackCommunity spec on GitHub, last commit May 2019
Layout after the timestamp4-bit version, 12 rand_a, 2-bit variant, 62 rand_b80 bits of randomness
Bits available for randomness7480
Canonical text36 chars, hex with hyphens26 chars, Crockford base32
Same-millisecond orderingThree optional methods (below)Increment the random part by 1; fail on overflow
Postgres typeNative uuidNone; text or a converted uuid

RFC 9562 lists ULID by name as prior art, alongside Snowflake and KSUID. UUIDv7 is the standardised descendant. Because the bit layouts line up, any ULID can be stored losslessly in a uuid column; you just lose the version nibble that tools like uuid_extract_version() read.

How Does uuidv7() Work in PostgreSQL 18?

Postgres 18.0 (25 September 2025) added uuidv7([shift interval]), uuidv4() as an alias for gen_random_uuid(), plus uuid_extract_timestamp() and uuid_extract_version(). Postgres 19.0, released on 19 November 2026, keeps the same function and adds uuid/bytea casts and a base32hex encoding, which I come back to below. Neither version has a native ULID type.

SELECT uuidv7(), uuid_extract_version(uuidv7()), uuid_extract_timestamp(uuidv7());
-- 01a20775-e9bb-782c-813f-9d7ad85876d1 | 7 | 2026-11-23 08:11:37.787+00

Generation cost is a non-issue. Ten million calls took a median of 4.0 s for uuidv7() and 4.3 s for gen_random_uuid(), about 0.4 µs per ID either way.

UUIDv4 vs UUIDv7 vs ULID: Postgres Benchmark on 10M Rows

Setup: Postgres 18.6 in Docker on a 2-vCPU, 2 GiB VM, default config (shared_buffers 128 MB, max_wal_size 1 GB, data checksums on, which is the Postgres 18 default). Each table held the key plus amount_minor bigint, currency char(3) and created_at timestamptz. I pre-generated IDs into staging tables in generation order, so the timed INSERT ... SELECT measures index maintenance rather than ID generation. The ULIDs came from a short monotonic generator written to the spec.

Primary keyBytes/keyPK indexLeaf densityHeapWALFull-page imagesInsert, median of 3
bigint8214 MB90.0%574 MB1,460 MB126.2 s
uuidv7()16301 MB90.0%651 MB1,624 MB126.8 s
ULID, text COLLATE "C"27474 MB90.1%805 MB1,951 MB177.8 s
ULID, text (en_US.utf8)27474 MB90.1%805 MB1,951 MB1841.4 s
gen_random_uuid() (v4)16390 MB69.5%651 MB3,217 MB266,65177.7 s

Treat the timings as rough. They swung by up to 4x between rounds on this VM (v7 ran between 6.2 and 25.7 s, v4 between 40 and 164 s). The size and density columns were identical in every round, and WAL repeated to within 21 kB for every key except v4, which I explain below.

So I reran the timing on 1 million rows, small enough that every index fits in shared buffers, five times each. Apart from one 715 ms outlier, each set of five sat within 8%:

Primary key, 1M rows in memoryInsert, median of 5
bigint517 ms
uuidv7()561 ms
ULID, text COLLATE "C"622 ms
gen_random_uuid() (v4)1,181 ms
ULID, text (en_US.utf8)1,571 ms

In memory, v4 costs about 2.1 times as much as v7. At 10 million rows, once the 390 MB index no longer fits in 128 MB of buffers, the median gap grows to 11 times.

Why Is UUIDv4 Slow as a Primary Key?

The density column explains most of it. The Postgres docs say B-tree leaf pages are filled to the fillfactor (90% by default) "when extending the index at the right (adding new largest key values)". Time-ordered keys always land on the rightmost leaf, so every split leaves a page 90% full. Random v4 keys land anywhere, pages split 50/50, and the index settles at the textbook ln 2, about 69.3% full. I measured 69.45%. Same 16-byte key, 30% more index.

The bigger cost is cache misses. The v4 insert read 3.29 million buffers from outside shared buffers; the v7 insert read 63,748, almost all of them from the staging table. Every random insert needs a different leaf page, and at 10 million rows most of those pages are cold.

Then there is WAL. After each checkpoint, the first change to any page writes a full-page image. Time-ordered keys keep touching the same few pages, so v7 wrote 12 images across the whole load. Random keys dirty pages across the index, so v4 wrote between 190,000 and 356,000, depending on how many checkpoints fell inside the run. That is why v4's WAL varied between rounds: a slower insert spans more checkpoints, writes more page images, and slows down further. The median was 3,217 MB of WAL against 1,624 MB for v7, and every byte of it goes to your replicas and backups.

Should You Store a ULID as text or uuid in Postgres?

Store it as uuid. As text, a ULID needs 26 characters plus a 1-byte header, and the index tuple pads from 24 bytes to 40. That is where the 57% bigger index and 24% bigger heap in the table come from.

The collation matters even more than the size. A text primary key under en_US.utf8, the default in the official Docker image, compares through the C library's locale rules on every B-tree step. The same values under COLLATE "C" compare as plain bytes. The bytes, the index size and the WAL volume were identical; only the comparison changed, and it cost 2.5 times the insert time in memory and 5.3 times at 10 million rows.

If you must keep text (an external ID you don't control, say), pin the collation and the alphabet:

CREATE TABLE payouts (
  id text COLLATE "C" PRIMARY KEY
     CHECK (id ~ '^[0-7][0-9A-HJKMNP-TV-Z]{25}$'),  -- uppercase Crockford ULID
  amount_minor bigint NOT NULL
);

The spec says decoders accept lowercase, so normalise to upper case before insert or the byte order stops matching time order. Stripe gives the same advice in MySQL terms for its own IDs: they can be up to 255 characters, and it suggests VARCHAR(255) COLLATE utf8_bin.

Postgres 19's new rtrim(encode(id::bytea, 'base32hex'), '=') produces a 26-character sortable string, and its docs also require COLLATE "C". It uses the RFC 4648 extended-hex alphabet (0-9, A-V), not Crockford, so the output is not a ULID even though it is the same length.

Is UUIDv7 Monotonic? Postgres, Rust, Python and Node Compared

RFC 9562 section 6.2 offers three ways to order IDs created in the same millisecond. Method 1 puts a dedicated counter of 12 to 42 bits after the timestamp. Method 2 treats the random bits as a randomly seeded counter and increments it. Method 3 replaces up to 12 random bits with a sub-millisecond clock fraction. Each library picks differently:

RuntimeFunctionSame-millisecond order
Postgres 18+uuidv7()Method 3 (12-bit fraction), monotonic per backend only
Rust uuidUuid::now_v7(), v7 feature, stable since 1.6.042-bit counter via ContextV7 since 1.9.0
Python 3.14uuid.uuid7()Method 1, 42-bit counter; advances the timestamp on overflow
Node 26.1crypto.randomUUIDv7()Docs: "not guaranteed to be strictly increasing"
npm uuid 10+v7()32-bit sequence, randomly seeded
Go google/uuid 1.5+NewV7()Sub-millisecond bits plus a bump, per process
.NET 9Guid.CreateVersion7()Random; no ordering within a millisecond
JDK 26UUID.ofEpochMillis(long)Caller supplies the time; 74 random bits

I checked the Postgres claim directly: one million consecutive uuidv7() calls in a single session came out strictly increasing. Across sessions, there is no such guarantee.

Two traps. On SQL Server, uniqueidentifier sorts by its last six bytes first, so a .NET v7 GUID is not index-friendly there at all. And if you use the Rust ulid crate, Ulid::new() became Ulid::gen() in 2.0.0 and then Ulid::generate() in 3.0.0, both in July 2026. A dependency bump will break your build.

For the B-tree, none of this matters much: a few keys out of order within one millisecond still land on the same rightmost page. It matters when code treats ID order as commit order. A transaction that takes its ID first can commit last, which is the same reason a BIGSERIAL outbox poller skips events, covered in my transactional outbox guide.

Can You Query a UUIDv7 Primary Key by Time?

Yes. Build the smallest possible v7 for a timestamp and range-scan the primary key:

CREATE FUNCTION uuidv7_floor(ts timestamptz) RETURNS uuid
LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$
  SELECT (lpad(to_hex(floor(extract(epoch FROM ts) * 1000)::bigint), 12, '0')
          || '70008000000000000000')::uuid
$$;

SELECT count(*) FROM payments WHERE id >= uuidv7_floor(now() - interval '1 hour');

On the 10-million-row table this planned as an index-only scan on the primary key with zero heap fetches, and no row sat below its own floor. Keep created_at anyway: the ID records when the ID was generated, by whichever clock generated it, which is not your booking time.

Does UUIDv7 Leak Information in Payment IDs?

It leaks the creation time to the millisecond, and uuid_extract_timestamp() reads it out in one call. On a payment shown next to its date on a receipt, that leaks nothing new. On a customer or merchant ID in a URL, it reveals when the account was opened. Unlike bigint, it does not reveal how many rows you have.

RFC 9562 section 8 says UUIDs "MUST NOT be used as security capabilities", and recommends v4 where security matters. Payout-claim links and password-reset tokens should not be any UUID. Postgres's uuidv7(shift) offsets the embedded time if you need to blur it. Until 18.6, an out-of-range shift produced a garbage UUID, and any shifted ID breaks the floor query above.

UUIDv7 vs ULID vs TypeID vs Snowflake: Which to Pick in 2026?

FormatSizeTextTime-orderedPostgres storage
UUIDv4128 bits, 122 random36 charsNouuid
UUIDv7128 bits36 charsTo the msuuid, native uuidv7()
ULID128 bits26 charsTo the msuuid after conversion, or pgx_ulid
TypeID (spec 0.3.0)UUIDv7 plus prefixUp to 90 charsTo the msuuid
Snowflake64 bits: 41 ms, 10 machine, 12 sequenceUp to 19 digitsTo the msbigint
KSUID160 bits27 chars, base62To the secondbytea or text

My position: store uuidv7() in a uuid column, and treat ULID as a text encoding for the API boundary, not a storage format. Snowflake halves the key size but makes you assign and police machine IDs, which is a coordination problem I'd rather not own for a payments ledger. TypeID gets you readable prefixed IDs like pay_01jf... while the database sees an ordinary v7.

I also expect new ULID adoption to fade to that encoding role within a couple of years. Postgres, Python, Node, .NET and the JDK now generate v7 natively, Go's de facto google/uuid has done so since 2023, and the ULID spec has not changed since 2019.

Which Payment IDs Must Stay UUIDv4 in the UK?

The UETR. In pacs.008 it is typed UUIDv4Identifier, with a literal 4 in the version position and lowercase hex only, so a v7 fails schema validation. I covered the full pattern in UETR vs EndToEndId vs TxId. Run a separate v4 generator for it.

Length limits catch the other formats:

FieldLimitHyphenated UUID (36)Hex UUID (32)ULID (26)
ISO 20022 EndToEndIdMax35TextToo longFitsFits
EndToEndIdentification via Faster Payments31 chars (Open Banking UK spec)Too longToo longFits
FPS / Bacs payment reference18 charsToo longToo longToo long

A TypeID with a three-letter prefix, pay_ plus 26 characters, is exactly 30 and still fits the Faster Payments limit. Nothing 128-bit fits an 18-character reference, so generate a short reference separately and map it.

What This Means for Payments Engineers

1. New tables on Postgres 18 or 19: id uuid PRIMARY KEY DEFAULT uuidv7(). On 17 or older, generate v7 in the application with one of the libraries above. 2. Never put sortable IDs in text under a natural-language collation. If text is unavoidable, use COLLATE "C", a CHECK on the alphabet, and upper-case normalisation. 3. Migrating from v4? Budget for a bloated index. I loaded 1 million v4 rows, then 1 million v7 rows into the same column. The v7 keys land in the middle of the v4 key space, not at the right edge, so pages split 50/50: those million rows took 54 MB of index against 30 MB in a v7-only table. REINDEX brought it back to 90% density (60 MB in total), but new v7 rows will go on splitting the same way, because v4 keys still sort above them. A fresh table or column is cleaner. 4. Keep UETRs on v4 and unit-test the generator against the schema regex. 5. Check field lengths before you choose a public ID format: 35 for EndToEndId, 31 if it travels over Faster Payments, 18 for the reference. 6. Never page through new rows by ID. Use a commit-aware cursor, not WHERE id > last_seen.

I'm Tom Wang, and I write these guides from test output where I can. The scripts here are short; run them against your own instance and collation before you take my numbers for yours.