adnan kamili adnan kamili - 2 months ago 15
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
MySql
database table with
unique
set to
true


I am using following code to generate the string:

const Chance = require('chance');
const chance = new Chance(Date.now() + Math.random());
let randomStr = chance.string({length: 25,
pool: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'});
console.log(randomStr);


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

Answer

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.

Comments