Home

Posts

Tags

Design Distributed ID Generator

The Problem

In a distributed system with multiple servers/nodes, you can’t rely on simple auto-incrementing database IDs because:

This post explores how to design a distributed ID generator that can scale to hundreds of thousands of IDs per second across multiple data centers.

Requirements & Constraints

Functional Requirements

Scale:

ID Properties:

Infrastructure:

Performance:

Key Design Questions

Architecture Decision: Centralized vs Distributed?

Bit Allocation: How to structure the 64-bit ID?

Machine ID Assignment: How do servers get unique IDs?

Clock Issues: What if the system clock goes backwards?

Why Not UUIDs?

Before diving into our solution, let’s understand why random UUIDs aren’t ideal:

Problems with Random UUIDs:

Solution: Time-ordered IDs (Snowflake approach) solve these issues by keeping related IDs together.

The Solution: 64-Bit Snowflake ID Structure

Our ID is composed of 4 parts within 64 bits:

1Sibg0int4TM1iimlbelisittssaemcp1MI0aDcbhiitnse1SN2euqmbubieetnrsce

Bit Allocation Breakdown

1. Sign Bit (1 bit): Always 0

2. Timestamp (41 bits):

3. Machine ID (10 bits):

4. Sequence Number (12 bits):

Capacity Analysis

With our bit allocation:

This provides excellent headroom for growth.

Handling Edge Cases

Clock Drift: When Time Goes Backwards

The Problem: If the system clock moves backwards, we risk generating duplicate IDs.

Detection: Simple comparison

ifcu#rrCelnotc_ktimmoeve<dlbaasctk_wtairmdess!tamp:

Handling Strategies:

  1. Wait Strategy (Small drift < 5ms):

    • Pause and wait for clock to catch up
    • Best for minor NTP adjustments
  2. Continue Strategy (Medium drift 5-100ms):

    • Keep using last_timestamp
    • Continue incrementing sequence number
    • Acceptable since IDs don’t need precise timestamps
  3. Reject Strategy (Large drift > 100ms):

    • Return error and log incident
    • Prevents service from generating bad IDs
    • Requires manual intervention
  4. Hybrid Approach (Recommended):

    dieerflliisfdfetrwu:riadsa=fireittisl_flea<utasnsCt5t<tl_mi_otsl1tci:(0ikml0mDeamerssssitt:tfa_atmtmEpiprmr-e+osrctiuanrmcrpre)enmte_nttimseequence

Prevention & Monitoring:

Sequence Number Exhaustion

Problem: What if we generate 4,096 IDs within the same millisecond?

Solution Options:

  1. Wait for next millisecond (Recommended): Brief pause, guaranteed uniqueness
  2. Return error: Fail fast, let caller retry
  3. Spin wait: Busy-wait until clock advances

Machine ID Assignment

Options:

  1. Manual Configuration:

    • Simple: Add machine ID to config file
    • Pros: No external dependencies
    • Cons: Human error risk, manual tracking
  2. ZooKeeper/Consul:

    • Auto-assign IDs from a range
    • Pros: Automated, centralized tracking
    • Cons: External dependency
  3. Database Registration:

    • Servers register on startup
    • Pros: Audit trail, easy monitoring
    • Cons: Database dependency

Recommendation: Use ZooKeeper for automatic assignment with manual override capability.

Implementation Considerations

Multi-Datacenter Support

Split the 10-bit machine ID:

Time Precision Trade-offs

Milliseconds (Chosen):

Seconds:

ID Generation Algorithm

functciiel#iriuffladeorssCtnrcceto=ueuhusi:s_nrgnrarefets(snetrnrqqit(men_edeusumrcaqietnlnee#ceeuucudritetnqunscrheam___cuErcttrintetcteexreaenceilinhemtnee_=mom=can=pht_ieceeute_idgk(s_0=td(e<_=s=ttIi)tb=e=eicDm:_laqdmuecaclu0eruskae:sr-1rtwsne=e2r_atcqnE)etr_euwtPnidtea_Otmsi+nitC_e(mctiHmsce1e_m)itus),nelartelmra&wxipemats:np4i_2et:0tm2c_9i)ot5flnioldmrise#s()ne)1ec2xo-tnbdim(tillamlsaitss_ketciomnedstamp)

Advantages of This Design

  1. Scalable: Supports up to 1,024 machines generating 4B+ IDs/second
  2. Time-ordered: IDs naturally sort by creation time
  3. Database-friendly: Sequential IDs improve B-tree index performance
  4. Compact: Only 64 bits (vs 128 for UUIDs)
  5. Independent: No coordination needed between servers
  6. Fast: Sub-millisecond latency, no network calls
  7. Debuggable: Can extract timestamp and machine ID from any ID

Conclusion

The Snowflake approach provides an excellent balance between simplicity, performance, and scalability for distributed ID generation. By carefully allocating bits across timestamp, machine ID, and sequence number, we achieve:

This design has been battle-tested at scale by Twitter, Instagram, Discord, and many others, making it a proven solution for distributed systems.

Tags: