class Snowflake

Overview

The Snowflake class implements a Snowflake ID generator, which is designed to generate unique, time-based identifiers using a 64-bit structure. These identifiers consist of a timestamp component, a machine or process ID, and a sequence number to ensure uniqueness within the same millisecond.

The 64-bit ID is composed as follows:

This implementation uses the Twitter epoch of 1288834974657 milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC), which corresponds to November 4, 2010, 01:42:54.657 UTC. This epoch is the reference point from which all timestamps in Snowflake IDs are calculated.

Usage:

machine_id = 1_u64 # Assign a unique machine/process ID
generator = Snowflake.new(machine_id)
snowflake_id = generator.generate_id
puts snowflake_id

# To convert a Snowflake ID back to a UTC timestamp
utc_time = Snowflake.id_to_utc(snowflake_id)
puts utc_time

NOTE The machine ID must be unique across all instances of the generator to ensure the uniqueness of generated IDs.

Used resources:

Defined in:

snowflake.cr

Constant Summary

EPOCH = 1288834974657_i64
MACHINE_ID_BITS = 10
MACHINE_ID_SHIFT = SEQUENCE_BITS
MAX_MACHINE_ID = (1 << MACHINE_ID_BITS) - 1

Maximum values

MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1
SEQUENCE_BITS = 12
TIMESTAMP_BITS = 41

Constants for bit lengths

TIMESTAMP_SHIFT = MACHINE_ID_BITS + SEQUENCE_BITS

Bit shifts

VERSION = {{ (`shards version /srv/crystaldoc.info/github-mamantoha-snowflake-v0.1.0/src`).chomp.stringify }}

Constructors

Class Method Summary

Instance Method Summary

Constructor Detail

def self.new(machine_id : UInt64) #

[View source]

Class Method Detail

def self.id_to_utc(snowflake_id : UInt64) : Time #

Converts a given snowflake_id back to the UTC timestamp representing


[View source]

Instance Method Detail

def generate_id : UInt64 #

Generates a unique Snowflake ID based on the current time, machine ID, and an internal sequence.


[View source]