Snowflake Numeric ID Generator
Generate 64-bit Snowflake IDs with timestamp worker ID and sequence for sortable numeric unique IDs without coordination.
Code
export function snowflake(workerId=0,{epoch=1700000000000,workerBits=10,seqBits=12}={}){const maxW=(1<<workerBits)-1,maxS=(1<<seqBits)-1;if(workerId<0||workerId>maxW)throw new Error('workerId out of range');let lastTs=-1,seq=0;function next(){let ts=Date.now()-epoch;if(ts<lastTs)throw new Error('clock moved backwards');if(ts===lastTs){seq=(seq+1)&maxS;if(seq===0){while(ts<=lastTs)ts=Date.now()-epoch;}}else seq=0;lastTs=ts;return(ts<<(workerBits+seqBits))|(workerId<<seqBits)|seq;}return{next};}How the snippet works
Count the functions maxW, snowflake and next as the entire surface area of Snowflake Numeric ID Generator.
Failure is loud: Error aborts the current operation instead of degrading it.
Watch out for
- The guard
workerId<0||workerId>maxWshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The primary signature is export function snowflake(workerId=0,{epoch=1700000000000,workerBits=10,seqBits=12}={})
The surface worth importing is snowflake; the helpers around it are private to the snippet.
Interactive Tools for This Topic
FAQ
- How does the code behave when input is bad?
- Validation comes first — `Error` marks the failure at `workerId<0||workerId>maxW`, before any partial work happens.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `maxW`, `snowflake`, `next` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.