UUID v4 in Practice: Generation, Storage, and Common Pitfalls
How UUID v4 works, when to use it over other ID strategies, storage considerations, and common mistakes with database primary keys.
UUID v4 generates 128-bit identifiers from cryptographically secure random numbers. Their near-zero collision probability and independence from any central authority make them the default choice for distributed systems, but there are tradeoffs worth understanding.
UUID format and structure
A UUID is formatted as 8-4-4-4-12 hexadecimal characters, such as f47ac10b-58cc-4372-a567-0e02b2c3d479.
For v4, the third group always starts with 4 and the fourth group starts with 8, 9, a, or b. Those markers let you quickly identify a random-based UUID v4.
Tools for this section
Storing UUIDs in databases
VARCHAR(36) is portable but wastes space compared with a compact binary form. PostgreSQL has a native UUID type, while MySQL often benefits from storing UUIDs in BINARY(16) form.
UUID v4 is random, which means inserts into B-tree indexes land in scattered locations. At high insert rates that can increase fragmentation, so time-ordered alternatives such as UUID v7 are worth considering for write-heavy tables.
Tools for this section
When not to use UUID v4
UUID v4 is excellent for uniqueness, but it is long and not especially human-friendly. It can be awkward in support tickets, URLs, and any workflow where people need to read or type identifiers.
If readability, sortability, or insert locality matters more, evaluate alternatives such as nanoid, CUID2, UUID v7, or ULID instead of treating UUID v4 as the default for every table.
Tools for this section