Unique IDs
How to generate unique IDs across many machines, how auto-increment, UUIDs, Snowflake-style IDs and range allocation differ, and what interviewers ask.
On this page
A unique ID generator gives every record in a distributed system an identifier that no other record has ever had, even when many servers create records at the same time. The design choices are how the IDs are produced without the servers coordinating on every request, how large the ID is, whether IDs sort by creation time, and whether outsiders can guess them.
Without a plan for this, each database or server falls back on its own counter. Two shards then both create order 1001, and the first time their data is merged or joined, one record overwrites the other or the two get confused with each other.
Where ID generation sits
request and replyasynchronous message
The options below differ on three requirements: whether the ID must fit in 64 bits, whether sorting by ID should sort by creation time, and whether outsiders may guess IDs.
ID schemes
Database auto-increment
Each table has a counter that the database increments on every insert. The IDs are small, dense and strictly ordered, and no application code is needed. This is the right choice when there is one database and it will stay that way.
The counter lives in one database, so it does not work once the table is sharded. A common workaround is to give shard k of N the sequence k, k + N, k + 2N, ..., which keeps IDs unique across shards. The IDs no longer clash, but they are not in time order across shards, and adding a shard means changing the step on every existing shard.
Random UUID (version 4)
A version 4 UUID is 128 bits, of which 122 are random. Any machine, including a phone that is offline, can generate one with no coordination. With a good random number generator, a collision is so unlikely that it can be ignored.
It is a good choice when no ordering is needed and 16 bytes per key is acceptable, for example for IDs created on clients or for rows that are looked up only by ID. It has two costs. The ID is twice the size of a 64-bit integer and is repeated in every secondary index and foreign key, and because the values are random, inserts land at random positions in the primary key index, which slows down large tables (explained under index locality below).
Time-ordered IDs: UUID version 7 and ULID
These keep the no-coordination property of a random UUID but place a millisecond timestamp in the first 48 bits and fill the remaining bits with random data. UUID version 7 has the standard UUID format, so existing UUID columns and libraries accept it. A ULID has the same layout, with 80 random bits after the timestamp, and is usually written as a 26-character string that sorts correctly as text.
New IDs are larger than older ones, so inserts go to the end of the index, as they do with auto-increment. Pick these when 128 bits is acceptable and you want time ordering without any setup. Two limits apply. IDs created in the same millisecond are in random order unless the library implements a monotonic counter, and IDs from different machines are only as well ordered as the machines' clocks.
Snowflake-style 64-bit IDs
A Snowflake-style ID is a 64-bit integer split into fields. The timestamp is in the highest bits, so sorting the integers sorts them by time. The commonly used layout is one unused sign bit, 41 bits of milliseconds since an epoch you choose, 10 bits for the machine number and 12 bits for a per-millisecond sequence.
- The 41-bit timestamp counts milliseconds from your own epoch, such as your launch date. It overflows after about 70 years.
- The 10-bit machine number allows 1,024 generators to run at once. It must be unique among the generators that are running.
- The 12-bit sequence is a counter that restarts at 0 in every new millisecond. It allows 4,096 IDs per millisecond on each machine, about 4 million per second.
To build an ID, shift each field to its position and add them. With timestamp 1,000,000,000, machine 37 and sequence 5, the ID is 1,000,000,000 × 222 + 37 × 212 + 5 = 4,194,304,000,151,557.
Pick this scheme when IDs must be 64 bits and roughly time-ordered, as for messages, posts and orders at high volume. The costs are that every running generator needs its own machine number, and that correctness depends on the clock, both covered below.
- A
- 37
1Service A starts and claims machine number 37 from the coordination service. The claim is a lease that expires unless A keeps renewing it.
- timestamp
- 1,000,000,000
- machine
- 37
- sequence
- 5
2At millisecond 1,000,000,000, A creates its sixth ID of that millisecond, so the sequence is 5. The ID is 4,194,304,000,151,557.
- timestamp
- 1,000,000,000
- machine
- 38
- sequence
- 0
3In the same millisecond B creates its first ID, 4,194,304,000,155,648. The machine bits differ, so the two IDs cannot clash.
- last used
- 1,000,000,002
- clock now
- 999,999,999
4Time synchronisation moves A's clock back 3 ms. Using those milliseconds again could repeat an ID, so A refuses to create IDs until its clock passes the last timestamp it used.
- A
- stopped
- B
- 38
5A loses contact with the coordination service and its lease runs out. Machine number 37 may now be given to a new server, so A must stop. Two generators with the same number would produce the same IDs.
Ticket server and range allocation
A ticket server is a small database whose only job is to hand out numbers from a counter. Calling it for every ID would make it a bottleneck, so in practice each app server asks for a whole block, for example the next 1,000. The allocator records that 7,000 to 7,999 has been given out, and the server issues those numbers from memory. When the block is used up, the server asks for another. If a server crashes, the unused numbers in its block are skipped, which is harmless because IDs only have to be unique, not gap-free.
Pick this when you want compact, dense integers, such as the codes in a URL shortener, and when a short outage of the allocator is tolerable because each server still has a block in hand. The costs are that the allocator must be replicated, since if it is lost the counter is lost, and that IDs are ordered only within a block. Across servers they are not in creation order.
Clock, machine number, index and exposure problems
Clocks that move backwards
A time-based generator assumes that the clock never goes back. It can: time synchronisation can step the clock back a few milliseconds, and a restarted server can come up with a clock that is behind what it used before. If the generator then reuses a millisecond and its sequence starts again from 0, it creates an ID that already exists. The standard fix is to remember the last timestamp used and refuse to create IDs, or wait, until the clock passes it. A large jump should raise an alert instead of blocking for minutes.
Machine numbers that are not unique
Two running generators with the same machine number can create the same ID in the same millisecond. Machine numbers therefore need an owner. Common options are to take the number from a coordination service with a lease, as in the tracer, or to assign it at deploy time from a configuration that guarantees uniqueness. When the lease cannot be renewed, the generator must stop before the number can be given to someone else. With only 10 bits there is a limit of 1,024 generators, so numbers must be recycled when containers are short-lived.
Index locality
Most databases keep a primary key in a B-tree, a sorted tree of fixed-size pages. When new keys are always larger than existing ones, as with auto-increment, time-ordered UUIDs and Snowflake IDs, every insert goes to the last page, which stays in memory and fills up in order. When keys are random, as with UUID version 4, each insert goes to a random page. On a table too large for memory this means a disk read for almost every insert, and full pages split in half and leave the index larger and less dense.
Exposing sequential IDs
If an order ID in a URL is 10542, a user can try 10541 and 10543. That is only harmful when the server fails to check that the user may see those orders, so the first defence is an authorisation check on every request. Even with correct checks, sequential IDs reveal volume, because two orders placed a week apart show how many were placed in between. Time-based IDs have a similar leak, since the creation time can be read from the ID. When this matters, keep the internal ID for the database and give users a separate random public identifier, or encrypt the internal ID before showing it.
64-bit IDs in JavaScript
In the interview
Choose from the requirements in this order. Use auto-increment if there is one database. If there are several writers and you need 64-bit, time-sortable keys, use a Snowflake-style generator. If 128 bits is acceptable, use UUID version 7 for ordering or version 4 when order does not matter. Use range allocation for compact numeric codes. State the requirement that decided it, for example "unique across shards, 64 bits, roughly time-sorted".
Questions to expect:
- "How do you generate IDs when the table is sharded?" A per-shard counter produces clashes, so the ID has to be unique on its own. Use a Snowflake-style generator in each service when you need 64-bit, time-ordered IDs, or UUIDs if 128 bits is fine. Both avoid asking a central service on each insert.
- "Why not use random UUIDs as the primary key?" They are twice the size of a 64-bit key, and because they are random they spread inserts over the whole index. On a large table that causes constant page reads and splits. A time-ordered ID keeps inserts at the end of the index.
- "What happens if the clock goes backwards?" The generator could repeat a timestamp and create a duplicate. It records the last timestamp it used and waits or refuses until the clock passes it. A large jump should raise an alert instead of blocking.
- "Are the IDs in exact order?" Only roughly. IDs from one machine are ordered, but IDs from different machines depend on their clocks, and within one millisecond the machine bits decide. If exact order is required inside a conversation or an account, let one owner assign sequence numbers for it.
- "Why not use the current timestamp as the ID?" Two records created in the same millisecond, on one machine or on two, get the same value, so it is not unique. A Snowflake-style ID fixes this by adding a machine number and a per-millisecond sequence after the timestamp.
- "Is it a problem to put sequential IDs in URLs?" It lets people enumerate records and estimate your volume. Authorisation checks deal with the first, and a separate random public ID deals with both.
How do you assign message IDs?
Messages are written by many servers and shown in time order, so I'd use 64-bit Snowflake-style IDs. Each server leases a machine number from a coordination service when it starts, and then creates IDs locally with no network call.
Two messages in the same chat reach different servers in the same millisecond. Which one comes first?
The machine bits decide, so the order is arbitrary within that millisecond, and server clocks can differ by a few milliseconds anyway. That is acceptable for chat. If the exact order within a conversation mattered, I would have one owner per conversation assign sequence numbers.
What if a server's clock jumps backwards?
The generator remembers the last timestamp it used and waits until the clock passes it. For a large jump it stops and raises an alert.
A large table is written constantly, and its primary key is a random UUID. Inserts have become slow and the index is much larger than the data needs. What is the most likely cause, and what fixes it?
The IDs must be 64 bits, sorted roughly by time, and created by 200 servers without a call to a central service for each ID. Which scheme fits?
A Snowflake generator's clock is stepped back by 3 ms. What should the generator do?
What to practise next
Read Sharding and Partitioning to see why IDs must be unique across shards, and see range allocation in Design a URL Shortener and time-ordered IDs in Design a Chat App.