principlejavascriptModerate
UUID v7 vs v4: prefer v7 for database primary keys
Viewed 0 times
UUID v7UUID v4primary keyULIDindex fragmentationB-treesortable ID
Problem
Using UUID v4 (random) as a database primary key causes index fragmentation and poor insert performance at scale because values are not monotonically increasing.
Solution
Use UUID v7 for database primary keys:
import { v7 as uuidv7, v4 as uuidv4 } from 'uuid';
// UUID v4 — completely random, bad for B-tree indexes
// Each insert goes to a random position in the index tree
// UUID v7 — time-ordered, good for B-tree indexes
// Always inserts at the end of the index
console.log(uuidv7()); // '018e74d2-9f9a-7000-8000-4d5f2a3b1c0e'
// UUID v7 is also sortable chronologically
const ids = [uuidv7(), uuidv7(), uuidv7()];
console.log(ids.sort()); // already in creation order
// Practical: use ULID as an alternative if v7 isn't available
import { ulid } from 'ulid';
console.log(ulid()); // '01ARZ3NDEKTSV4RRFFQ69G5FAV'Why
B-tree indexes work best with monotonically increasing values. Random UUIDs (v4) cause page splits and fragmentation. UUID v7 encodes a millisecond timestamp in the high bits, so new IDs always append to the end of the index.
Gotchas
- UUID v7 exposes creation time — this can be a privacy concern in public-facing APIs
- Not all database drivers and ORMs support UUID v7 natively yet
- ULID is a popular alternative: 128 bits, sortable, case-insensitive, URL-safe
- If you have an existing table with v4 UUIDs, migrating is expensive — evaluate carefully
Revisions (0)
No revisions yet.