How to design a unique ID generator
The first sections are free. The deep dives, level expectations and quiz are part of Pro.
On this page
- The problem
- Clarifying questions
- The requirements menu
- Non-functional requirements
- Estimates
- Core entities
- The API
- The high-level design
- What breaks first
- The deep dives
- Entity fields
- Choosing the scheme
- Clocks that drift
- Spreading keys with consistent hashing
- Variants
- What each level is expected to show
- The 30-second answer
- Quiz
The problem
A unique id generator hands each service in the company a fresh 64-bit number that sorts roughly by the moment it was made, while machines in many data centers mint ids at the same instant without a call between them. The answer turns on packing the id with its own origin: a millisecond timestamp, which data center and which machine made it, and a short counter within that millisecond, so two machines produce different numbers without sharing anything. The rest of the round is what the machine clock does to that scheme, and how the ids spread across cache servers once they become keys.
Clarifying questions
| Ask | Why it matters | A typical answer |
|---|---|---|
How many ids a second, and from how many places? | The rate decides whether throughput matters at all, and the number of places decides how many bits the id must spend naming its maker. | About 10,000 a second in total, from up to 32 data centers with 32 machines each. |
Do the ids have to be numbers, and how large may they be? | A numeric 64-bit limit rules out UUIDs and anything that needs a string column, and it fixes the bit budget you'll split up later. | Numeric, and they must fit in 64 bits. |
Do ids have to grow by exactly one, or is sorting by time enough? | Dense sequential ids need a shared counter; roughly time-ordered ids can be made on each machine independently. | Sorting by creation time is enough. Gaps are fine, and ids from two machines made in the same instant may land in either order. |
May the generators talk to a central service for each id? | A round trip per id adds latency to each write in the company and puts one service in front of all of them. | No coordination per id. Assigning machine ids once at startup is acceptable. |
How long does the scheme have to keep working? | The lifetime comes out of the timestamp's bit width, and each bit you give the timestamp is one you take from the counter or the machine id. | 69 years from an epoch you pick. |
What are the ids used for downstream? | If they become cache keys, the question moves on to placing keys across servers so that adding one doesn't empty the cache. | They are keys on 10 cache servers, and the team adds servers from time to time. |
Non-functional requirements
| Requirement | What it forces |
|---|---|
10,000 ids a second | Spread over a second that's 10 ids a millisecond, and a 12-bit sequence allows 4,096 in one millisecond on a single machine, so throughput doesn't drive the design. Machines are added so generators sit next to their callers and so one machine's outage affects its own callers rather than the whole company, not for capacity. |
Up to 32 data centres with 32 machines each, with no coordination per id | Five bits for the data center and five for the machine go into the id itself, so uniqueness comes from the id carrying its origin, not from asking anyone. The one thing that is coordinated is handing out those two ids at startup, once per machine. |
The timestamp lasts 69 years from the chosen epoch | 41 bits of milliseconds. Count from a recent custom epoch, not from 1970, or decades of the range are spent before the first id. Say what happens at the end: a new epoch, or bits taken from the sequence and given to the timestamp. |
With 100 to 200 virtual nodes per server, a standard deviation of load of 5% to 10% | Each client of the cache holds a ring of 1,000 to 2,000 points for 10 servers, sorted so a lookup is a binary search. The spread figure describes a typical heavy server rather than the worst case, so provision each cache server with a margin above its average share of the keys. |
Estimates
| Quantity | Working | Result | What it sizes |
|---|---|---|---|
Ids one generator can make | 12 sequence bits: 2^12 = 4,096 ids in one millisecond; 4,096 × 1,000 ms = 4,096,000 ≈ 4 million a second; 4,096,000 ÷ 10,000 required ≈ 400 | About 4 million a second from one machine, about 400 times the whole company's demand | Why the fleet is not for throughput: one generator covers the load, and the others exist for locality and uptime. |
Ids needed per millisecond | 10,000 a second ÷ 1,000 ms = 10 a millisecond, against 4,096 available on one machine | About 10 a millisecond on average, so the sequence is exhausted by bursts far above the average, not by the average | How often a generator has to pause until the next millisecond tick: with about 10 a millisecond on average, a pause takes a burst hundreds of times the average inside one millisecond. |
Generators the id can name | 5 data center bits × 5 machine bits: 32 × 32 = 1,024 generators; 1,024 × 4 million ≈ 4 billion ids a second across the fleet | 1,024 distinct generators, with a fleet ceiling near 4 billion a second | How far the scheme can grow before the machine id bits run out, and why the machine id, not the rate, is the first limit. |
Timestamp lifetime | 2^41 ≈ 2.2 × 10^12 milliseconds; ÷ 1,000 ÷ 86,400 ÷ 365 ≈ 69.7 years; counted from the Unix epoch, 1970, the range would end around 1970 + 69 = 2039 | About 69 years from the chosen epoch | The epoch choice: counting from a recent date instead of 1970 keeps the full span ahead of you. |
Lifetime after moving two sequence bits to the timestamp | 43 timestamp bits = 4 × 2^41 → 4 × 69 ≈ 276 years; 10 sequence bits: 2^10 = 1,024 a millisecond × 1,000 ≈ 1 million a second, still about 100 times the 10,000 required | About 276 years of timestamps and about 1 million ids a second per machine | The answer for a service that makes few ids and must live long: trade sequence bits for years without touching the machine id bits. |
Keys that move when the eleventh cache server joins | Consistent hashing: about K/N = 1/11 ≈ 9% of keys move. Hash mod N: a key stays put when hash mod 10 equals hash mod 11, about 10 in 110 ≈ 9%, so about 91% move | About 9% of keys move on a ring, against about 91% under modulo placement | The cache miss rate right after a join: a dip of a tenth, or a near-total flush. |
Ring points to keep | 10 servers × 100 to 200 points per server = 1,000 to 2,000 points; with 11 servers, 1,100 to 2,200 | A sorted list of 1,000 to 2,000 entries per client | The ring metadata each cache client holds and refreshes when membership changes. |
Load on a heavy cache server | Average share with 10 servers = 10% of keys; with a 5% to 10% standard deviation, one sigma above the mean is 10% × 1.05 to 10% × 1.10 = 10.5% to 11% | A heavy server holds about 10.5% to 11% of the keys | A first cut at the headroom per cache server: one standard deviation above the mean is a typical heavy server, not the worst case, so provision with a margin above it. |
Core entities
| Entity | What it holds |
|---|---|
Id | One 64-bit integer whose bit fields say when it was made, where, and which number it was within that millisecond. |
Generator node | The process that mints ids: two ids it was given at startup and two values it keeps between calls. |
Hash ring | The placement of cache keys: each server appears many times on a circle of hash values, and a key belongs to the first server point clockwise from its hash. |
The API
| Endpoint | Notes |
|---|---|
| The main path. No network hop: the generator runs in the caller's process with its own data center and machine ids. It may block briefly when the sequence for the current millisecond is used up, and it should return an error rather than an id when the clock is behind the last timestamp it stamped. |
| A thin HTTP service wrapping one generator per instance, each instance with its own machine id. It costs a round trip and puts a shared box on those callers' write path, so run several behind a load balancer and keep the library the default. |
| A client-side call: hash the key, binary-search the sorted ring points for the first one at or past the hash, wrapping to the start, and return that point's server. Clients refresh the ring when membership changes. |
The high-level design
Step 1 of 5
A generator inside each service
Start with where ids are made. A service calls nextId() on a generator linked into its own process and gets a 64-bit id back, with no network hop and nothing shared with other services. The id is assembled from parts: the current millisecond, who made it, and a counter for ids made in the same millisecond. Running the generator inside each caller follows from the no-coordination requirement, and it means an id service outage somewhere else doesn't stop this service's writes.
What breaks first
The deep dives
Choosing the scheme. Two machines in different data centers each hand out an id at the same instant and don't talk to each other. How do you make sure the two ids differ, what does your scheme cost, and how many ids can one machine make?
Clocks that drift. A generator's clock gets pulled back a few milliseconds by a time sync while it is still issuing ids. What happens to the ids, and how closely do ids from two machines really sort by time?
Spreading keys with consistent hashing. The ids are keys on ten cache servers and an eleventh server joins. How do you place keys so that most of them stay where they were, and how even does the load across servers end up?
Concepts this guide uses
Sources
- TwitterAPI.io: Twitter Snowflake ID Explained
- twitter-archive/snowflake: README
- twitter-archive/snowflake: IdWorker.scala (original open-source branch)
- sony/sonyflake: README
- Flickr Engineering: Ticket Servers, Distributed Unique Primary Keys on the Cheap
- Sharding & IDs at Instagram (Instagram Engineering post, copy in a GitHub gist)
- Wikipedia: Universally unique identifier
- Wikipedia: Network Time Protocol
- Apache Cassandra documentation: Dynamo (consistent hashing and vnodes)
- ByteByteGo (Alex Xu): Design Consistent Hashing
- Last Minute Lecture: System Design Interview, Design Consistent Hashing overview
- AlgoMaster: Design Unique ID Generator