How to generate unique order number?

前端 未结 6 1638
情话喂你
情话喂你 2021-02-06 06:59

I\'m looking for a good way to generate a unique order ID. Can you see any problems with the code below?

int customerId = 10000000;

long ticks = DateTime.UtcNow         


        
6条回答
  •  独厮守ぢ
    2021-02-06 07:24

    Suppose you have two customer ids that differ by 100, and they happen to both make an order that is 100 time units apart. Your uniqueness just went out the window.

    You say that you're going to check the database for uniqueness; you don't say what you're going to do if there's a collision. You also don't say what you're going to do about race conditions; suppose two colliding order ids are created at the same time, neither is in the database. You ask the database on two different threads whether the item is unique; it is. You then enter both, and uniqueness has been violated even though the check has been done.

    This is a really, really bad way to get uniqueness. What would be better is to move this into the database layer. You can maintain a global, threadsafe counter of orders and assign each new order the next highest order number.

    Incidentally, for many years I have asked a variation on this question as a technical interview question. I've noticed a strong correlation between the set of people who attempt to use time as a source of uniqueness and the set of people who don't get hired. Time is a terrible source of uniqueness; lots of different things can happen at the same time.

    What is even worse is using random numbers. Random numbers are an even worse source of uniqueness than timestamps. Suppose you have a truly random number generator that generates random 32 bit integers for order IDs. How many orders do you need to have before the odds are better than fifty-fifty that you've generated two orders with the same ID? The answer surprises a lot of people: it's only about 77 thousand before there is a 50% chance that you've generated two orders with the same number (and only 9300 until there's a 1% chance.)

    Remember: what you are after is a guarantee of uniqueness. Not a probable uniqueness, but an iron-clad guarantee that one order number refers to exactly one order. If that's what you need, then make sure you implement that.

提交回复
热议问题