AlgoViz

Unique ID generator

medium 28 min

Give every record its own number, from many servers at once.

Video lesson · Chapter 1 of 5

An order number made from three fields

0:00 / 4:27

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

  1. 2005

    RFC 4122 standardises the 128-bit UUID, including version 4, which is mostly random bits.

  2. 2010

    Twitter announces Snowflake: 64-bit, roughly time-ordered IDs made by many machines without asking each other.

  3. 2024

    RFC 9562 replaces RFC 4122 and adds UUID version 7, which starts with the time in milliseconds.

  4. 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.

Step 1 of 3

Need. A record needs a number that nobody else will use

Understand it

Start here

The raffle

Tickets from several sellers
from 11

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

TrickHowWeakness
Odd and evenOne starts at 1, the other at 2, both add 2Adding a third database means a new plan
Shard number insidePut the shard number in some of the bitsNumber of shards has a limit
One ticket tableA small database only for numbersMust 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

Ask for the next block while some of the current one is left, so a short outage of the coordinator is not noticed.

How often do we ask?

3,500 IDs/s at peak1,000,000 per block=0.0035 calls/s≈1 call in 5 minutes\frac{3{,}500\ \text{IDs/s at peak}}{1{,}000{,}000\ \text{per block}} = 0.0035\ \text{calls/s} \approx 1\ \text{call in 5 minutes}
With one million numbers in a block, the coordinator is hardly used. Design a URL shortener uses this for its codes.

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?

p≈n22⋅2bn=1012, b=122:p≈9×10−14p \approx \frac{n^2}{2 \cdot 2^{b}} \qquad n = 10^{12},\ b = 122:\quad p \approx 9 \times 10^{-14}
A million million random UUIDs and still almost nothing. Only 64 random bits are another matter: a billion of them clash somewhere with about 2.7%. The estimate needs a good random source.

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

BitsPartRangeMeaning
1Unused0Keeps the number positive
41Timeabout 69.7 yearsMilliseconds since a chosen epoch
5Datacenter0 to 31Set when the server is deployed
5Machine0 to 31Given once, for example by ZooKeeper
12Counter0 to 4,095Starts again each millisecond
The first published version had one 10-bit machine number. Splitting it into 5 and 5 is a common choice. The epoch of the original is 4 November 2010.

How much can it make?

4,096×1,000=4.096 M IDs/s per machine32×32×4.096 M≈4.2 billion IDs/s4{,}096 \times 1{,}000 = 4.096\,\text{M IDs/s per machine} \qquad 32 \times 32 \times 4.096\,\text{M} \approx 4.2\,\text{billion IDs/s}
And 2412^{41} ms is 69.7 years. An epoch near your launch gives you all of them; with 1970 as epoch most are already used.

Making one ID

Python
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 ** 63
Putting the parts together and taking them apart again.
Edit and run it in your browser

Architecture

Inside the service, not beside it

Two instances, two machine numbers

Users call the order service, which runs as two instances. Each instance holds its own ID generator with a machine number, 7 and 8, leased from ZooKeeper when it starts. Both write orders to PostgreSQL, where the primary key refuses a duplicate. A time server outside our system sets their clocks.
ZooKeeper is asked once, at the start. The primary key is the last guard.

A library or a service?

ChoiceGoodCost
Library in each serverNo call, no extra systemEach process needs a machine number
ID serviceOne place to run and watchA network call for each ID, unless you ask for many at once
Default in the databaseSimplestThe 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. 1

    Clock moves back a little

    Wait until it passes the last used time. The original refused to make IDs until then.

  2. 2

    Clock moves back a lot

    Refuse, take the server out of service and alert. Waiting an hour helps nobody.

  3. 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. 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. 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?

p=1−e−k(k−1)2m=1−e−40×392×1024≈53%p = 1 - e^{-\frac{k(k-1)}{2m}} = 1 - e^{-\frac{40 \times 39}{2 \times 1024}} \approx 53\%
40 processes and 1,024 numbers: a shared number is more likely than not.

Choose

Which one?

Compared

SchemeBitsSorted by timeCoordinationWatch out
Database sequence64Yes, nearlyEach ID, or each blockOne place, shows your volume
Leased range64Only roughlyOnce per blockGaps after a crash
UUIDv4128NoNoneScattered inserts
UUIDv7 or ULID128Yes, to a millisecondNoneShows creation time
MongoDB ObjectId96To a secondNoneTime, random part, counter
Snowflake64Yes, nearlyMachine number onceClock, machine number

Choosing

Trade-offs

What each choice costs

QuestionOne sideOther side
Size64 bits: smaller keys in every index128 bits: more room, no machine numbers
OrderTime order: rows together, easy pagingRandom: nothing to read from it, writes spread evenly
CoordinationCentral: simple and denseIndependent: no call, more rules to keep
Time order keeps inserts together in one B-tree. In a store partitioned by key range, the same property sends all new rows to one partition: a hot spot. Put a hash first there.

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.

Sources