Skip to content

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
Practice this question

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

AskWhy it mattersA 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.

The requirements menu

RequirementScopeWhy

Each call returns a new id that no other call ever returns

Core

The whole point. A duplicate shows up later as a clash in some caller's table, so the scheme has to rule it out by construction rather than by checking.

Ids are numeric and fit in 64 bits

Core

A 64-bit integer fits a plain integer column and index, and Flickr's post gives index size as its reason for avoiding wider GUIDs. This is the line that rules out UUIDs.

Ids sort by creation time; they need not grow by exactly one

Core

Time-ordered keys land near each other in an index and let callers sort by id. Dropping the grow-by-one requirement is what allows generators to work without a shared counter.

Spread the keys these ids name across servers, so adding a server moves few keys

Core

The ids are cache keys, and a placement that remaps most keys when a server joins throws the cache away.

An HTTP endpoint for callers that don't link the library

Optional

Worth taking: it's in the API and costs one thin service in front of a generator. The trade is a network hop and a shared box for those callers, so push the library where you can.

Decode an id back into its timestamp, data center and machine

Optional

Cheap and useful for debugging, since the id already carries these parts. Take it if the interviewer asks what the id tells you; otherwise mention and move on.

Hand out machine ids automatically at startup instead of from a config file

Optional

A registry such as ZooKeeper, or a config file checked against the registry at startup, stops two machines booting with the same id. Worth naming as the fix for a duplicate-machine-id failure, not worth designing in the round.

A batch call that returns many ids at once

Optional

Tempting for bulk imports, but one generator already makes thousands per millisecond, so a loop over the library call is usually fine. Leave it unless asked.

Strict ordering of ids across data centers

Out of scope

Two machines with independent clocks are ordered to within their clock gap at best. Strict order would need coordination per id, which the requirements forbid. Say so, then stop.

Hiding the creation time and rate from anyone who sees an id

Out of scope

A time-ordered id reveals when it was made and, by counting, roughly how many were made. If that matters, the product wants random ids and gives up sorting. Name the trade and park it.

Ids that grow by exactly one

Out of scope

Listed as out of scope by the interviewer. It would force a single counter that all generators share.

Non-numeric ids

Out of scope

Listed as out of scope. Strings and UUIDs don't fit a 64-bit integer column.

Storing the ids, which callers do

Out of scope

Listed as out of scope. The generator hands out a number and forgets it; the caller's own table keeps it.

Non-functional requirements

RequirementWhat 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

QuantityWorkingResultWhat 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

EntityWhat 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

EndpointNotes

nextId() → 64-bit id, a library call inside each service

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.

GET /v1/ids → { id }, for callers without the library

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.

serverFor(key) → server, a lookup on the hash ring

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

nextIdCaller serviceGenerator64-bit id

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.

nextIdHTTPnextIdsyncsnowkeepshashclockwiseCaller serviceGeneratorId HTTP serviceNTPMachine clock64-bit idGenerator stateHash ringCache server
The whole design

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?

A concept that helps here: Unique ID generationA concept that helps here: Stating a trade-offA concept that helps here: Back-of-the-envelope estimation

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?

A concept that helps here: Clocks and orderingA concept that helps here: Unique ID generationA concept that helps here: Failing open or failing closed

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?

A concept that helps here: Consistent hashingA concept that helps here: Hot keys and hot partitionsA concept that helps here: Cache invalidation and TTLs

Concepts this guide uses

Sources

  1. TwitterAPI.io: Twitter Snowflake ID Explained
  2. twitter-archive/snowflake: README
  3. twitter-archive/snowflake: IdWorker.scala (original open-source branch)
  4. sony/sonyflake: README
  5. Flickr Engineering: Ticket Servers, Distributed Unique Primary Keys on the Cheap
  6. Sharding & IDs at Instagram (Instagram Engineering post, copy in a GitHub gist)
  7. Wikipedia: Universally unique identifier
  8. Wikipedia: Network Time Protocol
  9. Apache Cassandra documentation: Dynamo (consistent hashing and vnodes)
  10. ByteByteGo (Alex Xu): Design Consistent Hashing
  11. Last Minute Lecture: System Design Interview, Design Consistent Hashing overview
  12. AlgoMaster: Design Unique ID Generator
Sign in to report a mistake