Unique 10 digit Sequence ID - 200 IDs/Sec

I need to generate unique ID in c++. I'm looking at almost 200 IDs per second and these IDs should not repeat atleast for the next 30 days. The IDs should be 9 or 10 digits long. Also these should not repeat if my service is restarted or if my machine is restarted.

i checked out the following link Generate unique sequence ID

It's almost the same requirement as mine. But the problem i faced with that piece of code is the ID length. At times it used to generate as low as 2 digit IDs. I confirmed this with a test driver.

Your inputs will be much appreciated.

Upvotes: 0

Views: 169

Answers (2)

Nicu Stiurca
Nicu Stiurca

Reputation: 8677

As a first approximation, you could try something like this:

unsigned long genUniqueID()
{
  const unsigned long MIN_ID = 1e8; // 9 digit number
  const unsigned long MAX_IDs_SEC = 200;
  static unsigned long nextID = MIN_ID + getSecondsSinceStartOfMonth() * MAX_IDs_SEC;
  return nextID++;
}

Obviously there are two constants to tune. This solution wouldn't work if the average IDs generated per second during an uninterrupted run of your program exceeded MAX_IDs_SEC, so you will want to make sure that value is high enough, or otherwise throttle calling this function too often.

Upvotes: 3

Frerich Raabe
Frerich Raabe

Reputation: 94279

If you want to be able to generate 200 IDs per second, and you want to continue doing so (without repeating an ID) you need to be able to generate 30 * 24 * 60 * 60 * 200 = 518,400,000 IDs. If an ID should be at least 9 digits long, each ID should be (assuming you use decimal representation) larger or equal to 100,000,000 (the smallest number with 9 digits).

So ideally you'd have a function returning a value of a type which can hold the values between 100,000,000 and 618,400,000. Both values are smaller than the largest unsigned 32bit value (4,294,967,295), so you could just use that:

static uint32_t getNextId() {
  static uint32_t lastId = 99999999;
  return ++lastId;
}

Keep calling this function, it will yield a new ID on every call and they won't repeat in 30 days if you call the function 200 times per second.

If your process is started and stopped during those 30 days, just save the last used ID to a file when the process stops, and restore the ID when the process starts again.

Upvotes: 2

Related Questions