Skip to the content.

The Internet Folks Logo

@theinternetfolks/snowflake

GitHub license Maintainer Downloads Npm package version

Library to help you create a Snowflake Id or parse the same. This solves the problem of generating unique identifiers at scale.

What are Snowflakes?

Snowflake IDs, or snowflakes, are a form of unique identifier used in distributed computing. The format was created by Twitter and is used for the IDs of tweets. The format has been adopted by other companies, including Discord, and Instagram, which uses a modified version.

By default, the ID format follows the original Twitter snowflake format.

Why Snowflakes are better than random UUIDs?

Snowflakes are sortable by time, because they are based on the time they were created. Additionally, the time a snowflake was created can be calculated from the snowflake. This can be used to get snowflakes (and their associated objects) that were created before or after a particular date.

Who uses Snowflake?

How it Works

Each time you generate an ID, it works, like this.

The default Twitter format shown below.

+--------------------------------------------------------------------------+
| 1 Bit Unused | 41 Bit Timestamp |  10 Bit NodeID  |   12 Bit Sequence ID |
+--------------------------------------------------------------------------+

Performance

With default settings, this snowflake generator should be sufficiently fast enough on most systems to generate 4096 unique ID’s per millisecond. This is the maximum that the snowflake ID format supports. That is, around 243-244 nanoseconds per operation.

Since the snowflake generator is single threaded the primary limitation will be the maximum speed of a single processor on your system.

Installation

Install with npm

  npm install @theinternetfolks/snowflake

Install with yarn

  yarn add @theinternetfolks/snowflake

Usage

Simple Generation

import { Snowflake } from "@theinternetfolks/snowflake";

console.log(Snowflake.generate());
// 6917062538869867520

Advanced Generation

import { Snowflake } from "@theinternetfolks/snowflake";

console.log(Snowflake.generate({ timestamp: 1649156222074 }));
// 6917062538869867520
import { Snowflake } from "@theinternetfolks/snowflake";

console.log(Snowflake.generate({ timestamp: 1649157035498, shard_id: 4 }));
// 6917065950617407488

API

static generate(
    {
        timestamp?: Date | number;
        shard_id?: number;
        epoch?: number;
    }
): string;
static parse(snowflake: string | number | bigint): {
    timestamp: number;
    shard_id: number;
    binary: string;
};

Test Coverage

License

MIT

The project is based on a fork off of (snowflake-generator)[https://github.com/FatAussieFatBoy/snowflake-generator].