Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Distributed ID Generation Strategies in Modern Systems

Tech Nov 11 17

As monolithic architectures evolve into distributed systems, generating globally unique, scalable, and performent identifiers becomes a foundational challenge. A robust distributed ID scheme must satisfy uniqueness across nodes, monotonic ordering (where beneficial), high throughput, resilience to failures, and compatibility with storage layers like relational databases.

Core Requirements for Distributed IDs

  • Uniqueness: Guaranteed collision-free IDs across all services and regions.
  • Ordering: Time-ordered or roughly sequential IDs aid indexing, range queries, and time-based sharding.
  • Scalability: Horizontal growth without central bottlanecks or coordination overhead.
  • Availability: Tolerates partial infrastructure failure—no single point of failure.
  • Efficiency: Sub-millisecond latency at high concurrency; minimal I/O or network round trips.

Popular Implementation Approaches

UUID (v4)

Universally Unique Identifiers (RFC 4122) generate 128-bit random strings, e.g., 5a7e9c2f-1b3d-4e8a-9f0c-2d1e4a6b8c9d. In Java:

@Test
void generateUuid() {
    String id = UUID.randomUUID().toString();
    System.out.println(id); // e.g., "f8a1b2c3-d4e5-4f67-890a-1b2c3d4e5f67"
}

Pros: Zero coordination, simple, widely supported.
Cons: 128-bit size harms index efficiency in B+ tree structures (e.g., MySQL); non-sequential inserts cause page splits; MAC-based variants risk hardware fingerprint leakage.

Database-Centric Schemes

Auto-Increment with Sharding Keys

Using AUTO_INCREMENT per shard works only within isolated tables. To achieve global uniquenesss, a dedicated sequence table is often employed:

CREATE TABLE id_allocator (
  biz_tag VARCHAR(32) PRIMARY KEY,
  next_id BIGINT NOT NULL DEFAULT 1,
  step INT NOT NULL DEFAULT 1000,
  version INT NOT NULL DEFAULT 0
) ENGINE=InnoDB;

ID acquisition uses optimistic locking:

UPDATE id_allocator 
SET next_id = next_id + step, version = version + 1 
WHERE biz_tag = 'order' AND version = ?;

If the update affects zero rows, retry with refreshed version. This avoids contention but introduces database dependency and potential hotspots.

Segment Allocation (Batched Sequences)

Services pre-fetch blocks of IDs (e.g., [1001–2000]) and serve them locally until exhausted. A typical schema:

CREATE TABLE id_segments (
  id TINYINT PRIMARY KEY,
  biz_type VARCHAR(16),
  max_allocated BIGINT NOT NULL,
  segment_size INT NOT NULL,
  version INT NOT NULL DEFAULT 0
);

On depletion, the service atomically increments max_allocated by segment_size. This reduces DB round trips dramatically but may lead to gaps after crashes or redeployments.

Redis-Based Incrementers

Leveraging Redis’ atomic INCR command provides low-latency, ordered numeric IDs. For fault tolerance, multiple Redis masters can be used with modulo-based key routing:

@Component
public class RedisIdGenerator {

    private static final long EPOCH = 1659312000L; // Sep 1, 2022 UTC

    @Autowired private StringRedisTemplate redis;

    public long nextId(String namespace) {
        LocalDateTime now = LocalDateTime.now(ZoneOffset.UTC);
        long timestamp = now.toEpochSecond(ZoneOffset.UTC) - EPOCH;
        String key = String.format("id:%s:%s", namespace, now.format(DateTimeFormatter.ofPattern("yyyyMM")));
        long seq = redis.opsForValue().increment(key);
        return (timestamp << 22) | (seq & 0x3FFFFF); // 42-bit ts + 22-bit seq
    }
}

Pros: High throughput, natural ordering, decoupled from RDBMS.
Cons: Requires Redis infrastructure; persistence and failover configuration add operational complexity.

Snowflake Variants

Original Twitter Snowflake

A 64-bit integer composed as: 1-bit | 41-bit timestamp | 10-bit node ID | 12-bit sequence. The timestamp portion enables temporal sorting; node IDs prevent inter-node collisions. Java implementation highlights:

public class IdWorker {
    private final long epoch;
    private final long workerId;
    private final long datacenterId;
    private final long sequenceBits = 12L;
    private final long workerIdBits = 5L;
    private final long datacenterIdBits = 5L;
    
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public synchronized long nextId() {
        long curr = System.currentTimeMillis();
        if (curr < lastTimestamp) throw new IllegalStateException("Clock moved backwards");
        
        if (curr == lastTimestamp) {
            sequence = (sequence + 1) & ((1L << sequenceBits) - 1);
            if (sequence == 0) curr = waitNextMillis(curr);
        } else {
            sequence = 0L;
        }
        lastTimestamp = curr;

        return ((curr - epoch) << (workerIdBits + datacenterIdBits + sequenceBits))
                | (datacenterId << (workerIdBits + sequenceBits))
                | (workerId << sequenceBits)
                | sequence;
    }
}

Supports ~4 million IDs/sec per node, but requires stable clock and pre-assigned node identifiers.

Enhanced Implementations

  • UidGenerator (Baidu): Optimizes bit layout—28-bit timestamp, 22-bit worker ID, 13-bit sequence—enabling >6M QPS via ring-buffer caching and MySQL-backed worker registration.
  • Leaf (Meituan): Offers dual modes—segment (DB-backed batch allocation with double-buffer preloading) and snowflake (ZooKeeper-assigned worker IDs). Achieves 50K+ QPS with sub-millisecond p99 latency.
  • TinyID (Didi): Focuses on simplicity and multi-master DB support. Uses HTTP and embedded client SDKs; supports configurable step sizes (e.g., odd-only sequences) and automatic failover between DB replicas.
Tags: snowflake

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.