Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

8 Character Random Code

I've been through answers to a few similar questions asked on SO, but could not find what I was looking for.

Is there a more efficient way to generate 8 character unique IDs, base 36 (0-9A-Z), than generating a unique ID and querying the DB to see if it already exists and repeating until you get a unique ID that has not been used?

Other solutions I found use time, but this is perhaps too easy to guess and may not work well in distributed systems. Consider these IDs to be promo codes.

like image 247
Bradford Avatar asked Dec 31 '25 09:12

Bradford


1 Answers

One option is to do it the other way round: generate a huge number of them in the database whenever you need to, then either fetch a single one from the DB when you need one, or reserve a whole bunch of them for your particular process (i.e. mark them as "potentially used" in the database) and then dole them out from memory.

like image 54
Jon Skeet Avatar answered Jan 01 '26 23:01

Jon Skeet