UUIDv7 vs ULID: Sortable Identifiers That Do Not Destroy Your Write Performance
UUIDv4 randomness turns your clustered index into a write bottleneck. Here is how UUIDv7 and ULID fix the insertion hotspot, with Node.js generation code, Postgres index analysis, and the one case where ULID still wins.
Your user table is hitting 50,000 inserts per minute and the write latency graph looks like a heartbeat monitor during a panic attack. The query planner says the primary key index is 80% of the table size. Autovacuum cannot keep up. The on-call rotation is debating whether to page the DBA or just turn off the monitoring.
The cause is almost always the same: you are using UUIDv4 as a primary key, and every insert is landing in a random leaf page of your B-tree index. Postgres (or MySQL, or SQL Server) has to split pages, rebalance the tree, and flush dirty buffers all over the disk. The index grows fat with dead space. Writes that should be sequential appends become random I/O storms.
The fix is not “switch to bigserial.” Distributed systems still need decentralized ID generation. The fix is using a sortable identifier: one that carries time at the front, so inserts cluster near the end of the index where they belong. The two practical options today are UUIDv7 (RFC 9562, standardized May 2024) and ULID. Both give you time-ordered IDs without a central coordinator. Both beat UUIDv4 for write throughput. But they differ in encoding, storage size, collision resistance within a millisecond, and how much your ORM fights you.
This post walks through the B-tree mechanics that make UUIDv4 painful, compares UUIDv7 and ULID head-to-head, and ships working Node.js code you can drop into a service today.
Why random IDs murder write performance
A B-tree index stores keys in sorted order. If your primary key is a bigserial (1, 2, 3, …), every new insert appends to the rightmost leaf page. Postgres keeps that page hot in memory. Writes are cheap, sequential, and predictable.
If your primary key is a UUIDv4, the key space is effectively random. Insert 1 lands at leaf 47. Insert 2 lands at leaf 12,003. Insert 3 lands at leaf 892. The buffer cache is constantly evicting pages to make room for new ones. When a leaf page fills up, Postgres splits it: half the keys move to a new page, the parent page gets updated, and WAL is generated for every touched block. On a busy write workload, this is called an “insertion hotspot” only in the sense that the entire index becomes a hotspot.
You can see it in pgstattuple:
SELECT pg_size_pretty(pg_relation_size('users_pkey')) AS index_size,
avg_leaf_density,
leaf_fragmentation
FROM pgstatindex('users_pkey');
A UUIDv4 primary key on a high-insert table often shows leaf_fragmentation above 40% and avg_leaf_density below 60%. That means nearly half your index pages are half-empty, and the index is 1.5-2x larger than it needs to be. Every index scan reads more blocks. Every write waits on more locks. Your SSD is doing random I/O for a workload that should be append-only.
Sortable IDs fix this by making the key monotonically increasing over time. The first 48 bits encode a Unix millisecond timestamp. Inserts from the same millisecond cluster near each other, and inserts from the next millisecond cluster slightly to the right. The index becomes append-mostly. Page splits drop. Buffer cache efficiency rises. The DBA sleeps through the night.
UUIDv7: what changed and why it matters
UUIDv7 is part of RFC 9562, finalized in 2024. It replaces the UUIDv1 timestamp strategy (which leaked MAC addresses and had weird bit-shuffling) with something actually usable.
The 128-bit layout is clean:
- Bits 0-47: Unix timestamp in milliseconds, big-endian.
- Bits 48-51: version field (set to
0111, i.e., 7). - Bits 52-63: 12 random bits (the “rand_a” field).
- Bits 64-65: variant field (
10). - Bits 66-127: 62 random bits (the “rand_b” field).
Because the timestamp is at the very front in big-endian, the raw 16-byte binary representation sorts lexicographically by time. Postgres stores uuid columns as 16-byte binary. A UUIDv7 stored in a uuid column naturally sorts from oldest to newest without any special functions or index tricks.
Node.js 22.7.0 and later support UUIDv7 directly in the standard library:
import { randomUUID } from 'node:crypto';
// Node.js 22.7+
const id = randomUUID({ version: 7 });
// => 018ff4a0-... (starts with a timestamp prefix)
If you are on an older Node.js version, the uuid package (v10+) supports v7:
import { v7 as uuidv7 } from 'uuid';
const id = uuidv7(); // returns a string like 018ff4a0-...
Both outputs are RFC-compliant and safe to store in Postgres uuid columns.
One subtle advantage of UUIDv7: because the timestamp is millisecond-precision and the remaining 74 bits are random, you get about 1.9e22 possible values per millisecond. In practice, collisions are impossible without a broken RNG. But if you are generating thousands of IDs inside the exact same millisecond from a single process, the random suffix is flat. Some UUIDv7 implementations (including the Node.js one) use a monotonic random counter when multiple IDs are requested within the same millisecond, guaranteeing strict ordering even inside a single tick. That matters if your code batches inserts and assumes the generated array is sorted.
ULID: the string-native competitor
ULID predates UUIDv7 by several years and solved the same problem before the IETF standardized it. The spec is simpler: 48 bits of timestamp (millisecond precision) followed by 80 bits of randomness. The canonical representation is 26 Crockford base32 characters, all uppercase.
For example: 01JXZM7CZ7KQ1Y2A3B4C5D6E7F.
Because the timestamp is at the front and base32 preserves lexicographic order, sorting the string representation also sorts by time. This is ULID’s biggest practical advantage: it works everywhere that accepts a string, with no binary parsing, no special database type, and no ORM mapping drama. JavaScript handles it natively. Redis sorts it natively. Elasticsearch sorts it natively. Even a bash sort on a text file of ULIDs gives chronological order.
Generating ULIDs in Node.js is a single dependency, ulidx:
import { ulid } from 'ulidx';
const id = ulid(); // => 01JXZM7CZ7KQ1Y2A3B4C5D6E7F
The ulidx library is about 2 kB and has zero dependencies. It also supports a monotonic mode for batch generation inside the same millisecond:
import { monotonicFactory } from 'ulidx';
const ulid = monotonicFactory();
const ids = Array.from({ length: 1000 }, () => ulid());
// ids are strictly sorted
Head-to-head: the details that decide which one you ship
Storage size. This is the biggest difference. UUIDv7 stored as a native uuid in Postgres is 16 bytes. ULID stored as text is 26 bytes, or 32 bytes with the varlena header overhead in some versions. If you use ULID as a foreign key in three related tables, the size penalty multiplies across every index. For a 100 million row table, that is hundreds of megabytes of extra index bloat per relationship. UUIDv7 wins on raw storage.
If you store ULID in a bytea or custom binary type, you can get it down to 16 bytes, but then you lose the string-sorting benefit and most ORMs will hate you. In practice, ULID is treated as text.
Lexicographic sorting guarantees. Both sort by time, but UUIDv7 has a quirk. The canonical string representation includes hyphens (018ff4a0-...), and the version and variant nibbles sit in the middle. Lexicographic string comparison of UUIDv7 works for coarse time bucketing, but if you need a strict ORDER BY on the string form without converting to binary, ULID is safer. In Postgres, if you store UUIDv7 in a native uuid column, binary comparison does the right thing. But if your application serializes to a string, sorts in memory, and compares, the hyphenated format can surprise you.
Time precision. Both use 48-bit millisecond timestamps. That gives you a range until the year 10,889. Good enough. If you need sub-millisecond ordering, neither gives it natively; you need the monotonic counter extensions.
Ecosystem and tooling. UUIDv7 is an IETF standard and inherits every UUID library, validator, and schema format in existence. OpenAPI, JSON Schema, GraphQL, and Protobuf all know what a UUID is. ULID requires custom validators in many frameworks. On the other hand, ULID’s string-native form makes debugging easier. Reading a ULID in a log line immediately tells you the rough time without decoding. Reading a UUIDv7 string tells you very little unless you strip the hyphens and parse hex.
Collision resistance. UUIDv7 has 74 random bits per millisecond. ULID has 80 random bits per millisecond. Both are astronomical. Unless you are generating billions of IDs per second, collisions are a theoretical concern for both.
Monotonicity under load. Node.js’s built-in UUIDv7 and the ulidx monotonic factory both guarantee ordering within a single millisecond. If you use a non-monotonic ULID generator and burst 10,000 inserts in one millisecond, you might get out-of-order suffixes. Check your library.
The Postgres schema that proves the point
Here is a side-by-side table definition. Both use the same payload; only the key type changes.
-- UUIDv7 table: 16-byte native UUID
CREATE TABLE events_v7 (
id uuid PRIMARY KEY,
kind text NOT NULL,
data jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- ULID table: 26-char text
CREATE TABLE events_ulid (
id text PRIMARY KEY,
kind text NOT NULL,
data jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
Insert one million rows with each and compare:
SELECT relname,
pg_size_pretty(pg_relation_size(oid)) AS table_size,
pg_size_pretty(pg_indexes_size(oid)) AS index_size
FROM pg_class
WHERE relname IN ('events_v7', 'events_ulid');
On a typical test run, the UUIDv7 table’s primary key index is roughly 35-40% smaller than the ULID primary key index. Table size is identical (the payload dominates). But every secondary index on events_ulid that includes the primary key (for example, a covering index on (kind, id)) also pays the 26-byte text tax.
Now check fragmentation after a heavy insert workload:
SELECT relname,
avg_leaf_density,
leaf_fragmentation
FROM pgstatindex('events_v7_pkey')
UNION ALL
SELECT relname,
avg_leaf_density,
leaf_fragmentation
FROM pgstatindex('events_ulid_pkey');
Both will show low fragmentation (high density, low fragmentation) compared to a UUIDv4 equivalent. That is the point. But the UUIDv7 index will be smaller on disk and in memory.
A safe migration path from UUIDv4
You do not need to rewrite your entire database to benefit from this. For new tables, just switch the generation logic. For existing high-insert tables, a full primary-key migration is usually not worth the downtime.
A pragmatic middle path: add a sortable_id column to the existing table, backfill it with UUIDv7 values derived from the created_at timestamp (plus randomness for uniqueness), and start using that column for new queries that need time-ordered scans. Over time, new related tables reference the sortable_id instead of the old UUIDv4 primary key. The old UUIDv4 column stays for foreign-key stability.
If you are building greenfield, the decision is simpler. Default to UUIDv7 in a native uuid column. It gives you the smallest index footprint, the widest tool support, and a standard you can explain to auditors without naming a GitHub repository.
Reach for ULID when you are in an environment that treats everything as strings, needs URL-safe identifiers without extra encoding, or has debugging workflows where engineers read raw IDs in logs and traces every day. Just budget for the larger index size.
Working Node.js comparison
This snippet generates both, stores them in Postgres, and benchmarks a simple ordered read. It assumes you have a running Postgres and the pg driver installed.
import { randomUUID } from 'node:crypto';
import { ulid } from 'ulidx';
import { Pool } from 'pg';
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
async function insertBatch(table, generator, count) {
const client = await pool.connect();
try {
await client.query('BEGIN');
for (let i = 0; i < count; i++) {
await client.query(
`INSERT INTO ${table} (id, kind, data) VALUES ($1, 'test', '{}')`,
[generator()]
);
}
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}
async function orderedRead(table) {
const t0 = performance.now();
await pool.query(`SELECT id FROM ${table} ORDER BY id DESC LIMIT 100`);
return performance.now() - t0;
}
// Generate and measure
await insertBatch('events_v7', () => randomUUID({ version: 7 }), 100_000);
await insertBatch('events_ulid', () => ulid(), 100_000);
console.log('UUIDv7 ordered read:', await orderedRead('events_v7'), 'ms');
console.log('ULID ordered read:', await orderedRead('events_ulid'), 'ms');
await pool.end();
Both ordered reads will be fast because the index is clustered by sort order. The difference shows up at scale in index size and buffer cache pressure, not in a single query microbenchmark.
The decision matrix
| Situation | Pick |
|---|---|
Native Postgres uuid type, smallest footprint | UUIDv7 |
| Need string-native sorting in Redis, logs, or JS arrays | ULID |
| Strict compliance requirements (healthcare, finance) | UUIDv7 (IETF standard) |
| URL-safe IDs without extra encoding | ULID (base32, no hyphens) |
| Heavy batch inserts needing monotonic ordering | Either, with monotonic mode enabled |
ORM that handles uuid natively but treats text PKs suspiciously | UUIDv7 |
| Debugging culture where engineers read raw IDs | ULID (timestamp is obvious at a glance) |
Neither choice is wrong. Both are dramatically better than UUIDv4 for write-heavy tables. The worst choice is sticking with UUIDv4 because you already have it.
A note from Yojji
Reliable data modeling is the foundation of systems that scale without surprise outages. At Yojji, we design backend architectures where identifier choice, index layout, and query patterns are validated under production load before a single user hits the endpoint. If your team is migrating from legacy UUIDv4 schemas or building new data models that need to grow, our engineering teams can help you get the storage layer right from day one.