Unique ID Generation: UUIDs, Counters and Snowflake
Overview
Almost every table, message and file needs an identifier: a value that names exactly one thing. On a single database this is easy, because the database counts 1, 2, 3.... Once the data is spread over many machines that all create records at the same time, nobody can count in one place, and you must generate ids that never collide without asking a central server for each one.
This lesson compares the common approaches (database counters, UUIDs, ranges handed out in blocks, and the Snowflake layout), does the bit arithmetic, and explains the trade-offs interviewers probe: ordering, size, guessability and clock problems.
Detailed Notes
What is it?
A unique ID identifies one record. In distributed systems we want ids that are:
- Unique across all machines, without a per-id coordination step.
- Fast to generate (microseconds, no network call if possible).
- Compact: 64 bits is 8 bytes; 128 bits is 16 bytes. Ids are stored in every row and every index, so size multiplies.
- Sortable by time (often): a k-sortable id roughly increases over time, so "newest first" is just "highest id first", and inserts into a B-tree land near the end instead of random places.
- Not guessable (sometimes): if ids are
1, 2, 3, anyone can try/orders/1000and scrape everything.
Why do we need it?
Consider the naive approach: use the database's auto-increment (AUTO_INCREMENT, SERIAL).
- On one database it is perfect: unique, sorted, compact.
- It is a single writer: every insert needs the next number from one place, so it caps at that node's write rate (for example 5,000 inserts per second) and is a single point of failure.
- After sharding (splitting data over many databases), two shards would both produce id 1001. Ids collide across shards.
So we need a way for many generators to produce ids on their own that still never collide.
How does it work?
Option 1: UUID (128-bit random)
A UUID (universally unique identifier) is a 128-bit value written like 3f2b8c1e-9a47-4d1e-8a52-6c0e4f9b7d21. Version 4 fills 122 bits with random numbers. Any machine can make one with no coordination.
Space: 2^122 = about 5.3 x 10^36 possible values
Collision odds reach 50% only after about 2.7 x 10^18 ids (the birthday bound)
Generating 1 billion ids per second would take about 86 years to reach that
So collisions are not a practical concern. The real problems are different:
- Large: 16 bytes versus 8, doubled in every index and foreign key.
- Not sortable: random values mean inserts into a B-tree primary key land at random pages, causing page splits and poor cache use. Write performance drops noticeably at large table sizes.
- Unreadable and awkward in URLs.
UUID v7 (and similar ULID) fix the ordering problem by putting a millisecond timestamp in the high bits followed by random bits, so ids are roughly time-ordered.
Option 2: Database counters done smartly
- Ticket server. A dedicated small database whose only job is handing out numbers. Simple, ordered, but a single point of failure and a bottleneck. Mitigation: run two servers, one handing out odd numbers and one handing out even numbers.
- Range allocation. Each application server asks the counter for a block of ids, say 1,000, and then hands them out from memory. The central counter is hit only once per 1,000 ids, so 100,000 ids per second needs just 100 counter calls per second. A crashed server wastes its unused block, which is harmless with 64-bit space. The URL shortener's "counter range" idea is exactly this.
- Drawback. Ids are sequential and therefore guessable, and different servers' blocks interleave, so ids are only roughly time-ordered.
Option 3: Snowflake: pack time, machine and sequence into 64 bits
Twitter's Snowflake design builds each id from parts, so machines never need to talk to each other:
- sign1 bit
always 0, keeps it positive
- IDXtimestamp41 bits
ms since custom epoch: about 69.7 years
- UQmachine_id10 bits
1,024 generators (5 DC + 5 machine)
- sequence12 bits
4,096 ids per ms per machine
41 + 10 + 12 + 1 = 64 bits. Capacity: 4,096,000 ids per second per machine.
Read each row as one slice of the 64-bit number, from the most significant bit to the least.
- 1 bit sign, always 0, so the id stays a positive 64-bit integer.
- 41 bits of timestamp: milliseconds since a chosen custom epoch (a starting date such as 2024-01-01).
- 10 bits machine id (often 5 for data centre and 5 for machine). This gives 2^10 = 1,024 generators.
- 12 bits sequence number: a counter for ids created within the same millisecond on the same machine.
Total bits : 1 + 41 + 10 + 12 = 64
Lifetime : 2^41 ms = 2,199,023,255,552 ms
/ (1000 x 86,400 x 365 = 31,536,000,000 ms per year) = about 69.7 years
Per machine: 2^12 = 4,096 ids per millisecond = 4,096,000 ids per second
Whole fleet: 1,024 machines x 4.096 M = about 4.2 billion ids per second
How a machine makes an id: take the current time in ms, subtract the epoch, shift it left 22 bits (10 + 12), OR in its machine id shifted 12 bits, OR in the sequence. If it generates a second id in the same millisecond, it increments the sequence. If the sequence overflows (more than 4,096 in one ms), it waits for the next millisecond.
Properties: 8 bytes, unique with no coordination, increases over time, so sorting by id is sorting by creation time, and the timestamp can be extracted for debugging.
UUID v4
128-bit random
- 1
Generate 122 random bits
no coordination
- 2
Store 16 bytes
in every index
- 3
Insert at a random position
page splits
- Zero coordination
- Unguessable
- Large (16 bytes)
- Not time-ordered
Fine when order and size do not matter
Counter range
blocks from a counter
- 1
Server requests 1,000 ids
one call per block
- 2
Hand out from memory
very fast
- 3
Request a new block when empty
crash wastes a block
- Compact numbers
- Cheap and simple
- Central counter to protect
- Sequential, so guessable
Great for short keys such as URL shorteners
Snowflake
time + machine + sequence
- 1
Read the clock in ms
41 bits
- 2
Add machine id + sequence
10 + 12 bits
- 3
Return a 64-bit id
sorted by time
- 8 bytes, roughly time-ordered
- No call per id
- Depends on clocks
- Needs machine-id assignment
Default for high-volume sortable ids
Three common answers, judged on coordination, size and ordering.
Things that go wrong with Snowflake
- Clock going backwards. NTP (the protocol that synchronises clocks) may step a clock back by a few ms. The generator could reuse a timestamp and, with the same sequence, produce a duplicate. Fix: remember the last timestamp; if the clock is earlier, refuse to issue ids (or wait) until it catches up, and alert if the difference is large.
- Machine id assignment. Two machines must never share an id. Assign ids through a coordination service at startup (a registry with leases), or from a config assigned at deployment. This is the only coordination, and it happens once, not per id.
- Ordering is only approximate across machines. Machine A and B with clocks 5 ms apart can issue ids slightly out of true causal order. For "newest first" feeds that is fine; for strict ordering you need a different tool.
- Guessable. Ids reveal creation time and are increasing, so scrapers can enumerate them. Do not use them as an access-control secret.
Interview tip. Common mistakes: saying "just use UUID" and ignoring index locality and size, or proposing a single global counter without mentioning that it is a bottleneck and single point of failure. Also remember to state the bit budget; it shows you can reason about the limits.
Short, public-facing IDs
For URLs we often want short strings. Encode a number in base62 (a-z, A-Z, 0-9). A 64-bit id needs at most 11 characters (62^11 is about 5.2 x 10^19, above 2^64, about 1.8 x 10^19). For a URL shortener you do not need 64 bits: 62^7 is about 3.5 trillion, so a 7-character key from a counter range is enough. If keys must not be guessable, either generate them randomly, or scramble a counter with a reversible shuffle.
Real-world example
A messaging app stores 500 million messages per day across 64 database shards. Each message id is a Snowflake-style id generated by the chat server that received it: 41 bits of time, 10 bits for the server, 12 bits sequence. The client sorts a conversation by message id, which matches arrival order, and the database primary key stays compact (8 bytes) and append-friendly. A rare clock step-back on one server made it pause id generation for 3 ms until the clock caught up, and an alert recorded the event.
System design example
Design id generation for an order system that needs 20,000 orders per second, sorted newest first, with ids visible in URLs.
- Requirements: unique, time-sortable, 64-bit (fits a normal integer column), and not trivially enumerable by customers.
- Choice: Snowflake-style ids generated inside each order service instance: no network call, 4 million per second capacity per instance, so 20,000 per second is far below the limit.
- Machine ids: each instance claims one of 1,024 slots from a coordination service at boot using a lease.
- Customer-facing URL: do not expose the raw id. Either use a separate random public id (
ord_8Kx2...) mapped to the internal id, or sign the id. The internal id remains for sorting and joins. - Failure handling: refuse to issue ids if the clock moves backwards, and monitor the clock offset.
Interview discussion. Say: "A central counter becomes a bottleneck and single point of failure, and UUID v4 is large and unordered, hurting index locality. I'd use Snowflake-style 64-bit ids: timestamp in the high bits for ordering, a machine id and sequence for uniqueness, with no per-id coordination."
Trade-off thinking. Counters give perfect order but need coordination. UUIDs need none but are large and random. Snowflake gets both small size and rough order, at the price of depending on clocks and a machine-id registry.
Key interview takeaway
Choose by requirements: need only uniqueness and no ordering, use a UUID; need time ordering and compactness at scale, use Snowflake or UUID v7; need small readable numbers with light coordination, use range allocation. Quote the bit layout and its limits, and mention clock skew.
Real World Example
A messaging app generates a 64-bit Snowflake-style id on each chat server. Sorting a conversation by id gives arrival order, and one server paused id generation for 3 ms after a clock step-back instead of risking duplicates.
Common Interview Questions
Finished this lesson?
0 of 44 lessons done · 0% of the course

