Snowflake Algorithm (Snowflake ID)
March 3, 2025About 1 min
Snowflake Algorithm (Snowflake ID)
Introduction
The Snowflake Algorithm is a distributed ID generation algorithm developed by Twitter. It is designed for high-concurrency environments to generate globally unique IDs with sequential order, uniqueness, and high performance.
Snowflake ID Structure
A Snowflake ID is a 64-bit long integer, structured as follows:
Sign Bit (1bit) | Timestamp (41bit) | Machine ID (10bit) | Sequence Number (12bit) |
---|---|---|---|
0 | 41-bit Timestamp | 10-bit Machine ID | 12-bit Sequence Number |
- 1-bit Sign: Always
0
(ensures positive numbers) - 41-bit Timestamp: Stores
(current time - custom epoch)
, supports approximately 69 years - 10-bit Machine ID: Supports up to
1024
unique machine nodes - 12-bit Sequence Number: Supports
4096
unique IDs per millisecond
Advantages of Snowflake Algorithm
✅ Globally Unique: No duplicate IDs
✅ Increasing Trend: Optimized for database indexing and insert performance
✅ High Performance: Locally generated, no database or central server required
✅ Distributed Support: Multiple nodes generate IDs independently without communication
Java Implementation
public class SnowflakeIdGenerator {
private final long epoch = 1640995200000L; // Custom epoch (2022-01-01)
private final long workerIdBits = 10; // Bits for machine ID
private final long sequenceBits = 12; // Bits for sequence number
private final long maxWorkerId = ~(-1L << workerIdBits); // Max machine ID
private final long sequenceMask = ~(-1L << sequenceBits); // Max sequence number
private final long workerIdShift = sequenceBits; // Shift for machine ID
private final long timestampLeftShift = sequenceBits + workerIdBits; // Shift for timestamp
private long workerId; // Machine ID
private long sequence = 0L; // Sequence number
private long lastTimestamp = -1L; // Last generated timestamp
public SnowflakeIdGenerator(long workerId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException("Worker ID out of range");
}
this.workerId = workerId;
}
public synchronized long nextId() {
long timestamp = System.currentTimeMillis();
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards, refusing to generate ID");
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
while ((timestamp = System.currentTimeMillis()) <= lastTimestamp) {}
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
return ((timestamp - epoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
}
public static void main(String[] args) {
SnowflakeIdGenerator generator = new SnowflakeIdGenerator(1);
for (int i = 0; i < 10; i++) {
System.out.println(generator.nextId());
}
}
}
Conclusion
- nowflake Algorithm is ideal for high-concurrency distributed systems
- IDs are increasing and optimized for database storage
- Avoids single points of failure in centralized ID generation