Generate Unique UInt32 ID for Couchbase

I am looking for a way to generate a unique ID for nosql database. Unlike relational database there is no idea of rows which means there is no last row to increment from.

The most common way to handle this is to use UUID's. But my problem is I need to add another ID (other than the UUID) which needs to be:

  • Unique
  • Unsigned Int32

Total data could reach around 50,000,000. So how would you generate somewhat unique uint32 ID's?

The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295.

  • Only generated when a new user registers.
  • 3 Id's are given to each new user.
  • Currently using Couchbase Server.

This problem has already been solved - I would suggest using the atomic Increment (or Decrement) functions in Couchbase - these are a common pattern to generate unique IDs.

Whenever the incr() method is called, it atomically increments the counter by the specified value, and returns the old value, therefore it's safe if two clients try to increment at the same time.

Pseudocode example (I'm no Node.JS expert!):

// Once, at the beginning of time we init the counter:
client.set("user::count", 0);
...
// Then, whenever a new user is needed: 
nextID = client.incr("user::count", 1); // increments counter and returns 'old' value.
newKey = "user_" + nextID;
client.add(newKey, value);

See the Node.JS SDK for reference, and see Using Reference Doucments for Lookups section in the Couchbase Developer Guide for a complete usage example.

Here's a function that returns a unique identifier each time it's called. It should be fine as long as the number of items does not exceed the range of 32-bit integers, which seems to be the case given the described requirements. (warning: once the array of UIDs fills up, this enters an infinite loop. You may also want to create some sort of a reset function that can empty the array and thus reset the UID when necessary.)

var getUID = (function() {
    var UIDs = [];

    return function() {
        var uid;

        do {
            uid = Math.random() * Math.pow(2, 32) | 0x0;
        } while (UIDs[uid] !== undefined);

        return UIDs[uid] = uid;
    };
}());