generated from templates/typescript-library
Utility for generating Snowflake UIDs (see: https://en.wikipedia.org/wiki/Snowflake_ID)
Features:
- Zero dependencies
- Configurable epoch time
- Configurable instance size, allowing timestamp and sequence to be larger
Install
# Update project npm config to refer to correct registry for the @js scope
echo '@js:registry=https://gitea.jbrumond.me/api/packages/js/npm/' >> ./.npmrc
npm install --save @js/snowflake-uid
# optional - additional supporting typescript definitions
npm install --save-dev @js/types
Usage
import { Snowflake, create_snowflake_uid_generator } from '@js/snowflake-uid';
const snowflake = create_snowflake_uid_generator({
// See "More about instance_size" below
instance_size: 10n,
// Epoch time for the timestamp field. Static field that cannot be
// changed once you start generating IDs. Must be a time in the past.
epoch: BigInt(Date.parse('1 Jan 2020 00:00:00')),
// Instance ID for this generator. Must be unique across all generators
// in the same ID space. IDs can be reused once a new generator can no
// longer create IDs. These should likely be treated as a shared resource
// allocated from a pool. Must fit inside of the space allocated by the
// instance_size field.
instance: process.env.SNOWFLAKE_INSTANCE_ID,
});
// IDs can be generated as bigint or string values
const id1: bigint = snowflake.uid();
const id2: Snowflake = snowflake.uid_str();
More about instance_size
A larger value enables running more concurrent instances generating IDs in the same space (as few as 16 for 4-bits, or as many as 1024 for 10-bits).
This number cannot be changed once you start generating IDs, so you should choose a value that you don't think you will exceed the supported space limitations for.
Using fewer bits for the instance creates more space for the timestamp and sequence
number fields. The supported configurations are listed below, with the instance_size
parameter representing the bit-size of the "instances" column:
instances | timestamp space | sequence space |
---|---|---|
4-bit : 16 instances |
44-bit : ~560 years |
15-bit : 32768 IDs/ms/inst |
5-bit : 32 instances |
44-bit : ~560 years |
14-bit : 16384 IDs/ms/inst |
6-bit : 64 instances |
43-bit : ~280 years |
14-bit : 16384 IDs/ms/inst |
7-bit : 128 instances |
43-bit : ~280 years |
13-bit : 8192 IDs/ms/inst |
8-bit : 256 instances |
42-bit : ~140 years |
13-bit : 8192 IDs/ms/inst |
9-bit : 512 instances |
42-bit : ~140 years |
12-bit : 4096 IDs/ms/inst |
10-bit : 1024 instances |
41-bit : ~70 years |
12-bit : 4096 IDs/ms/inst |
Description
Utility for generating Snowflake UIDs (see https://en.wikipedia.org/wiki/Snowflake_ID)
Languages
TypeScript
100%