Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a unique reference number strategies

Hrm... here's where my CS knowledge lets me down. I want to write an algorithm that generates a reference number that is unique.

I don't want to use sequential numbers as they introduce a security risk and I want to use alphanumerics. The ref will have a min and max length too. (I can't use a GUID it is too long)

Ideally I don't want to query my persistence layer to see if a ref has been used before.

What strategies can I employ?

like image 241
Johnno Nolan Avatar asked Dec 10 '08 17:12

Johnno Nolan


2 Answers

If you're worried about security risks, then you want a cryptographically-secure random number generator. You should be able to tell it how many bytes you want (i.e. how long the number can be).

like image 86
Roger Lipscombe Avatar answered Nov 15 '22 09:11

Roger Lipscombe


If this number will be ever be referenced by humans, I encourage you to follow these guidelines in your solution:

What is the best format for a customer number, order number?

If you can't synchorize with the database to see what the next number will be, and you can't use GUIDs or a comparably long random string, then you need to include some sort of local value in the ID.

e.g., if all clients will be on a known network, you can end each number in each client's ip address D block.

Or, if clients have to login and each user can login only once at a time, you can include their userid in the number somewhere.

like image 40
Michael Haren Avatar answered Nov 15 '22 10:11

Michael Haren