Unique IDs at Scale
Snowflake IDs.
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.

- 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.
| Option | Unique | Short | Time-sorted |
|---|---|---|---|
| Central counter | yes | yes | yes (bottleneck) |
| UUID | yes | no | no |
| Snowflake | yes | yes | yes |
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.
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)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