Unique 64-bit, time-ordered ID Generator.
$ dotnet add package SnowflakeGeneratorSnowflakeGenerator is a unique ID generator based on Twitter's Snowflake. It generates 64-bit, time-ordered, unique IDs based on the Snowflake algorithm. It is written in C# and is compatible with .NET Standard 2.0.
Available as a NuGet Package.
The default bit assignment for this Snowflake implementation is:
41 bits for the TimeStamp value
10 bits for the MachineID value
12 bits for Sequence value
This provides by default:
If you require a higher generation rate or large range of MachineID's these values can be customised by the Settings used to initialize a Snowflake instance.
NOTE: 41 bits is always reserved for the TimeStamp value. Therefore, the sum of the MachineIDBitLength and SequenceBitLength cannot exceed 22. With the SequenceBitLength being at least equal to 1.
To install the SnowflakeGenerator library, you can use the following command in the Package Manager Console:
Install-Package SnowflakeGenerator
Alternatively, you can use the .NET CLI:
dotnet add package SnowflakeGenerator
First, import the SnowflakeGenerator namespace:
using SnowflakeGenerator;
Create a new instance of the Snowflake class with optional settings:
Settings settings = new Settings
{
MachineID = 1,
CustomEpoch = new DateTimeOffset(2020, 1, 1, 0, 0, 0, TimeSpan.Zero)
};
Snowflake snowflake = new Snowflake(settings);
Generate a new unique ID:
long id = snowflake.NextID();
Decode ID content:
var (timeStamp, machineId, sequence) = sonyflake.DecodeID(uniqueId);
NextID() will throw a TimestampOverflowException once it reaches the limit of the TimeStamp.
The Settings class allows you to customize the Snowflake instance:
MachineID: A unique identifier for the machine or instance generating the IDs.
CustomEpoch: A custom epoch or reference point for the timestamp portion of the generated ID.
MachineIDBitLength: Sets the number of bits allocated to the Machine ID part of the Snowflake ID.
SequenceBitLength: Sets the number of bits allocated to the Sequence part of the Snowflake ID.
This project is licensed under the MIT License.
Contributions are welcome. Please submit a pull request or create an issue to discuss your proposed changes.