DEV Community

Sebastian Korotkiewicz
Sebastian Korotkiewicz

Posted on

1

Generating Globally Unique IDs in Distributed Systems

In today's distributed systems, one of the key challenges is generating unique identifiers (IDs) in highly concurrent and distributed environments. Snowflake, a tool commonly used in distributed systems to generate globally unique IDs with a timestamp component. Discover why Snowflake IDs are a valuable asset for your project.

This library is only inspired by the existing Snowflake project, but is written by me.
So if you find an error, let me know.

Also added a promise to ensure that the ID is never repeated.

Generating Unique IDs in Any Context

Snowflake IDs ensure uniqueness in distributed and multi-threaded environments.

You can also decode any ID to object, here is a example:

import { Snowflake, decodeSnowflake } from "@skorotkiewicz/snowflake-id";

(async () => {
  const machineId = 1; // machine ID (0-1023)
  const snowflake = new Snowflake(machineId);

  const id1 = await snowflake.generate();
  console.log("encodeID", id1);
  // output: 7160521316708126720

  const decoded = decodeSnowflake(id1);
  console.log("decodeID", decoded);
  // output: { timestamp: '2024-02-06T05:12:47.730Z', machineId: '1', sequence: '0' }
})();
Enter fullscreen mode Exit fullscreen mode

Are you ready to implement Snowflake IDs in your project? Let me know what ideas you have for their use!

I hope this article has been helpful to you. I look forward to your comments and questions on this topic!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
ranjancse profile image
Ranjan Dailata

Yet another interesting project named "Sonyflake".

Sonyflake is a distributed unique ID generator inspired by Twitter's Snowflake.

Sonyflake

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay