SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Consensus Algorithms
  • Paxos
  • Raft
  • Leader Election
  • ZooKeeper and etcd
  • Distributed Locks
  • Fencing Tokens
  • Gossip Protocol
  • CRDTs
  • Operational Transformation
  • Distributed Unique ID Generation (Snowflake, UUID)
  • Two Generals Problem
  • Byzantine Fault Tolerance (BFT)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Coordination and Consensus

Distributed Unique ID Generation (Snowflake, UUID)

Make unique IDs on many machines at once without asking a central counter every time.

โฑ 13 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Every row, order, message and file needs an ID. On one database, the database can count 1, 2, 3. On many machines, they must make IDs at the same time, without asking a central counter every time, and without ever making the same ID twice.

  • UUID: a 128-bit ID. v4 is random (no order). v7 starts with the time, so it sorts.
  • Snowflake: a 64-bit ID made of time + machine ID + counter. Unique, sortable and small.
  • Others: database auto-increment, ticket servers (hand out blocks of numbers) and ULID. Each trades size, order and coordination.

02Concept: What is it?

An ID generator has two jobs. It must be unique (never the same ID twice, on any machine). Often it should also be roughly sortable by time, so new IDs are bigger than old ones. Sorted IDs make database indexes faster and let you page through results in order.

There are three main ways to get uniqueness without a central counter. Randomness: pick so many random bits that two machines will practically never pick the same (UUID v4). Partitioning: give each machine its own slice of the ID space, such as a machine number in the ID (Snowflake). Ranges: a central service hands out a block of numbers, and each machine uses its block alone (ticket server).

Snowflake was made at Twitter. A 64-bit number is split into parts: 41 bits of time in milliseconds, 10 bits of machine number, and 12 bits of a counter that restarts every millisecond. Two machines never clash because their machine bits differ. One machine never clashes with itself because the counter increases inside the same millisecond. And since time is at the front, newer IDs are bigger.

The Snowflake layout
0๏ธโƒฃ1 bitunused (sign)
๐Ÿ•’41 bitsmilliseconds since an epoch (about 69 years)
๐Ÿ–ฅ๏ธ10 bitsmachine ID (1,024 machines)
๐Ÿ”ข12 bitscounter (4,096 per ms)
64 bits: one unused, then time, machine, counter.
๐Ÿง Unique is the hard rule, sorted is the bonus
A duplicate ID is a bug that overwrites someone else's data. An ID that is slightly out of time order is only a small annoyance. Design for the first, then optimise the second.

03Real-Life Example

๐ŸตRaffle Tickets in Many Shops
A chain of shops sells raffle tickets, and no ticket number may appear twice. One way: phone head office for every ticket (slow, and head office is busy). Another: each shop prints its own tickets using date + shop number + counter, such as 0412-07-0031. No two shops can ever match, since the shop number differs, and tickets sort by date. A third way: head office gives each shop a box of 100 numbers at a time, and the shop only calls when its box is empty.
Raffle shops
ID generation
Calling head office for every ticket
Auto-increment in one database
Date + shop number + counter
Snowflake: time + machine + counter
A box of 100 numbers per shop
Ticket server handing out ranges
Long random ticket, no one checks
UUID v4
Random ticket that starts with the date
UUID v7 or ULID
The shop clock was set back by mistake
Clock going backwards, risk of duplicates
Two shops given the same number
Duplicate machine ID
One Snowflake ID being made
๐Ÿ•’Nowms since epoch
โ†’โ†“+
๐Ÿ–ฅ๏ธMachine 7from config
โ†’โ†“+
๐Ÿ”ขCounter 3third ID this ms
โ†’โ†“pack
๐Ÿ†”One 64-bit IDfits in a database BIGINT

04Why Do We Need It?

๐Ÿš€No bottleneck
Each machine makes IDs alone. No network call on the hot path.
๐ŸงฉSafe in many places
Many servers, many databases and many regions can all create IDs without clashing.
๐Ÿ“ˆFaster indexes
IDs that grow keep new rows at the end of a B-tree. Random IDs scatter writes everywhere.
๐Ÿ“„Easy paging
"Give me rows after ID X" works well when IDs follow time.
๐Ÿ”€Sharding friendly
IDs made before a row is stored let you choose the shard without asking a database.
๐ŸชชNo leaks
Unlike 1, 2, 3, a random ID does not reveal how many orders you have.
Pick a scheme that is unique without coordination, and sortable if your database or paging needs it.

05Where Do We Use It?

๐ŸฆTweets and posts
Twitter created Snowflake so tweet IDs sort by time across thousands of servers.
๐Ÿ“ธPhoto and message IDs
Instagram and Discord use Snowflake-style IDs built into their databases or services.
๐Ÿ›’Orders and payments
Order IDs must be unique across regions and safe to retry.
๐Ÿ“จMessage and event IDs
Idempotency keys and dedupe tables rely on unique IDs per message.
๐Ÿ—„๏ธPrimary keys
UUIDs are often the primary key when data is made on many clients or in many places.
๐Ÿ”ŽTracing
Trace and span IDs are random IDs made on every service.

