Why CUID has so many zeros in almost every generated ID

If you’ve ever used the CUID library in your JavaScript projects, you may have noticed that almost every generated ID contains a lot of zeros. This can be confusing, especially if you’re not sure what the zeros represent or why they’re there. In this post, we’ll explore the reason behind the zeros in CUID-generated IDs and answer some common questions about the library.

First off, let’s clarify what a CUID is. A CUID (short for “Collision-resistant Unique IDentifier”) is a unique identifier generated by the CUID library, which is often used in JavaScript apps to generate unique IDs for objects, elements, or other data types. CUIDs are designed to be highly resistant to collisions, meaning that it’s very unlikely for two CUIDs to be generated that are identical.

Now, let’s get back to the question at hand: why do CUIDs have so many zeros in them? The answer is actually quite simple. The zeros represent the same process generating multiple keys within the same second. In other words, the CUID library uses a counter to keep track of how many IDs are generated within a given second, and the zeros represent the value of the counter when the ID is generated.





So, what is a process in this context? A process refers to a single computer or host that is generating CUIDs. Many processes can generate hundreds or thousands of IDs in tight loops, which can cause collisions if the counter isn’t used to keep track of the number of IDs generated. This is where the counter comes in – it ensures that each ID generated within the same second is unique by incrementing a counter for each new ID generated.

If you’re using CUID in a cloud function or serverless environment, you may notice that almost every generated ID contains only zeros. This is because each serverless function invocation is considered a separate process, and the counter starts at zero for each new process. So, if you’re only generating one ID per function invocation, the counter will always spit out zeros. Don’t worry – this is perfectly normal and doesn’t affect the uniqueness of the generated IDs.

This issue came up when I was testing some things with Bookends and became curious so I opened an issue on the cuid github repo, you can see it here.