AI Hints
Home›System Design Tutorial›IDs and Security
System Design · Lesson 88 of 120

Unique IDs at Scale

Snowflake IDs.

⏱ 2 min read▶ Video at 1:45:53🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

On one database, order IDs are easy. Each new order gets the next number. But with ten shards, each counting on its own, two orders could get the same ID. We need IDs that are unique across many machines.

Unique IDs at Scale
From the video: Unique IDs at Scale
  • One DB: just count
  • Ten shards: clashes
  • Unique across machines

Options

There are a few options. A central counter is simple, but it's a single point of failure. Random UUIDs never clash, but they're long, and don't sort by time. Snowflake IDs, invented at Twitter, are short, unique, and roughly sorted by time, and every machine can make them on its own.

OptionUniqueShortTime-sorted
Central counteryesyesyes (bottleneck)
UUIDyesnono
Snowflakeyesyesyes

A snowflake ID

A snowflake ID is a sixty four bit number, built from three parts. The time in milliseconds, a machine number, and a sequence number for IDs made in the same millisecond. Run it. Two machines make IDs at the same moment, and they never clash. And the time can be read back out of the ID.

snowflake.pypython
EPOCH = 1_700_000_000_000   # custom start, in ms

def snowflake(ms, machine, seq):
    return ((ms - EPOCH) << 22) | (machine << 12) | seq

now = 1_794_400_000_000
a = snowflake(now, machine=1, seq=0)
b = snowflake(now, machine=2, seq=0)
c = snowflake(now, machine=1, seq=1)
print(a, b, c, sep="\n")
print("time back out:", (a >> 22) + EPOCH == now)
Output
395942297600004096
395942297600008192
395942297600004097
time back out: True

Summary

Snowflake IDs combine time, machine, and a sequence, so every machine can make unique, sortable IDs on its own. Next, keeping out the people who shouldn't get in.

Key takeaways
  • Time + machine + sequence
  • No central counter
  • Sorted by time
Next up: Security Basics — authentication and authorization