Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good algorithm for generating an order number

Tags:

algorithm

math

As much as I like using GUIDs as the unique identifiers in my system, it is not very user-friendly for fields like an order number where a customer may have to repeat that to a customer service representative.

What's a good algorithm to use to generate order number so that it is:

  • Unique
  • Not sequential (purely for optics)
  • Numeric values only (so it can be easily read to a CSR over phone or keyed in)
  • < 10 digits
  • Can be generated in the middle tier without doing a round trip to the database.

UPDATE (12/05/2009) After carefully reviewing each of the answers posted, we decided to randomize a 9-digit number in the middle tier to be saved in the DB. In the case of a collision, we'll regenerate a new number.

like image 506
Jason Avatar asked Dec 01 '09 03:12

Jason


People also ask

Is order number unique?

The order number is not guaranteed to be unique. Two orders will have the same order number if they both happened at the same millisecond and also both have the same padding digit. It's important to understand the probability for a collision to see if this can work reasonable in a real system.


2 Answers

If the middle tier cannot check what "order numbers" already exists in the database, the best it can do will be the equivalent of generating a random number. However, if you generate a random number that's constrained to be less than 1 billion, you should start worrying about accidental collisions at around sqrt(1 billion), i.e., after a few tens of thousand entries generated this way, the risk of collisions is material. What if the order number is sequential but in a disguised way, i.e. the next multiple of some large prime number modulo 1 billion -- would that meet your requirements?

like image 86
Alex Martelli Avatar answered Sep 20 '22 18:09

Alex Martelli


<Moan>OK sounds like a classic case of premature optimisation. You imagine a performance problem (Oh my god I have to access the - horror - database to get an order number! My that might be slow) and end up with a convoluted mess of psuedo random generators and a ton of duplicate handling code.</moan>

One simple practical answer is to run a sequence per customer. The real order number being a composite of customer number and order number. You can easily retrieve the last sequence used when retriving other stuff about your customer.

like image 36
James Anderson Avatar answered Sep 21 '22 18:09

James Anderson