adnan kamili adnan kamili - 1 year ago 138
Javascript Question

Nodejs - Generating unique random alpha numeric random string for Database

I have a use case where I need to generate alpha numeric capital case strings of length 25, so the total possible unique combinations are very high:

36 pow (25) = 808281277464764060643139600456536293376

The string is to be stored in
database table with
set to

I am using following code to generate the string:

const Chance = require('chance');
const chance = new Chance( + Math.random());
let randomStr = chance.string({length: 25,

Node.js can run in cluster mode, so value of timestamp can be same for different requests so I also added
. Is this enough to ensure that
unique constraint won't be violated by the random strings.

Answer Source

Is this enough to ensure that MySQL unique constraint won't be violated by the random strings.

3625 has 129 bit. If we apply the birthday problem, then you're likely getting a collision around 264 strings. You'll probably generate much less than that. This is only true provided that you use a good randomness source.

Math.random() is not a good randomness source.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download