UUIDs Explained: v4 vs v7 vs ULID for Database Keys

How UUIDs are structured, why random v4 keys fragment B-trees, and when time-ordered v7 or ULID are the better primary key.

Structure

A UUID is 128 bits written as 8-4-4-4-12 hex groups. The version nibble (the first digit of the third group) tells you how it was made: 4 = random, 7 = time-ordered random.

Insert performance

InnoDB and PostgreSQL B-trees append efficiently when primary keys are monotonically increasing. Random v4 keys scatter inserts across the index; v7 and ULID embed a timestamp prefix so new rows cluster at the right edge.

Entropy

v4 carries 122 random bits — collisions are astronomically unlikely. Keep generation on a cryptographic RNG; Math.random() is not acceptable for identifiers.

Alat terkait