06Types / Parts / How It Works

The main schemes

SchemeSizeSorted by time?NeedsWeak spot
Auto-increment64 bitsYes, strictlyOne databaseA bottleneck and a single point of failure
UUID v4128 bitsNoNothingBig, random, bad for index locality
UUID v7128 bitsYesA clockBig, order within a millisecond is loose
ULID128 bits (26 chars)YesA clockSimilar to UUID v7
Ticket server64 bitsRoughlyA small serviceService must be highly available
Snowflake64 bitsYes, roughlyA clock and a machine IDClock going back, duplicate machine IDs

Auto-increment and ticket servers

One database with AUTO_INCREMENT gives perfect 1, 2, 3, but all writes go through it. A well-known trick: run two or more databases, one makes odd IDs and one makes even IDs. A ticket server goes further: a machine asks for a block (say 1,000 numbers) and uses them locally. The service is called rarely, and a crash only wastes a block.

UUID versions

VersionMade fromNotes
v1Time + MAC addressLeaks the machine, and is not sorted well
v4Random bits (122 of them)Most common, simple, no order
v748-bit time + randomSorts by time, a good modern default for keys

Snowflake in detail

Why the three parts together are enough
Different times
๐Ÿ•’Time bits differno clash across milliseconds
Same ms, different machines
๐Ÿ–ฅ๏ธMachine bits differno clash across servers
Same ms, same machine
๐Ÿ”ขCounter differsno clash inside one server
Each part closes one way of clashing.
Time Machine Counter

Where the machine ID comes from matters: a config file, an environment variable, or a short lease from ZooKeeper or etcd. Where the counter overflows (more than 4,096 IDs in one millisecond) the generator waits for the next millisecond.

VisualizerMake IDs with different schemesSwitch between UUID v4, UUID v7, auto-increment, ticket server, Snowflake and ULID. Look at the sizes, whether they sort, and what each one needs. Then turn on โ€œSteps back at ID 6โ€ to see what a bad clock does: Snowflake can repeat an ID, the others stay unique.
ID scheme
The clock
The 64 bits of a Snowflake ID (1 bit is unused, always 0)
0
41 bits time (ms since an epoch)
10 bits machine
12 bits counter
41 bits of milliseconds is about 69 years. 10 bits allow 1,024 machines. 12 bits allow 4,096 IDs per machine per millisecond.
IDs in the order they were created (server shown on the left)
#1 S11724551110456246272
#2 S21724551110464638976
#3 S31724551110473031680
#4 S11724551110481412096
#5 S21724551110489804800
#6 S31724551110498197504
#7 S11724551110506577920
#8 S21724551110514970624
Duplicates
0
must always be 0
Out of order
0
by time
Sortable
Yes
Yes, roughly by time
Size: 64 bits: 41 time + 10 machine + 12 counter
Needs: A clock and a unique machine ID
Bad clock: Dangerous: can repeat IDs
Collisions: None, unless the clock goes back
Snowflake: 0 duplicates and 0 out of order in these 8 IDs. Try the bad clock to see what time-based schemes risk.

The "random" digits come from a fixed formula so the page looks the same every time. Real UUIDs and ULIDs use a secure random source. The clock step is a simple model: it replays an earlier millisecond.

07How to Use It / Steps / Implementation

Building a Snowflake-style generator

  1. 1
    Choose a custom epoch
    Count milliseconds from your own start date (say the launch day) so the 41 bits last about 69 years from then.
  2. 2
    Give each machine a unique ID
    Use config, or take a short lease from ZooKeeper or etcd. Two machines with the same ID will clash.
  3. 3
    Read the clock in milliseconds
    Use the wall clock for time, and keep the last timestamp you used.
  4. 4
    Same millisecond? Add 1 to the counter
    If the counter goes over 4,095, wait until the next millisecond.
  5. 5
    New millisecond? Reset the counter to 0
    Some designs start at a random value to spread IDs across shards.
  6. 6
    Clock went backwards? Do not make IDs
    Wait until the clock catches up, or fail loudly. Never reuse an earlier time.
  7. 7
    Pack the bits
    (time << 22) | (machine << 12) | counter. Use a 64-bit integer.
๐Ÿ’กChoosing quickly
Need no coordination and no ordering? UUID v4. Need keys that sort and can live with 128 bits? UUID v7 or ULID. Need compact 64-bit IDs at very high rates? Snowflake. One small database? Auto-increment is fine.
โš ๏ธDo not let clients choose
If a user can send their own ID, they can reuse someone else's. Make IDs on the server, or check them.

08Key Terms to Know

