Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 205
majidarif Avatar asked Aug 10 '14 15:08

majidarif


1 Answers

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.

like image 156
DaveR Avatar answered Oct 11 '22 18:10

DaveR