ChiyaFlake  README.md

File README.md from the latest check-in


ChiyaFlake

Simple thread-safe snowflake generator in C#, with millisecond precision and support for up to 64 concurrent generators.

ChiyaFlake generates snowflakes that are very short compared to IdGen or Twitter Snowflake, which makes it suitable for small projects where storage requirements are small.

Background

Snowflakes are useful in a highly concurrent multi-server environment, or when the primary key for an entity needs to be known before insertion in databases.

While UUIDs are practically unique enough for such purposes, they are very large at 128-bit and produce unwieldy strings when encoded.

When using solely ElasticSearch as the primary database without another SQL database, the IDs automatically generated by ElasticSearch are unnecessarily long. ChiyaFlake can be useful in these circumstances.

Installation

  1. Copy Snowflake.cs into your project.

Usage

Static generator class Snowflake uses an instance of SnowflakeInstance bound to the calling thread, with generator ID configured using the calling thread's ID.

using ChiyaFlake;

class Program
{
    static void Main(string[] args)
    {
        // default epoch is 2000/01/01

        var snowflake = Snowflake.New;       // JKIzu87d       (string)
        var timestamp = Snowflake.Timestamp; // 40279071308893 (long)
    }
}
  • Snowflake.New for snowflake generation, encoded in URL-safe Base64.
  • Snowflake.Timestamp to retrieve raw timestamp value used in snowflake string generation.

Instance class SnowflakeInstance can be initialized with a 6-bit generator ID (0 to 63) and epoch time. This class implements ISnowflake.

using ChiyaFlake;

class Program
{
    static void Main(string[] args)
    {
        // generator ID: 10
        // epoch time:   2019/12/11
        var generator = new SnowflakeInstance(10, new DateTime(2019, 12, 11));

        var snowflake = generator.New;       // 8A9q0Q     (string)
        var timestamp = generator.Timestamp; // 4027545361 (long)
    }
}