Design a Unique ID Generator (Snowflake)

Medium
ConcurrencyDistributed SystemsSnowflakeBit ManipulationMonotonic IDsConcurrency

Problem Statement

Design a distributed unique ID generation service like Twitter Snowflake that generates globally unique, time-ordered, 64-bit integer IDs — supporting high throughput (millions of IDs per second) with no coordination between nodes.

Requirements

Functional Requirements

  • generateId() → returns a unique 64-bit long integer
  • IDs must be roughly time-ordered (sortable by generation time)
  • Support multiple nodes/workers (each with a unique worker ID) — no cross-node coordination
  • Each node can generate up to 4096 IDs per millisecond
  • Extract timestamp, worker ID, and sequence from a generated ID
  • Handle clock skew: if system clock goes backward, wait or throw exception
  • Thread-safe: concurrent ID generation on same node

Non-Functional Requirements

  • O(1) ID generation
  • Single IdGenerator instance per node (Singleton)
  • Configurable bit allocation

Key Entities

  • IdGenerator: Singleton; workerId, datacenterId, sequence, lastTimestamp
  • SnowflakeId structure (64 bits): 1 bit sign + 41 bits timestamp (ms since epoch) + 5 bits datacenterId + 5 bits workerId + 12 bits sequence
  • generateId(): get current ms timestamp, handle clock skew, increment sequence (reset at new ms), combine bits via shift/OR

Constraints

  • Timestamp: 41 bits = 69 years of IDs from custom epoch
  • Sequence: 12 bits = 4096 IDs per millisecond per worker
  • WorkerId + DatacenterId: 10 bits total = 1024 unique nodes
  • Thread-safe via synchronized generateId method
  • Clock going backward by >5ms must throw exception

!Constraints

- 41-bit timestamp (ms since custom epoch) - 5-bit datacenterId + 5-bit workerId = 1024 unique nodes - 12-bit sequence per ms = 4096 IDs/ms/node - Clock skew ≤5ms: wait for clock to catch up; >5ms: throw ClockBackwardException - Thread-safe: synchronized generateId()
Output

Run or submit your code to see output here.