Introduction
Snowflake is a service used to generate unique IDs for objects within Twitter (Tweets, Direct Messages, Users, Collections, Lists etc.). These IDs are unique 64-bit unsigned integers, which are based on time, instead of being sequential. The full ID is composed of a timestamp, a worker number, and a sequence number.
By default, 64-bit unsigned integers will generate an Id whose length is 19, but sometimes it may be too long, some customers need an Id whose length is 16.
In this article, I will show how can we adapt to generate an Id whose length is 16.
How to Do This?
The full ID is composed of a 41 bit timestamp, 10 bit worker number, and 12 bit sequence number.
We can reduce the bit count of those components to finish this work.
Here is a sample that we can follow.
As you can see, the above code reduces the bit count of worker number and sequence number.
The next step is to use this IdGenerator.
- static void Main(string[] args)
- {
-
- var generator = new IdGenerator(0, 0);
-
- System.Threading.Tasks.Parallel.For(0, 20, x =>
- {
- Console.WriteLine(generator.NextId().ToString());
- });
-
- Console.WriteLine("Hello World!");
- Console.ReadKey();
- }
Here is the result of it.
NOTE
We should keep the generator qas a singleton, it means that we should only create the generator once. If not, it may generate some duplicate Ids.
Summary
This article showed you a simple solution of how to generate a snowflake id whose length is 16.
By the way, you can adjust the bit count to adapt your work.
I hope this will help you!