UUID Version 4 (Random)

Learn how UUID v4 works, its 122 bits of randomness, collision probability, and why it is the most widely used UUID version in modern applications.

Version

Detailed Explanation

UUID Version 4 is the most commonly used UUID variant. It relies on cryptographically secure random or pseudo-random numbers to generate identifiers that are virtually guaranteed to be unique without any coordination between systems.

Bit layout (128 bits total):

  • 122 bits are randomly generated
  • 4 bits encode the version number (0100 for v4, placed at bits 48-51)
  • 2 bits encode the variant (10 for RFC 4122/9562, placed at bits 64-65)

This means the version digit in the string representation is always 4, and the first hex digit of the fourth group is always 8, 9, a, or b. For example: 550e8400-e29b-41d4-a716-446655440000.

Why 122 random bits matters: With 2^122 (approximately 5.3 x 10^36) possible values, you would need to generate roughly 2.71 x 10^18 UUIDs before reaching a 50% probability of a single collision (the birthday paradox threshold). In practical terms, generating one billion UUIDs per second would take about 86 years to reach that point.

Generation in JavaScript:

// Modern browsers and Node.js 19+
const id = crypto.randomUUID();

// Fallback using crypto.getRandomValues
function uuidv4() {
  const bytes = crypto.getRandomValues(new Uint8Array(16));
  bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
  bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10
  const hex = [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
  return [hex.slice(0,8), hex.slice(8,12), hex.slice(12,16), hex.slice(16,20), hex.slice(20)].join('-');
}

Performance considerations: UUID v4 generation is extremely fast because it only requires a random number generator call. However, because v4 UUIDs are entirely random, they cause poor index locality in B-tree database indexes. Inserts scatter across the index rather than appending to the end, leading to more page splits and higher write amplification. If index performance matters, consider UUID v7 instead.

Use Case

UUID v4 is ideal for generating unique identifiers in distributed systems where no central authority exists, such as session tokens, API request IDs, or document identifiers in collaborative editing tools.

Try It — UUID Generator

Open full tool