TermMeaning in easy words
UUIDUniversally Unique Identifier, a 128-bit ID usually written as 32 hex digits
SnowflakeA 64-bit ID made of time, machine ID and counter
ULIDA 128-bit, time-sorted ID written in 26 text characters
EpochThe starting moment that time is counted from
Machine ID / worker IDA number that is different on every ID generator
Sequence / counterA number that grows for IDs made in the same millisecond
Ticket serverA service that hands out blocks of numbers to many machines
CollisionTwo different things getting the same ID
k-sortableRoughly sorted by time, with small errors
Clock skewTwo clocks (or one clock at two moments) disagreeing
Birthday paradoxWhy collisions in random IDs happen sooner than you think
MonotonicAlways going up, never back

09Pros, Cons and Trade-offs

โœ… Pros
  • No central bottleneck
  • Very fast: one local calculation
  • Safe across machines, shards and regions
  • Time-based IDs help indexes and paging
  • Snowflake is only 64 bits and fits a BIGINT
  • Works offline, even in the client (UUID)
โš ๏ธ Cons
  • Clock problems can cause duplicates (Snowflake)
  • Machine IDs must be managed
  • Random UUIDs hurt index locality and are big
  • Time-based IDs leak when something was created
  • Order is only approximate across machines
  • Changing scheme later is painful

Trade-offs

ChoiceWe gainWe lose
UUID v4Zero setup, no coordinationSize and no ordering
UUID v7 / ULIDSorted, no machine IDs128 bits, and a clock
SnowflakeSmall, sorted, fastMachine ID management and clock risk
Ticket serverStrict ranges, no clockA service to run, wasted numbers on crash
Auto-incrementSimplest, perfectly orderedDoes not scale writes
Fewer machine bitsMore counter or timeFewer generators

10Common Problems and Mistakes

Common mistakes

  1. Trusting the clock. NTP can step a clock back. A Snowflake generator that ignores this can repeat an ID.
  2. Reusing a machine ID. Two live servers with the same ID produce the same IDs in the same millisecond.
  3. Using the wall clock as an exact order. IDs from different machines are only roughly in time order.
  4. Random UUIDs as a clustered primary key. Inserts scatter across the table and pages split constantly.
  5. Exposing sequential IDs. Competitors can count your orders, and attackers can guess the next one.
  6. Overflowing the counter. More than 4,096 IDs in one millisecond must wait, not wrap around.
  7. Sending 64-bit IDs as JSON numbers. JavaScript loses precision above 253. Send them as strings.

Things to watch

โชClock goes back
Keep the last time. If now is smaller, wait or fail.
๐Ÿ–ฅ๏ธMachine ID leases
Release IDs when machines die, and never give one to two live machines.
๐Ÿ“…Epoch running out
41 bits last about 69 years. Plan the end date.
๐Ÿ” String vs number
Big IDs break in JavaScript numbers. Use strings at the API edge.

11Real-World Examples

๐ŸฆTwitter Snowflake
The original. Tweet IDs sort by time, and anyone can read the time back out of the ID.
๐Ÿ“ธInstagram
Makes 64-bit IDs inside PostgreSQL using time, a shard ID and a per-shard sequence.
๐ŸŽฎDiscord
Uses Snowflake IDs with its own epoch for messages, users and servers.
๐ŸŽซFlickr ticket servers
Used two MySQL servers with odd and even auto-increment to make unique IDs.
๐ŸงพMongoDB ObjectId
12 bytes: time, random value, and a counter. Same idea, different layout.
โ˜๏ธAWS and Google IDs
Cloud resources and trace IDs use random 128-bit values.
Mini case: the clock steps back
๐Ÿ•’ms 1000, counter 0makes ID X
โ†’โ†“NTP steps the clock back
๐Ÿ•’ms 998... 1000 againcounter restarts at 0
โ†’โ†“same time, machine, counter
๐Ÿ’ฅSame ID X againone row overwrites the other
Without a guard, a Snowflake server can make the same ID twice.

12Related Topics to Read Next

Shardingโ†’

IDs often decide which shard a row goes to.

Consistent Hashingโ†’

Another way to spread IDs over machines.

Clock Synchronization Problemโ†’

Why clocks go wrong and IDs can repeat.

NTP: Network Time Protocolโ†’

The thing that can step a clock back.

Hybrid Logical Clocks (HLC)โ†’

A time-plus-counter idea close to Snowflake.

Idempotencyโ†’

Unique request IDs make retries safe.

ZooKeeper and etcdโ†’

A good place to lease machine IDs.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Goal: unique first, roughly time-sorted second.
  • โœ”Snowflake: 1 + 41 time + 10 machine + 12 counter = 64 bits.
  • โœ”UUID v4: random, no order. v7: time first, sorted.
  • โœ”Ticket server: hand out blocks, so the service is called rarely.
  • โœ”Auto-increment: simple, but one bottleneck.
  • โœ”Danger: clock going back, or two machines with the same ID.
  • โœ”API tip: send big IDs as strings.
  • โœ”One line: โ€œMix the time, the machine and a counter, and no two IDs ever meet.โ€
โ† Previous
Operational Transformation
Next โ†’
Two Generals Problem