Snowflake IDs are 64-bit time-ordered integers originally created by Twitter for distributed systems. They allow multiple worker nodes to generate globally unique, chronological IDs concurrently without coordinating through a centralized database lock.
64-Bit Binary Layout
- 1 Bit (Sign): Unused (always
0). - 41 Bits (Timestamp): Milliseconds since custom epoch (Jan 1, 2021) — covers 69 years.
- 10 Bits (Worker/Machine ID): Supports up to 1,024 independent worker nodes (0–1023).
- 12 Bits (Sequence Number): Supports up to 4,096 IDs per millisecond per worker node (over 4 million IDs/sec/node).
Usage
js
import { snowflake } from '@readytools/id';
// Generate Snowflake ID for worker node 1
const id = snowflake(1);
// Returns: "176283920194857216" (string to avoid JS MAX_SAFE_INTEGER truncation)
// Worker ID can range between 0 and 1023
const workerNodeId = parseInt(process.env.WORKER_ID || '42', 10);
const recordId = snowflake(workerNodeId);⚡ Live Playground
snowflake()
Generating...
📏 Calculating...✨ Web Crypto Native
Clock Drift and Sequence Handling
If system time drifts backward (NTP sync), the generator throws an explicit error (Clock moved backwards). If the 4,096 sequence count is exhausted within a single millisecond, it automatically spins until the next millisecond tick to guarantee strict uniqueness.