A lightweight, thread-safe, extensible, and decodable Snowflake ID generator for .NET
$ dotnet add package SnowspeckA lightweight, thread-safe, extensible, and decodable Snowflake ID generator for .NET.
Microsoft.Extensions.Options)A Snowflake ID is a 64-bit integer originally developed by Twitter to generate unique, time-ordered identifiers in distributed systems.
It typically encodes:
This structure ensures:
Snowflake IDs are intentionally decodable and expose metadata like generation time and worker identity.
They are not cryptographically secure and should not be used to encode sensitive or private information.
Use them only for unique, ordered identifiers, not for hiding or securing data.
Using the CLI:
dotnet add package Snowspeck
Or via the NuGet Package Manager:
Install-Package Snowspeck
Snowspeck offers two implementations of the generator, depending on whether you prefer signed or unsigned IDs:
| Class | Return Type | ID Range | Notes |
|---|---|---|---|
SignedSnowflakeService | long | -2⁶³ to 2⁶³−1 | Default in DI setup, fits in signed columns |
UnsignedSnowflakeService | ulong | 0 to 2⁶⁴−1 | Full 64-bit range, use when unsigned is OK |
Both use the same structure:
Choose the implementation that best fits your database, serialization, or sorting needs.
using Snowspeck;
using Snowspeck.Interfaces;
using Snowspeck.Services;
var options = new SnowflakeOptions
{
WorkerId = 1,
Epoch = 1735689600000L // (optional) Default is 1735689600000L -> Jan 1, 2025
};
ISnowflakeGenerator generator = new SignedSnowflakeService(options);
long id = generator.NextId();
builder.Services.AddSnowspeck(options =>
{
options.WorkerId = 1;
options.Epoch = 1735689600000L; // (optional) Default is 1735689600000L -> Jan 1, 2025
});
builder.Services.AddSnowspeckUnsigned(options =>
{
options.WorkerId = 1;
options.Epoch = 1735689600000L; // (optional) Default is 1735689600000L -> Jan 1, 2025
});
Once registered, resolve ISnowflakeGenerator via constructor injection:
public class MyService
{
private readonly ISnowflakeGenerator _generator;
public MyService(ISnowflakeGenerator generator)
{
_generator = generator;
}
public void DoSomething()
{
long id = _generator.NextId();
}
}
The generator supports decoding a Snowflake ID back into:
Timestamp (UTC time the ID was generated)DatacenterIdWorkerIdSequencelong id = generator.NextId();
var metadata = generator.Decode(id);
Console.WriteLine($"Timestamp: {metadata.Timestamp}");
Console.WriteLine($"DatacenterId: {metadata.DatacenterId}");
Console.WriteLine($"WorkerId: {metadata.WorkerId}");
Console.WriteLine($"Sequence: {metadata.Sequence}");
Licensed under the MIT License.
© 2025 Tiago Ferreira Alves