2

i want to know what are the chances for this unique id generator to collide https://github.com/vejuhust/blog-code/blob/master/python-short-id-generator/short_id_v5.py

i wanted to generate a unique url for my Django project. is it going to be safe to use. i am a beginner in python and Django.

maria
  • 23
  • 2
  • 2
    you can use [`uuid`](https://docs.python.org/3/library/uuid.html), which is very safe and minimal chance of collision. Reference: https://stackoverflow.com/questions/1155008/how-unique-is-uuid – ruddra Sep 02 '19 at 08:16
  • i want url to be short – maria Sep 02 '19 at 08:31

1 Answers1

3

This is a base62 encoded 8 byte random number. The encoding does not matter however, since every random number is encoded differently. It thus boils down on what are the odds that two 8 byte random numbers are the same.

We can generate a total of 28×8=18'446'744'073'709'552'000 values with 8 bytes. So the odds of generating a second value that is the same is 1/18'446'744'073'709'552'000 or 0.000000000000000000542%.

If you generate k items, the odds of generating a duplicate is:

1 - (28×8)!/((28×8-k)!×28×8×k).

As k grows larger, the odds of a collision increase. If you mark the field unique, and thus have a retry mechanism, the odds that it will collide a second time (or a third time) are quite small.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • so is it safe to use it as url generator. – maria Sep 02 '19 at 08:30
  • @maria: yes, although as said, you can simply mark the field unique and have a retry mechanism to insert in the database. That will *guarantee* uniqness. But it would be very unlikely to retry anyway. – Willem Van Onsem Sep 02 '19 at 08:31