Safe way to generate unique primary keys from AWS Lambda functions with Node.js

Viewed 635

I am using AWS Lambda with Node.js to insert items to my DynamoDB tables and need to generate unique ids for the items.

My biggest concern is with entropy in AWS Lambda underlying infrastructure, and risk of collisions with high number of ids per second.

I am using nanoid, but not sure if it meet this requirements. The code that I am using is this:

const { customAlphabet } = require("nanoid");
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const idSize = 20;
const nanoid = customAlphabet(alphabet, idSize);
const id = nanoid(); //=> "scLV4Vc7OrJ2Vpib9rz6"

How does nonoid generates randomness? Is it safe to use in AWS Lambda functions (high entropy and low change of collisions)? If not, what are the alternatives?

1 Answers

Taken from the nanoid documentation

For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.

With DynamoDB there is always the risk of a collision, it is BASE so you are swapping consistency with performance.

If you are able to increase the string length of your ID this will give you even less chance of collision.

If you do want to use DynamoDB but also add consistency, transactional support was added. It will add a small overhead to performance.

Related