What is UUID/GUID

A Universally Unique IDentifier (UUID) – also called a Global Unique IDentifier (GUID) – is a 128-bit value formatted into blocks of hexadecimal digits separated by a hyphen (‘-‘ U+002D). A typical UUID is baef6775-eb3a-4ac9-85d3-70e4aa0d9d94.

A version 4 UUID is defined in RFC 4122: 128 randomly-generated bits with six bits at certain positions set to particular values. For example,

1

2

3

baef6775-eb3a-4ac9-85d3-70e4aa0d9d94

^^

12

The digit at position 1 above is always ‘4‘ and the digit at position 2 is always one of ‘8‘, ‘9‘, ‘A‘ or ‘B‘. It doesn’t matter whether the letters A-F are upper or lower case.

Procedure

The procedure to generate a version 4 UUID is as follows:

Generate 16 random bytes (=128 bits)

Adjust certain bits according to RFC 4122 section 4.4 as follows:

set the four most significant bits of the 7th byte to 0100’B, so the high nibble is ‘4’

set the two most significant bits of the 9th byte to 10’B, so the high nibble will be one of ‘8’, ‘9’, ‘A’, or ‘B’.

Side Note

Be aware that UUID uniqueness relies heavily on the underlying random number generator (RNG). The solution above uses Math.random() for brevity, however Math.random() is not guaranteed to be a high-quality RNG. See Adam Hyland’s excellent writeup on Math.random() for details. For a more robust solution, consider something like node-uuid.js

This gist describes how to determine how many IDs can be generated before reaching a certain probability of collision. For example, with 3.26×1015 version 4 RFC4122 UUIDs you have a 1-in-a-million chance of collision.