Every row, message, order and event needs an identifier. On one database an auto-increment column is enough, but in a distributed system thousands of machines must mint IDs at the same time without coordinating, without ever colliding, and ideally in roughly time-sorted order so indexes stay efficient. The main options are random UUIDs, database sequences and ticket servers, pre-allocated ranges, and time-based schemes such as Twitter's Snowflake.
Think of it like
Receipt numbers in a chain of stores
A single shop can number receipts 1, 2, 3. A chain with a thousand stores cannot share one counter without everyone phoning head office for every sale. Instead each receipt reads date and time, store number, then a till counter: 2026-10-30 14:02:07 / store 381 / #0042. No two stores can print the same receipt, nobody calls head office, and sorting receipts sorts them by time. That is a Snowflake ID.
Requirements
- Unique: never collide, across all machines and all time, including after restarts and failovers.
- Sortable: roughly ordered by creation time (k-sortable), so new rows append to the right edge of a B-tree index and "latest first" pagination is a range scan.
- Compact: 64 bits fits a
BIGINT, half the size of a 128-bit UUID in every index, foreign key and cache entry. - Fast and available: minted in-process in microseconds, with no network hop and no single point of failure.
- Sometimes: not guessable (public URLs), or containing routing information such as a shard ID.
UUIDs
A UUID is 128 bits, usually written as 36 hex characters with dashes. Version 4 fills 122 bits with random data (6 bits encode version and variant). Any machine can generate one with no coordination at all, and collisions are absurdly unlikely: you would need about 2.7 × 10¹⁸ of them for a 50% chance of a single collision, which is a billion UUIDs per second for about 86 years.
| Version | Contents | Sortable? | Notes |
|---|---|---|---|
| v1 | 60-bit timestamp + clock sequence + MAC address | No (timestamp bytes are out of order) | Leaks the machine's MAC address and creation time |
| v3 / v5 | MD5 / SHA-1 hash of a namespace + name | No | Deterministic: the same name always yields the same UUID |
| v4 | 122 random bits | No | The common default; terrible B-tree locality |
| v6 | v1 with timestamp bytes reordered | Yes | Mainly for migrating v1 systems |
| v7 | 48-bit Unix timestamp in ms + 74 random bits | Yes | Standardized in RFC 9562 (2024); the modern choice when you want UUIDs |
| unix_ts_ms (48) | ver=7 (4) | rand_a (12) | var (2) | rand_b (62) |
0190f3a2-7c41-7d3e-9b2a-41c6e88f0d17
\___________/ ^
timestamp version 7UUIDv7 keeps the coordination-free generation of v4 but puts the millisecond timestamp first, so IDs sort by creation time and index like a sequence. PostgreSQL 18 includes a built-in uuidv7() function and Python 3.14 added uuid.uuid7(). The remaining downsides are size (16 bytes) and that the creation time is visible to anyone who sees the ID.
Database auto-increment
A single database's AUTO_INCREMENT or SEQUENCE is the simplest generator: compact, strictly ordered, and free. It breaks down at scale because every insert depends on one primary (a bottleneck and single point of failure), and each shard of a sharded table would hand out the same numbers. Sequential public IDs also leak business volume: a competitor creating an order today and another next week learns how many orders you took in between.
Multi-master with offsets
With N database servers, give each a different starting offset and a step of N: with two servers, one produces 1, 3, 5, ... and the other 2, 4, 6, ... (MySQL's auto_increment_increment = 2 and auto_increment_offset = 1 or 2). IDs never collide, but adding a server means changing N everywhere, and IDs from different servers drift apart, so they are not ordered by time.
Ticket servers (Flickr)
Flickr (2010) ran dedicated MySQL "ticket servers" whose only job was handing out IDs. Each server holds one tiny table; REPLACE INTO bumps the auto-increment and LAST_INSERT_ID() returns it. Two ticket servers with odd and even offsets give redundancy. It is simple and produces compact numeric IDs, but every ID costs a network round trip and the ticket servers are critical infrastructure.
CREATE TABLE Tickets64 (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
stub CHAR(1) NOT NULL DEFAULT '',
PRIMARY KEY (id),
UNIQUE KEY stub (stub)
) ENGINE = InnoDB;
-- Server A: auto_increment_increment = 2, auto_increment_offset = 1 (odd IDs)
-- Server B: auto_increment_increment = 2, auto_increment_offset = 2 (even IDs)
REPLACE INTO Tickets64 (stub) VALUES ('a'); -- the table always has exactly one row
SELECT LAST_INSERT_ID();Range (segment) allocation
Instead of asking for one ID at a time, each application server grabs a block of IDs (say 1,000) with a single atomic update, then hands them out from memory. The database is hit once per thousand IDs. Meituan's Leaf adds double buffering: when 10% of the current block is used, it fetches the next block in the background, so callers never wait.
-- One row per ID sequence ("biz tag")
UPDATE id_alloc SET max_id = max_id + 1000 WHERE biz_tag = 'order';
SELECT max_id FROM id_alloc WHERE biz_tag = 'order';
-- Run both in one transaction. This server now owns (max_id - 1000, max_id].- Pros: compact 64-bit IDs, very fast, tolerant of short database outages (the buffer covers them).
- Cons: a crashed server's unused range is lost, leaving gaps; IDs from different servers interleave, so they are only roughly time-ordered.
Twitter Snowflake
Snowflake packs a timestamp, a machine ID and a per-millisecond counter into a signed 64-bit integer. Each machine generates IDs independently in memory, and IDs sort by time because the timestamp occupies the most significant bits. Step through the bit layout in the simulation above.
| Bits | Field | Range | Purpose |
|---|---|---|---|
| 1 | Sign | Always 0 | Keeps IDs positive in signed 64-bit types (Java long, SQL BIGINT) |
| 41 | Timestamp | 0 to 2⁴¹ − 1 ms | Milliseconds since a custom epoch (Twitter: 1288834974657, November 4, 2010) |
| 10 | Machine ID | 0 to 1,023 | Twitter split it into 5 bits of datacenter and 5 bits of worker |
| 12 | Sequence | 0 to 4,095 | Counter for IDs generated by this machine within the same millisecond |
Lifetime
~69.7 years
2⁴¹ ms from the custom epoch
Machines
1,024
2¹⁰ worker IDs
Per machine
4.096M /s
4,096 IDs per millisecond
Cluster max
~4.19B /s
1,024 × 4.096M
Worked example: with a timestamp offset of 1,000,000,000 ms (about 11.6 days after the epoch), machine 37 and sequence 5, the ID is 1,000,000,000 × 2²² + 37 × 2¹² + 5 = 4,194,304,000,151,557. Choosing a recent custom epoch instead of 1970 is what makes 41 bits last about 70 years from launch.
Sequence overflow
If one machine requests more than 4,096 IDs within the same millisecond, the sequence wraps to 0. The generator must then wait for the next millisecond before issuing more, otherwise it would repeat an ID. At 4 million IDs per second per machine this almost never happens, but the code must handle it.
Clock skew and clocks moving backwards
Snowflake trusts the wall clock. If NTP steps the clock back by 5 ms, the generator could reissue timestamps it has already used, and with the same machine ID and a reset sequence it would produce duplicate IDs. Every production implementation remembers the last timestamp it used and guards against going backwards.
- Refuse: throw an error (and alert) when
now < lastTimestamp. Twitter's original implementation did this. Safe, but fails requests during the skew. - Wait out small skews: if the clock is behind by a few milliseconds, sleep until it catches up; refuse only for larger jumps.
- Borrow from the future: keep using
lastTimestampand keep incrementing the sequence, as a logical clock would, until real time catches up. See Time, Clocks & Ordering. - Prevent it: configure NTP (chrony) to slew the clock gradually instead of stepping it, and monitor clock offset on every host.
- Check on startup: persist the last timestamp, or wait a short period after boot, so a restarted machine with a wrong clock cannot reuse recent timestamps.
ULID, KSUID and other variants
| Scheme | Size | Layout | Encoding |
|---|---|---|---|
| ULID | 128 bits | 48-bit ms timestamp + 80 random bits; monotonic mode increments the random part within a millisecond | 26 characters, Crockford base32, lexicographically sortable |
| KSUID (Segment) | 160 bits | 32-bit timestamp in seconds since a custom epoch (May 2014) + 128 random bits | 27 characters, base62 |
| MongoDB ObjectId | 96 bits | 32-bit timestamp in seconds + 5-byte per-process random value + 3-byte counter | 24 hex characters |
| Sonyflake | 63 bits | 39-bit time in 10 ms units + 8-bit sequence + 16-bit machine ID | Integer; longer lifetime (about 174 years), lower per-machine rate |
| 64 bits | 41-bit ms timestamp + 13-bit logical shard ID + 10-bit sequence | Integer; generated inside PostgreSQL. See Sharding & Partitioning | |
| Discord | 64 bits | Snowflake with a 2015 epoch | Integer, serialized as a string |
Comparison
| Approach | Size | Time-sortable | Coordination | Throughput | Main drawback |
|---|---|---|---|---|---|
| Single DB auto-increment | 64 bits | Yes (strict) | Every insert | Limited by one primary | Bottleneck and SPOF; does not work across shards |
| Multi-master offsets | 64 bits | No | Config only | Scales with servers | Changing server count is painful |
| Ticket server | 64 bits | Roughly | Network call per ID | Limited by ticket servers | Critical central dependency |
| Range allocation | 64 bits | Roughly | One call per block | Very high | Gaps on crash; not strictly ordered |
| UUID v4 | 128 bits | No | None | Unlimited | Large; random inserts hurt indexes |
| UUID v7 / ULID | 128 bits | Yes (ms) | None | Unlimited | Large; exposes creation time |
| Snowflake | 64 bits | Yes (k-sorted) | Worker ID at startup | 4M per second per machine | Depends on clocks and unique worker IDs |
- 1
Small or single-database system
Use the database sequence. Expose a separate random public ID if enumeration matters.
- 2
Need IDs before insert, any client can create them
Use UUIDv7 (or ULID): no infrastructure, sortable, good enough for most workloads.
- 3
Need compact 64-bit, time-sorted IDs at high scale
Use Snowflake with leased worker IDs and clock-skew protection.
- 4
Need dense numeric IDs from a legacy system
Use range allocation from a central table.
Implementation
41-bit timestamp, 10-bit worker ID, 12-bit sequence. Waits out sequence overflow and small backward clock jumps; refuses larger ones.
import threading
import time
class Snowflake:
EPOCH_MS = 1_288_834_974_657 # Twitter's epoch; choose your own
WORKER_BITS = 10
SEQUENCE_BITS = 12
MAX_WORKER = (1 << WORKER_BITS) - 1 # 1023
MAX_SEQUENCE = (1 << SEQUENCE_BITS) - 1 # 4095
TIMESTAMP_SHIFT = WORKER_BITS + SEQUENCE_BITS # 22
MAX_BACKWARD_MS = 5
def __init__(self, worker_id: int):
if not 0 <= worker_id <= self.MAX_WORKER:
raise ValueError(f"worker_id must be in [0, {self.MAX_WORKER}]")
self.worker_id = worker_id
self.last_ts = -1
self.sequence = 0
self.lock = threading.Lock()
@staticmethod
def _now_ms() -> int:
return time.time_ns() // 1_000_000
def _wait_until(self, target_ms: int) -> int:
ts = self._now_ms()
while ts < target_ms:
time.sleep((target_ms - ts) / 1000)
ts = self._now_ms()
return ts
def next_id(self) -> int:
with self.lock:
ts = self._now_ms()
if ts < self.last_ts: # clock moved backwards
drift = self.last_ts - ts
if drift > self.MAX_BACKWARD_MS:
raise RuntimeError(f"clock moved backwards by {drift} ms")
ts = self._wait_until(self.last_ts)
if ts == self.last_ts:
self.sequence = (self.sequence + 1) & self.MAX_SEQUENCE
if self.sequence == 0: # 4,096 IDs used this ms
ts = self._wait_until(self.last_ts + 1)
else:
self.sequence = 0
self.last_ts = ts
return (
((ts - self.EPOCH_MS) << self.TIMESTAMP_SHIFT)
| (self.worker_id << self.SEQUENCE_BITS)
| self.sequence
)
@classmethod
def decode(cls, id_: int) -> dict[str, int]:
return {
"timestamp_ms": (id_ >> cls.TIMESTAMP_SHIFT) + cls.EPOCH_MS,
"worker_id": (id_ >> cls.SEQUENCE_BITS) & cls.MAX_WORKER,
"sequence": id_ & cls.MAX_SEQUENCE,
}
gen = Snowflake(worker_id=7)
new_id = gen.next_id()
print(new_id, Snowflake.decode(new_id))Key takeaways
- Distributed IDs must be unique without coordination; ideally they are also 64-bit, time-sortable and fast to mint.
- UUIDv4 needs no infrastructure but is 128-bit and random, which hurts B-tree indexes; UUIDv7 and ULID fix the ordering.
- Auto-increment, multi-master offsets and ticket servers are simple but put a database on the ID path.
- Snowflake = 41-bit ms timestamp + 10-bit machine ID + 12-bit sequence: about 70 years, 1,024 machines, 4,096 IDs per ms each.
- Snowflake's safety rests on unique worker IDs and on never letting the clock go backwards.
- Snowflake IDs are k-sorted across machines, strictly increasing only within one machine.
Common pitfalls
- Using per-shard auto-increment IDs that collide when data is merged or moved.
- Assigning Snowflake worker IDs randomly or from IP addresses, so two processes share one.
- Ignoring backward clock jumps or sequence overflow, both of which produce duplicate IDs.
- Sending 64-bit IDs to JavaScript as JSON numbers, which silently rounds them above 2⁵³.
- Exposing sequential IDs publicly and leaking volumes or enabling enumeration of resources.
Interview tips
- Start from requirements (size, ordering, throughput, availability) before naming a scheme.
- Do the Snowflake math out loud: 2⁴¹ ms ≈ 69.7 years, 2¹⁰ machines, 2¹² IDs per ms.
- Explain how worker IDs are assigned and how you handle clock skew; this is where interviewers dig.
- Mention UUIDv7 as the modern zero-infrastructure option and why random UUIDs hurt indexes.
Real-world applications
- Primary keys for sharded databases (Instagram, Discord, Twitter/X).
- Message and event IDs in chat systems and event streams.
- Short-code generation in URL shorteners (ID + base62).
- Order, payment and trace IDs that encode creation time for debugging.
Test yourself
In the standard Snowflake layout, how many IDs can one machine generate per millisecond?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.