UUIDv7 Explained: Time-Ordered Database IDs With Unix Milliseconds
Using random UUIDv4 primary keys in large PostgreSQL or MySQL tables forces the database to insert new rows into random index pages, causing heavy disk writes and slow queries. UUIDv7 fixes that bottleneck by placing a 48-bit Unix millisecond timestamp at the very front of the ID.
Bit Structure of UUIDv7 (RFC 9562)
Standardized in IETF RFC 9562, a 128-bit UUIDv7 arranges its fields in big-endian chronological order:
- 48 bits (unix_ts_ms): Unsigned Unix timestamp in milliseconds, supporting dates until the year 10,889 AD.
- 4 bits (ver): Fixed version nibble
7. - 12 bits (rand_a): Sub-millisecond sequence or random bits.
- 2 bits (var): Standard RFC variant bits
10. - 62 bits (rand_b): Cryptographically random bits to prevent collisions.
Extract the Unix Timestamp From Any UUIDv7 in JavaScript
Because the first 12 hexadecimal characters represent the 48-bit millisecond integer directly, you can decode when any UUIDv7 record was created without querying a separate created_at column:
const uuidv7 = "019394b0-0000-7000-8000-000000000000";
const hex48 = uuidv7.replace(/-/g, "").slice(0, 12);
const unixMs = parseInt(hex48, 16);
console.log(new Date(unixMs).toISOString());