Skip to content
HLD Learn/Unique IDs & Distributing Data

Generating Unique IDs at Scale

4 min read

You'll learn to

  • -Explain why auto-increment IDs break down across multiple databases
  • -Describe how Snowflake-style IDs work

Every database you've used so far in this course has had one instance handing out IDs, trivial with auto-increment. That assumption is about to break: the rest of this module is about splitting data across multiple database instances, and the moment there is more than one instance, "just increment a counter" no longer works, because two instances would each hand out their own 1, 2, 3... with no coordination between them.

Why Auto-Increment Breaks Down

If Shard A and Shard B both auto-increment independently, they will both eventually assign id=482 to two completely different records. You need IDs that are unique across the whole system, not just within one database instance.

UUIDs

A UUID is a 128-bit random (or pseudo-random) value, collision-probability so low it's treated as impossible in practice. Any machine can generate one with zero coordination with any other machine. The cost: UUIDs are large (compared to a 64-bit integer), and the common random variant (v4) has no inherent ordering; you can't tell which of two UUIDs was created first just by looking at them.

Snowflake-Style IDs

Twitter's Snowflake approach (since adopted widely, including by Discord) packs a timestamp, a machine/worker identifier, and a per-millisecond sequence number into a single 64-bit integer. The result is compact like a normal integer, globally unique without central coordination, and, critically, sortable by creation time just by comparing the numbers, since the timestamp is the leading bits.

Doing the Math on a 64-bit Snowflake ID
41 bits
Timestamp - good for ~69 years from a chosen epoch
10 bits
Machine ID - up to 1,024 unique ID-generator nodes
12 bits
Sequence - up to 4,096 unique IDs per node, per millisecond
~4.19M/sec
Max cluster-wide ID throughput (4,096 x 1,024 nodes)

Notice the trade-off pattern again: UUIDs optimize for zero-coordination simplicity, Snowflake IDs optimize for compactness and sortability at the cost of needing a coordinated machine-id assignment scheme. Neither is "better": they solve slightly different problems.

Interview Signal

Why does it matter that Snowflake IDs are sortable by creation time, but UUIDs aren't?

Weak Answer

"Sortable IDs are just a nice-to-have for debugging."

Strong Answer

"It affects real performance, not just convenience. A database index on a sortable ID gets new rows appended at the end, which is cheap. A random UUID as a primary key scatters inserts across the index unpredictably, causing far more index page splits and worse write performance at scale, which is exactly why systems that need both scale and natural time-ordering (like this one) tend to reach for Snowflake-style IDs over UUIDs."

ScaleDojo Logo
Initializing ScaleDojo