Back to 20 Concepts
scaling • Intermediate
Distributed ID Generation: Twitter Snowflake vs UUIDv4/v7
UUIDv4 (128-bit random) causes severe B+ Tree database index fragmentation. Twitter Snowflake generates 64-bit monotonically time-sortable IDs containing Timestamp, Machine ID, and Sequence counter.
Intuitive Mental Model
The Manufacturing Serial Number: A car VIN number encodes the year of manufacture, factory location, and sequential chassis number in a single compact code.
Architecture Blueprint & CodeProduction Standard
// 64-bit Twitter Snowflake Layout:
// 1 bit: Unused (sign bit = 0)
// 41 bits: Epoch Timestamp (69 years of millisecond precision)
// 10 bits: Machine ID (1,024 independent server instances)
// 12 bits: Sequence Counter (4,096 IDs per millisecond per machine!)
function generateSnowflake(epochMs: number, machineId: number, sequence: number): bigint {
return (BigInt(epochMs) << 22n) | (BigInt(machineId) << 12n) | BigInt(sequence);
}Key Architectural Takeaways
- •64-Bit Integer Efficiency: Fits in standard BIGINT column, indexed 2x faster than 128-bit UUIDs.
- •Naturally Time-Sortable: Sorting by ID automatically orders records chronologically without secondary indexes.
Common Architectural Pitfall
Using random UUIDv4 as a primary key clustered index in MySQL/PostgreSQL, causing catastrophic B+ Tree page splits.
Production Best Practice
Use time-sortable 64-bit Snowflake IDs or UUIDv7 for clustered database primary keys.