{"id":15038159,"url":"https://github.com/robthree/idgen","last_synced_at":"2025-05-13T18:10:02.909Z","repository":{"id":29776743,"uuid":"33320747","full_name":"RobThree/IdGen","owner":"RobThree","description":"Twitter Snowflake-alike ID generator for .Net","archived":false,"fork":false,"pushed_at":"2025-02-28T02:45:25.000Z","size":748,"stargazers_count":1245,"open_issues_count":1,"forks_count":148,"subscribers_count":28,"default_branch":"master","last_synced_at":"2025-04-25T15:48:41.232Z","etag":null,"topics":["c-sharp","dotnet","idgenerator","snowflake","twitter-snowflake","unique-id"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RobThree.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["RobThree"],"custom":["https://paypal.me/robiii"]}},"created_at":"2015-04-02T16:56:14.000Z","updated_at":"2025-04-23T14:58:57.000Z","dependencies_parsed_at":"2023-02-19T02:45:48.498Z","dependency_job_id":"6998d93d-51cf-455c-8bd1-51213ac37692","html_url":"https://github.com/RobThree/IdGen","commit_stats":{"total_commits":124,"total_committers":4,"mean_commits":31.0,"dds":"0.17741935483870963","last_synced_commit":"ce5e341e34a51a39c9dda47e9cd299a8339aea7d"},"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobThree%2FIdGen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobThree%2FIdGen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobThree%2FIdGen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RobThree%2FIdGen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RobThree","download_url":"https://codeload.github.com/RobThree/IdGen/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254000854,"owners_count":21997442,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c-sharp","dotnet","idgenerator","snowflake","twitter-snowflake","unique-id"],"created_at":"2024-09-24T20:37:21.893Z","updated_at":"2025-05-13T18:10:02.887Z","avatar_url":"https://github.com/RobThree.png","language":"C#","readme":"# ![Logo](https://raw.githubusercontent.com/RobThree/IdGen/master/logo.png) IdGen\n\n![Build Status](https://img.shields.io/github/actions/workflow/status/RobThree/IdGen/test.yml?branch=master\u0026style=flat-square) [![Nuget version](https://img.shields.io/nuget/v/IdGen.svg?style=flat-square)](https://www.nuget.org/packages/IdGen/)\n\nTwitter Snowflake-alike ID generator for .Net. Available as [Nuget package](https://www.nuget.org/packages/IdGen)\n\n## Why\n\nIn certain situations you need a low-latency, distributed, uncoordinated, (roughly) time ordered, compact and highly available Id generation system. This project was inspired by [Twitter's Snowflake](https://github.com/twitter/snowflake) project which has been retired. Note that this project was inspired by Snowflake but is not an *exact* implementation. This library provides a basis for Id generation; it does **not** provide a service for handing out these Id's nor does it provide generator-id ('worker-id') coordination.\n\n## How it works\n\nIdGen generates, like Snowflake, 64 bit Id's. The [Sign Bit](https://en.wikipedia.org/wiki/Sign_bit) is unused since this can cause incorrect ordering on some systems that cannot use unsigned types and/or make it hard to get correct ordering. So, in effect, IdGen generates 63 bit Id's. An Id consists of 3 parts:\n\n* Timestamp\n* Generator-id\n* Sequence \n\nAn Id generated with a **Default** `IdStructure` is structured as follows: \n\n![Id structure](https://raw.githubusercontent.com/RobThree/IdGen/master/structure.png)\n\nHowever, using the `IdStructure` class you can tune the structure of the created Id's to your own needs; you can use 45 bits for the timestamp, 2 bits for the generator-id and 16 bits for the sequence if you prefer. As long as all 3 parts (timestamp, generator and sequence) add up to 63 bits you're good to go!\n\nThe **timestamp**-part of the Id should speak for itself; by default this is incremented every millisecond and represents the number of milliseconds since a certain epoch. However, IdGen relies on an [`ITimeSource`](IdGen/ITimeSource.cs) which uses a 'tick' that can be defined to be anything; be it a millisecond (default), a second or even a day or nanosecond (hardware support etc. permitting). By default IdGen uses 2015-01-01 0:00:00Z as epoch, but you can specify a custom epoch too. \n\nThe **generator-id**-part of the Id is the part that you 'configure'; it could correspond to a host, thread, datacenter or continent: it's up to you. However, the generator-id should be unique in the system: if you have several hosts or threads generating Id's, each host or thread should have it's own generator-id. This could be based on the hostname, a config-file value or even be retrieved from an coordinating service. Remember: a generator-id should be unique within the entire system to avoid collisions!\n\nThe **sequence**-part is simply a value that is incremented each time a new Id is generated within the same tick (again, by default, a millisecond but can be anything); it is reset every time the tick changes.\n\n## System Clock Dependency\n\nWe recommend you use NTP to keep your system clock accurate. IdGen protects from non-monotonic clocks, i.e. clocks that run backwards. The [`DefaultTimeSource`](IdGen/DefaultTimeSource.cs) relies on a 64bit monotonic, increasing only, system counter. However, we still recommend you use NTP to keep your system clock accurate; this will prevent duplicate Id's between system restarts for example.\n\nThe [`DefaultTimeSource`](IdGen/DefaultTimeSource.cs) relies on a [`Stopwatch`](https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) for calculating the 'ticks' but you can implement your own time source by simply implementing the [`ITimeSource`](IdGen/ITimeSource.cs) interface.\n\n\n## Getting started\n\nInstall the [Nuget package](https://www.nuget.org/packages/IdGen) and write the following code:\n\n```c#\nusing IdGen;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var generator = new IdGenerator(0);\n        var id = generator.CreateId();\n        // Example id: 862817670527975424\n    }\n}\n```\n\nVoila. You have created your first Id! Want to create 100 Id's? Instead of:\n\n`var id = generator.CreateId();`\n\nwrite:\n\n`var id = generator.Take(100);`\n\nThis is because the `IdGenerator()` implements `IEnumerable` providing you with a never-ending stream of Id's (so you might want to be careful doing a `.Select(...)` or `Count()` on it!).\n\nThe above example creates a default `IdGenerator` with the GeneratorId (or: 'Worker Id') set to 0 and using a [`DefaultTimeSource`](IdGen/DefaultTimeSource.cs). If you're using multiple generators (across machines or in separate threads or...) you'll want to make sure each generator is assigned it's own unique Id. One way of doing this is by simply storing a value in your configuration file for example, another way may involve a service handing out GeneratorId's to machines/threads. IdGen **does not** provide a solution for this since each project or setup may have different requirements or infrastructure to provide these generator-id's.\n\nThe below sample is a bit more complicated; we set a custom epoch, define our own id-structure for generated Id's and then display some information about the setup:\n\n```c#\nusing IdGen;\nusing System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        // Let's say we take april 1st 2020 as our epoch\n        var epoch = new DateTime(2020, 4, 1, 0, 0, 0, DateTimeKind.Utc);\n            \n        // Create an ID with 45 bits for timestamp, 2 for generator-id \n        // and 16 for sequence\n        var structure = new IdStructure(45, 2, 16);\n            \n        // Prepare options\n        var options = new IdGeneratorOptions(structure, new DefaultTimeSource(epoch));\n            \n        // Create an IdGenerator with it's generator-id set to 0, our custom epoch \n        // and id-structure\n        var generator = new IdGenerator(0, options);\n\n        // Let's ask the id-structure how many generators we could instantiate \n        // in this setup (2 bits)\n        Console.WriteLine(\"Max. generators       : {0}\", structure.MaxGenerators);\n\n        // Let's ask the id-structure how many sequential Id's we could generate \n        // in a single ms in this setup (16 bits)\n        Console.WriteLine(\"Id's/ms per generator : {0}\", structure.MaxSequenceIds);\n\n        // Let's calculate the number of Id's we could generate, per ms, should we use\n        // the maximum number of generators\n        Console.WriteLine(\"Id's/ms total         : {0}\", structure.MaxGenerators * structure.MaxSequenceIds);\n\n\n        // Let's ask the id-structure configuration for how long we could generate Id's before\n        // we experience a 'wraparound' of the timestamp\n        Console.WriteLine(\"Wraparound interval   : {0}\", structure.WraparoundInterval(generator.Options.TimeSource));\n\n        // And finally: let's ask the id-structure when this wraparound will happen\n        // (we'll have to tell it the generator's epoch)\n        Console.WriteLine(\"Wraparound date       : {0}\", structure.WraparoundDate(generator.Options.TimeSource.Epoch, generator.Options.TimeSource).ToString(\"O\"));\n    }\n}\n```\n\nOutput:\n```\nMax. generators       : 4\nId's/ms per generator : 65536\nId's/ms total         : 262144\nWraparound interval   : 407226.12:41:28.8320000 (about 1114 years)\nWraparound date       : 3135-03-14T12:41:28.8320000+00:00\n```\n\nIdGen also provides an `ITimeSouce` interface; this can be handy for [unittesting](IdGenTests/IdGeneratorTests.cs) purposes or if you want to provide a time-source for the timestamp part of your Id's that is not based on the system time. For unittesting we use our own [`MockTimeSource`](IdGenTests/Mocks/MockTimeSource.cs).\n\n## Configuration\n\nA configuration package for .Net Framework projects can be found in [IdGen.Configuration](https://www.nuget.org/packages/IdGen.Configuration). This package allows you to configure your IdGenerators in your `app.config` or `web.config` file. The configuration section looks like this:\n\n```xml\n\u003cconfiguration\u003e\n  \u003cconfigSections\u003e\n    \u003csection name=\"idGenSection\" type=\"IdGen.Configuration.IdGeneratorsSection, IdGen.Configuration\" /\u003e\n  \u003c/configSections\u003e\n\n  \u003cidGenSection\u003e\n    \u003cidGenerators\u003e\n      \u003cidGenerator name=\"foo\" id=\"123\"  epoch=\"2016-01-02T12:34:56\" timestampBits=\"39\" generatorIdBits=\"11\" sequenceBits=\"13\" tickDuration=\"0:00:00.001\" /\u003e\n      \u003cidGenerator name=\"bar\" id=\"987\"  epoch=\"2016-02-01 01:23:45\" timestampBits=\"20\" generatorIdBits=\"21\" sequenceBits=\"22\" /\u003e\n      \u003cidGenerator name=\"baz\" id=\"2047\" epoch=\"2016-02-29\"          timestampBits=\"21\" generatorIdBits=\"21\" sequenceBits=\"21\" sequenceOverflowStrategy=\"SpinWait\" /\u003e\n    \u003c/idGenerators\u003e\n  \u003c/idGenSection\u003e\n\n\u003c/configuration\u003e\n```\n\nThe attributes (`name`, `id`, `epoch`, `timestampBits`, `generatorIdBits` and `sequenceBits`) are required. The `tickDuration` is optional and defaults to the default tickduration from a `DefaultTimeSource`. The `sequenceOverflowStrategy` is optional too and defaults to `Throw`. Valid DateTime notations for the epoch are:\n\n* `yyyy-MM-ddTHH:mm:ss`\n* `yyyy-MM-dd HH:mm:ss`\n* `yyyy-MM-dd`\n\nYou can get the IdGenerator from the config using the following code:\n\n`var generator = AppConfigFactory.GetFromConfig(\"foo\");`\n\n## Dependency Injection\n\nThere is an [IdGen.DependencyInjection NuGet package](https://www.nuget.org/packages/IdGen.DependencyInjection) available that allows for easy integration with the commonly used [Microsoft.Extensions.DependencyInjection](https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection).\n\nUsage is straightforward:\n\n```c#\nservices.AddIdGen(123); // Where 123 is the generator-id\n```\n\nOr, when you want to use non-default options:\n\n```c#\nservices.AddIdGen(123, () =\u003e new IdGeneratorOptions(...));  // Where 123 is the generator-id\n```\n\nThis registers both an `IdGenerator` as well as an `IIdGenerator\u003clong\u003e`, both pointing to the same singleton generator.\n\n## Upgrading from 2.x to 3.x\n\nUpgrading from 2.x to 3.x should be pretty straightforward. The following things have changed:\n\n* Most of the constructor overloads for the `IdGenerator` have been replaced with a single constructor which accepts `IdGeneratorOptions` that contains the `ITimeSource`, `IdStructure` and `SequenceOverflowStrategy`\n* The `MaskConfig` class is now more appropriately named `IdStructure` since it describes the structure of the generated ID's.\n* The `UseSpinWait` property has moved to the `IdGeneratorOptions` and is now an enum of type `SequenceOverflowStrategy` instead of a boolean value. Note that this property has also been renamed in the config file (from `useSpinWait` to `sequenceOverflowStrategy`) and is no longer a boolean but requires one of the values from `SequenceOverflowStrategy`.\n* `ID` is now `Id` (only used as return value by the `FromId()` method)\n\nThe generated 2.x ID's are still compatible with 3.x ID's. This release is mostly better and more consistent naming of objects.\n\n# FAQ\n\n**Q**: Help, I'm getting duplicate ID's or collisions?\n\n**A**: Then you're probably not using IdGen as intended: It should be a singleton (per thread/process/host/...), and if you insist on having multiple instances around they should all have their own unique GeneratorId.\n\n**A**: Also: Don't change the structure; once you've picked an `IdStructure` and go into production commit to it, stick with it. This means that careful planning is needed to ensure enough ID's can be generated by enough generators for long enough. Although changing the structure at a later stage isn't impossible, careful consideration is needed to ensure no collisions will occur.\n\n**Q**: I'm experiencing weird results when these ID's are used in Javascript?\n\n**A**: Remember that generated ID's are 64 (actually 63) bits wide. Javascript uses floats to store all numbers and the [maximum integer value you can safely store](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) is 53 bits. If you need to handle these ID's in Javascript, treat them as `strings`.\n\n\u003chr\u003e\n\nIcon made by [Freepik](http://www.flaticon.com/authors/freepik) from [www.flaticon.com](http://www.flaticon.com) is licensed by [CC 3.0](http://creativecommons.org/licenses/by/3.0/).\n","funding_links":["https://github.com/sponsors/RobThree","https://paypal.me/robiii"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frobthree%2Fidgen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frobthree%2Fidgen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frobthree%2Fidgen/lists"}