Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collisions when generating UUIDs in JavaScript

This relates to this question. I am using the code below from this answer to generate a UUID in JavaScript:

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {     var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);     return v.toString(16); }); 

This solution appeared to be working fine, but I am getting collisions. Here's what I have:

  • A web application running in Google Chrome.
  • 16 users.
  • about 4000 UUIDs have been generated in the past two months by these users.
  • I got about 20 collisions - e.g., a new UUID generated today was the same as about two months ago (different user).

What is causing this issue and how can I avoid it?

like image 398
Muxa Avatar asked Aug 02 '11 03:08

Muxa


People also ask

How do you avoid UUID collisions?

Use encapsulation, create a UUID factory object, where you save old ones in a set, then every time check is the new UUID exist or no, then return it only if it doesn't exist, else repeat.

Does UUID have collisions?

A collision is possible but the total number of unique keys generated is so large that the possibility of a collision is almost zero. As per Wikipedia, the number of UUIDs generated to have atleast 1 collision is 2.71 quintillion.

Can random UUID collide?

The principle doesn't change, UUID generation is really random—meaning you can consider the generation of UUIDs to to be independent events from one another. In other words, creating UUIDs from different computers does not change anything, it is incredibly unlikely that a collision will occur.

What does UUID do in JavaScript?

Introduction to JavaScript UUID. A universally unique identifier (UUID) is an identifier of the 128-bit value that is used in the construction of software. Each bit present in the value differs by the meaning as several variants are considered.


1 Answers

My best guess is that Math.random() is broken on your system for some reason (bizarre as that sounds). This is the first report I've seen of anyone getting collisions.

node-uuid has a test harness that you can use to test the distribution of hex digits in that code. If that looks okay then it's not Math.random(), so then try substituting the UUID implementation you're using into the uuid() method there and see if you still get good results.

[Update: Just saw Veselin's report about the bug with Math.random() at startup. Since the problem is only at startup, the node-uuid test is unlikely to be useful. I'll comment in more detail on the devoluk.com link.]

like image 89
broofa Avatar answered Oct 01 '22 18:10

broofa