InterviewHubPRO
Section Overview
Q17

Question 17 of 50

Part 2: Real-World High-Scale Architecture Problems (11 - 25)

34%
System Design (50 Qs)•Part 2: Real-World High-Scale Architecture Problems (11 - 25)

Design a Distributed Unique ID Generator (Twitter Snowflake ID).

In Simple Words: Generate unique 64-bit integer IDs across thousands of distributed servers without requiring centralized database auto-increments or slow distributed consensus coordination.

Snowflake 64-Bit Structure:

  1. 1 bit: Unused sign bit (always 0).
  2. 41 bits: Timestamp in milliseconds since custom epoch ($2^{41} approx 69$ years of IDs).
  3. 5 bits: Datacenter ID ($2^5 = 32$ datacenters).
  4. 5 bits: Worker / Machine ID ($2^5 = 32$ servers per datacenter).
  5. 12 bits: Sequence number per millisecond ($2^{12} = 4,096$ IDs per millisecond per machine).
typescript
export class SnowflakeIdGenerator {
  private epoch = 1704067200000n; // Custom epoch: 2024-01-01
  private datacenterId: bigint;
  private workerId: bigint;
  private sequence = 0n;
  private lastTimestamp = -1n;

  constructor(datacenterId: number, workerId: number) {
    this.datacenterId = BigInt(datacenterId & 0x1f);
    this.workerId = BigInt(workerId & 0x1f);
  }

  public nextId(): bigint {
    let now = BigInt(Date.now());
    if (now === this.lastTimestamp) {
      this.sequence = (this.sequence + 1n) & 0xfffn;
      if (this.sequence === 0n) {
        // Millisecond exhausted: wait for next millisecond
        while (now <= this.lastTimestamp) {
          now = BigInt(Date.now());
        }
      }
    } else {
      this.sequence = 0n;
    }

    this.lastTimestamp = now;
    return (
      ((now - this.epoch) << 22n) |
      (this.datacenterId << 17n) |
      (this.workerId << 12n) |
      this.sequence
    );
  }
}