paralleldrive / cuid

Collision-resistant ids optimized for horizontal scaling and performance.
Other
3.42k stars 123 forks source link

Why does a cuid have so many zeros in almost every generated id? #269

Closed usmanity closed 1 year ago

usmanity commented 1 year ago

I was looking over the readme and I understand that the zeros represent the same process generating multiple keys within the same second.

  1. Is this the correct understanding?
  2. What is a process in this case? Is it a single computer/host?

My current usage of cuid is within a next.js app (using Prisma) and I never see anything but zeros within a generated cuid. I'm wondering if this is because each one of my next.js api calls (the ones where cuids are generated) are being done within a separate serverless function call? This is my hypothesis so far.

ericelliott commented 1 year ago

My current usage of cuid is within a next.js app (using Prisma) and I never see anything but zeros within a generated cuid. I'm wondering if this is because each one of my next.js api calls (the ones where cuids are generated) are being done within a separate serverless function call? This is my hypothesis so far.

This is correct. Many processes actually generate hundreds or thousands of ids in tight loops, and the counter is needed to keep those from colliding. In fact, the counter is the main innovation that prevents collisions in databases and clients that generate lots of ids very quickly.

If you're using cloud functions and only generate one id per function invocation, the counter will always spit out zeros. That's OK.