AlgoViz

Unique ID generator

medium 28 min

Give every record its own number, from many servers at once.

Snowflake generator, range lease and UUIDv7

Read it, run it, change a line and run it again.

Loading editor…

The clock is passed in, so that rollbacks can be tried. Other languages show the Snowflake generator with a real clock; they refuse at once when it goes back.

The same in TypeScript
// Snowflake ID generator// 64-bit ID: 1 bit unused | 41 bits timestamp | 5 bits datacenter | 5 bits machine | 12 bits sequenceclass SnowflakeGenerator {  private readonly epoch: bigint = 1609459200000n; // Jan 1, 2021  private readonly datacenterIdBits = 5n;  private readonly machineIdBits = 5n;  private readonly sequenceBits = 12n;  private readonly maxDatacenterId = (1n << this.datacenterIdBits) - 1n;  private readonly maxMachineId = (1n << this.machineIdBits) - 1n;  private readonly maxSequence = (1n << this.sequenceBits) - 1n;  private readonly machineIdShift = this.sequenceBits;  private readonly datacenterIdShift = this.sequenceBits + this.machineIdBits;  private readonly timestampShift = this.sequenceBits + this.machineIdBits + this.datacenterIdBits;  private sequence: bigint = 0n;  private lastTimestamp: bigint = -1n;  constructor(    private readonly datacenterId: bigint,    private readonly machineId: bigint  ) {    if (datacenterId > this.maxDatacenterId || datacenterId < 0n) {      throw new Error(`Datacenter ID must be between 0 and ${this.maxDatacenterId}`);    }    if (machineId > this.maxMachineId || machineId < 0n) {      throw new Error(`Machine ID must be between 0 and ${this.maxMachineId}`);    }  }  private currentTimestamp(): bigint {    return BigInt(Date.now());  }  private waitNextMillis(lastTimestamp: bigint): bigint {    let timestamp = this.currentTimestamp();    while (timestamp <= lastTimestamp) {      timestamp = this.currentTimestamp();    }    return timestamp;  }  nextId(): bigint {    let timestamp = this.currentTimestamp();    if (timestamp < this.lastTimestamp) {      throw new Error('Clock moved backwards!');    }    if (timestamp === this.lastTimestamp) {      // Same millisecond - increment sequence      this.sequence = (this.sequence + 1n) & this.maxSequence;      if (this.sequence === 0n) {        // Sequence exhausted, wait for next millisecond        timestamp = this.waitNextMillis(this.lastTimestamp);      }    } else {      // New millisecond - reset sequence      this.sequence = 0n;    }    this.lastTimestamp = timestamp;    // Assemble the 64-bit ID    const id = ((timestamp - this.epoch) << this.timestampShift) |               (this.datacenterId << this.datacenterIdShift) |               (this.machineId << this.machineIdShift) |               this.sequence;    return id;  }  // Decode a Snowflake ID back to its components  decode(id: bigint): { timestamp: Date; datacenterId: bigint; machineId: bigint; sequence: bigint } {    const timestamp = new Date(Number((id >> this.timestampShift) + this.epoch));    const datacenterId = (id >> this.datacenterIdShift) & this.maxDatacenterId;    const machineId = (id >> this.machineIdShift) & this.maxMachineId;    const sequence = id & this.maxSequence;    return { timestamp, datacenterId, machineId, sequence };  }}// Usageconst generator = new SnowflakeGenerator(1n, 1n);// Generate unique IDsconst orderId = generator.nextId();const userId = generator.nextId();const transactionId = generator.nextId();console.log('Order ID:', orderId.toString());console.log('User ID:', userId.toString());console.log('Transaction ID:', transactionId.toString());// Decode an IDconst decoded = generator.decode(orderId);console.log('Decoded:', decoded);
The same in Go
package snowflake// Snowflake ID generator// 64-bit ID: 1 bit unused | 41 bits timestamp | 5 bits datacenter | 5 bits machine | 12 bits sequenceimport (	"errors"	"sync"	"time")const (	// Custom epoch: Jan 1, 2021	epoch int64 = 1609459200000	// Bit lengths	datacenterIDBits = 5	machineIDBits    = 5	sequenceBits     = 12	// Max values	maxDatacenterID = (1 << datacenterIDBits) - 1 // 31	maxMachineID    = (1 << machineIDBits) - 1    // 31	maxSequence     = (1 << sequenceBits) - 1     // 4095	// Bit shifts	machineIDShift    = sequenceBits	datacenterIDShift = sequenceBits + machineIDBits	timestampShift    = sequenceBits + machineIDBits + datacenterIDBits)type Generator struct {	mu            sync.Mutex	datacenterID  int64	machineID     int64	sequence      int64	lastTimestamp int64}type DecodedID struct {	Timestamp    time.Time	DatacenterID int64	MachineID    int64	Sequence     int64}func NewGenerator(datacenterID, machineID int64) (*Generator, error) {	if datacenterID < 0 || datacenterID > maxDatacenterID {		return nil, errors.New("datacenter ID out of range")	}	if machineID < 0 || machineID > maxMachineID {		return nil, errors.New("machine ID out of range")	}	return &Generator{		datacenterID:  datacenterID,		machineID:     machineID,		sequence:      0,		lastTimestamp: -1,	}, nil}func (g *Generator) currentTimestamp() int64 {	return time.Now().UnixMilli()}func (g *Generator) waitNextMillis(lastTimestamp int64) int64 {	timestamp := g.currentTimestamp()	for timestamp <= lastTimestamp {		timestamp = g.currentTimestamp()	}	return timestamp}func (g *Generator) NextID() (int64, error) {	g.mu.Lock()	defer g.mu.Unlock()	timestamp := g.currentTimestamp()	if timestamp < g.lastTimestamp {		return 0, errors.New("clock moved backwards")	}	if timestamp == g.lastTimestamp {		// Same millisecond - increment sequence		g.sequence = (g.sequence + 1) & maxSequence		if g.sequence == 0 {			// Sequence exhausted, wait for next ms			timestamp = g.waitNextMillis(g.lastTimestamp)		}	} else {		// New millisecond - reset sequence		g.sequence = 0	}	g.lastTimestamp = timestamp	// Assemble the 64-bit ID	id := ((timestamp - epoch) << timestampShift) |		(g.datacenterID << datacenterIDShift) |		(g.machineID << machineIDShift) |		g.sequence	return id, nil}func (g *Generator) Decode(id int64) DecodedID {	timestampMs := (id >> timestampShift) + epoch	timestamp := time.UnixMilli(timestampMs)	datacenterID := (id >> datacenterIDShift) & maxDatacenterID	machineID := (id >> machineIDShift) & maxMachineID	sequence := id & maxSequence	return DecodedID{		Timestamp:    timestamp,		DatacenterID: datacenterID,		MachineID:    machineID,		Sequence:     sequence,	}}// Usage examplefunc main() {	generator, err := NewGenerator(1, 1)	if err != nil {		panic(err)	}	// Generate unique IDs	orderID, _ := generator.NextID()	userID, _ := generator.NextID()	transactionID, _ := generator.NextID()	fmt.Printf("Order ID: %d\n", orderID)	fmt.Printf("User ID: %d\n", userID)	fmt.Printf("Transaction ID: %d\n", transactionID)	// Decode an ID	decoded := generator.Decode(orderID)	fmt.Printf("Decoded: %+v\n", decoded)	// Concurrent generation	var wg sync.WaitGroup	ids := make(chan int64, 10000)	for i := 0; i < 4; i++ {		wg.Add(1)		go func() {			defer wg.Done()			for j := 0; j < 2500; j++ {				id, _ := generator.NextID()				ids <- id			}		}()	}	wg.Wait()	close(ids)	// Verify uniqueness	unique := make(map[int64]bool)	for id := range ids {		unique[id] = true	}	fmt.Printf("Generated %d unique IDs\n", len(unique))}
The same in Rust
// Snowflake ID generator// 64-bit ID: 1 bit unused | 41 bits timestamp | 5 bits datacenter | 5 bits machine | 12 bits sequenceuse std::sync::Mutex;use std::time::{SystemTime, UNIX_EPOCH};use chrono::{DateTime, Utc};// Custom epoch: Jan 1, 2021const EPOCH: i64 = 1609459200000;// Bit lengthsconst DATACENTER_ID_BITS: u8 = 5;const MACHINE_ID_BITS: u8 = 5;const SEQUENCE_BITS: u8 = 12;// Max valuesconst MAX_DATACENTER_ID: i64 = (1 << DATACENTER_ID_BITS) - 1; // 31const MAX_MACHINE_ID: i64 = (1 << MACHINE_ID_BITS) - 1;       // 31const MAX_SEQUENCE: i64 = (1 << SEQUENCE_BITS) - 1;           // 4095// Bit shiftsconst MACHINE_ID_SHIFT: u8 = SEQUENCE_BITS;const DATACENTER_ID_SHIFT: u8 = SEQUENCE_BITS + MACHINE_ID_BITS;const TIMESTAMP_SHIFT: u8 = SEQUENCE_BITS + MACHINE_ID_BITS + DATACENTER_ID_BITS;#[derive(Debug)]pub struct DecodedId {    pub timestamp: DateTime<Utc>,    pub datacenter_id: i64,    pub machine_id: i64,    pub sequence: i64,}pub struct SnowflakeGenerator {    datacenter_id: i64,    machine_id: i64,    state: Mutex<GeneratorState>,}struct GeneratorState {    sequence: i64,    last_timestamp: i64,}#[derive(Debug)]pub enum SnowflakeError {    InvalidDatacenterId,    InvalidMachineId,    ClockMovedBackwards,}impl SnowflakeGenerator {    pub fn new(datacenter_id: i64, machine_id: i64) -> Result<Self, SnowflakeError> {        if datacenter_id < 0 || datacenter_id > MAX_DATACENTER_ID {            return Err(SnowflakeError::InvalidDatacenterId);        }        if machine_id < 0 || machine_id > MAX_MACHINE_ID {            return Err(SnowflakeError::InvalidMachineId);        }        Ok(Self {            datacenter_id,            machine_id,            state: Mutex::new(GeneratorState {                sequence: 0,                last_timestamp: -1,            }),        })    }    fn current_timestamp() -> i64 {        SystemTime::now()            .duration_since(UNIX_EPOCH)            .expect("Time went backwards")            .as_millis() as i64    }    fn wait_next_millis(last_timestamp: i64) -> i64 {        let mut timestamp = Self::current_timestamp();        while timestamp <= last_timestamp {            timestamp = Self::current_timestamp();        }        timestamp    }    pub fn next_id(&self) -> Result<i64, SnowflakeError> {        let mut state = self.state.lock().unwrap();        let mut timestamp = Self::current_timestamp();        if timestamp < state.last_timestamp {            return Err(SnowflakeError::ClockMovedBackwards);        }        if timestamp == state.last_timestamp {            // Same millisecond - increment sequence            state.sequence = (state.sequence + 1) & MAX_SEQUENCE;            if state.sequence == 0 {                // Sequence exhausted, wait for next ms                timestamp = Self::wait_next_millis(state.last_timestamp);            }        } else {            // New millisecond - reset sequence            state.sequence = 0;        }        state.last_timestamp = timestamp;        // Assemble the 64-bit ID        let id = ((timestamp - EPOCH) << TIMESTAMP_SHIFT)            | (self.datacenter_id << DATACENTER_ID_SHIFT)            | (self.machine_id << MACHINE_ID_SHIFT)            | state.sequence;        Ok(id)    }    pub fn decode(&self, id: i64) -> DecodedId {        let timestamp_ms = (id >> TIMESTAMP_SHIFT) + EPOCH;        let timestamp = DateTime::from_timestamp_millis(timestamp_ms).unwrap();        let datacenter_id = (id >> DATACENTER_ID_SHIFT) & MAX_DATACENTER_ID;        let machine_id = (id >> MACHINE_ID_SHIFT) & MAX_MACHINE_ID;        let sequence = id & MAX_SEQUENCE;        DecodedId {            timestamp,            datacenter_id,            machine_id,            sequence,        }    }}// Usagefn main() {    let generator = SnowflakeGenerator::new(1, 1).unwrap();    // Generate unique IDs    let order_id = generator.next_id().unwrap();    let user_id = generator.next_id().unwrap();    let transaction_id = generator.next_id().unwrap();    println!("Order ID: {}", order_id);    println!("User ID: {}", user_id);    println!("Transaction ID: {}", transaction_id);    // Decode an ID    let decoded = generator.decode(order_id);    println!("Decoded: {:?}", decoded);    // Concurrent generation with threads    use std::thread;    use std::sync::Arc;    let generator = Arc::new(SnowflakeGenerator::new(1, 1).unwrap());    let mut handles = vec![];    for _ in 0..4 {        let gen = Arc::clone(&generator);        handles.push(thread::spawn(move || {            (0..2500).map(|_| gen.next_id().unwrap()).collect::<Vec<_>>()        }));    }    let all_ids: Vec<i64> = handles        .into_iter()        .flat_map(|h| h.join().unwrap())        .collect();    // Verify uniqueness    let unique: std::collections::HashSet<_> = all_ids.iter().collect();    assert_eq!(all_ids.len(), unique.len());    println!("Generated {} unique IDs", all_ids.len());}