Unique ID generator
medium 28 minGive every record its own number, from many servers at once.
Video lesson · Chapter 1 of 5
An order number made from three fields
Unique IDs in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A unique ID generator hands out identifiers that are never given twice, even when many servers ask at the same moment. Every order, user, message and file needs one.
The hard part is doing it without asking one central place each time. Either the numbers are shared out beforehand, or each server builds numbers from parts that no other server can produce.
In one line: give every piece of data its own passport number that works everywhere.
Why it exists
A counter inside each server starts at 1 everywhere, so two servers give the same number. One counter for all of them is correct, but every write must reach it, and it stops all writes when it stops.
The ID also decides other things: how big every index is, whether new rows sit together on disk, whether a list can be sorted by age, and what a stranger can learn from a link.
A short history
2005
RFC 4122 standardises the 128-bit UUID, including version 4, which is mostly random bits.
2010
Twitter announces Snowflake: 64-bit, roughly time-ordered IDs made by many machines without asking each other.
2024
RFC 9562 replaces RFC 4122 and adds UUID version 7, which starts with the time in milliseconds.
2025
PostgreSQL 18 ships a built-in
uuidv7()function.
Words to know
- Sequence
- A counter kept by one database, usually with gaps.
- Range lease
- A block of numbers given to one server, to use in memory.
- UUID
- A 128-bit identifier. Version 4 is random, version 7 starts with the time.
- Snowflake ID
- A 64-bit number made of time, machine number and a small counter.
- Epoch
- The moment from which the time in an ID is counted.
- K-sorted
- Nearly in order: an item is at most a small time away from its right place.
- Clock rollback
- A computer clock that is set to an earlier time.
How it works
Step through the idea, or press Play.
Need. A record needs a number that nobody else will use
Understand it
Start here
The raffle
Two ideas: share out the numbers before, or build them from parts that nobody else has.
What a good ID offers
Unique
Never two the same, in any server or region.
Fast
Millions a second in total, without waiting for a call.
Sortable
Newer IDs are larger. Useful, not always wanted.
Independent
A server can work while the coordinator is away.
Compact
64 bits fit in one integer column; 128 bits double the key.
Readable time
The creation time can be taken out of the ID again.
Simple
One counter in a database
Auto-increment is the right answer for one database. It is simple and it cannot repeat. It is not gapless: PostgreSQL does not give a number back when a transaction fails.
Good
- One line of SQL
- Small and ordered
- Nothing else to run
Not so good
- One place for every write
- A network call before you know the ID
- Two databases both start at 1
- Order number 1042 tells a rival how many orders you have
Two databases without clashes
| Trick | How | Weakness |
|---|---|---|
| Odd and even | One starts at 1, the other at 2, both add 2 | Adding a third database means a new plan |
| Shard number inside | Put the shard number in some of the bits | Number of shards has a limit |
| One ticket table | A small database only for numbers | Must be made redundant |
Share out
Leased ranges
A coordinator stores one number: the start of the next free block. A server takes a block in one atomic step, then counts in memory. It asks again only when the block runs out.
Taking a block
How often do we ask?
Random
UUID version 4
122 random bits, made anywhere, without any coordination. The standard is supported in nearly every language. The price is size and scattered inserts: RFC 9562 notes that version 4 has poor database-index locality, because new values land at random places of the B-tree.
How likely is a clash?
Time first
UUIDv7 and ULID
Both begin with 48 bits of milliseconds since 1970 and end with random bits. New values are close together, so inserts go to one end of the index and the list is sorted by time. UUIDv7 looks like any other UUID; a ULID is written as 26 letters and digits without special characters.
Snowflake
The 64 bits of a Snowflake ID
The layout
| Bits | Part | Range | Meaning |
|---|---|---|---|
| 1 | Unused | 0 | Keeps the number positive |
| 41 | Time | about 69.7 years | Milliseconds since a chosen epoch |
| 5 | Datacenter | 0 to 31 | Set when the server is deployed |
| 5 | Machine | 0 to 31 | Given once, for example by ZooKeeper |
| 12 | Counter | 0 to 4,095 | Starts again each millisecond |
How much can it make?
Making one ID
EPOCH = 1609459200000 # 1 January 2021ms, dc, machine, counter = 1703836800000, 1, 7, 1i = (ms - EPOCH) << 22 | dc << 17 | machine << 12 | counterprint(i) # 395848345190559745print((i >> 22) + EPOCH, i >> 17 & 31, i >> 12 & 31, i & 4095)assert i < 2 ** 63Architecture
Inside the service, not beside it
Two instances, two machine numbers
A library or a service?
| Choice | Good | Cost |
|---|---|---|
| Library in each server | No call, no extra system | Each process needs a machine number |
| ID service | One place to run and watch | A network call for each ID, unless you ask for many at once |
| Default in the database | Simplest | The ID is known only after the insert |
Danger
Clocks and machine numbers
Snowflake IDs are unique under two conditions: no two machines share a number, and no machine lives through the same millisecond twice.
- 1
Clock moves back a little
Wait until it passes the last used time. The original refused to make IDs until then.
- 2
Clock moves back a lot
Refuse, take the server out of service and alert. Waiting an hour helps nobody.
- 3
Restart after a rollback
The last time lived in memory. Store it now and then, or wait at start for longer than the largest expected jump.
- 4
Machine number
Lease it with a lifetime from ZooKeeper, etcd or a table. Stop making IDs if the lease cannot be renewed in time. Do not give an old number out again at once.
- 5
Prevention
Keep clocks in step with NTP in a mode that slows or speeds the clock instead of jumping, and watch the offset.
Why not choose the machine number at random?
Choose
Which one?
Compared
| Scheme | Bits | Sorted by time | Coordination | Watch out |
|---|---|---|---|---|
| Database sequence | 64 | Yes, nearly | Each ID, or each block | One place, shows your volume |
| Leased range | 64 | Only roughly | Once per block | Gaps after a crash |
| UUIDv4 | 128 | No | None | Scattered inserts |
| UUIDv7 or ULID | 128 | Yes, to a millisecond | None | Shows creation time |
| MongoDB ObjectId | 96 | To a second | None | Time, random part, counter |
| Snowflake | 64 | Yes, nearly | Machine number once | Clock, machine number |
Choosing
Trade-offs
What each choice costs
| Question | One side | Other side |
|---|---|---|
| Size | 64 bits: smaller keys in every index | 128 bits: more room, no machine numbers |
| Order | Time order: rows together, easy paging | Random: nothing to read from it, writes spread evenly |
| Coordination | Central: simple and dense | Independent: no call, more rules to keep |
Where do new rows land?
Security
An ID is a name, not a key
Sequential and Snowflake IDs can be guessed, and show volume or time. That is fine for most records if every request checks authorization. For a link that works without login, use at least 128 bits from a secure random source, and let it expire.
Operate
Do and do not
Do
- Lock around time and counter
- Choose an epoch near the launch
- Assign machine numbers at start, with a lease
- Watch clock offset and waits for the next millisecond
- Keep the unique constraint
Do not
- Trust the clock blindly
- Run two processes with one machine number
- Store number IDs as text
- Let clients depend on the parts of an ID
- Expect strict order between machines: see causal IDs
Summary
The whole topic in one minute.
Start with a sequence in the database. Move to leased ranges, UUIDv7 or Snowflake when one counter becomes a dependency you cannot accept.
A Snowflake ID is time, machine and counter. It stays unique only if two machines never share a number and a clock never repeats a moment. IDs are for naming things, never for keeping them secret.
- One database: a sequence. Many writers: ranges, UUIDv7 or Snowflake.
- Snowflake: 41 bits time, 10 bits machine, 12 bits counter, 69.7 years, 4,096 IDs per millisecond and machine.
- Two rules: machine numbers are never shared, time never repeats.
- Time-ordered IDs are nearly sorted across machines, not exactly.
- An ID is not a secret. Check access, and send 64-bit IDs as strings.