TExcelTAD
Home › System Design › Distributed IDs

Distributed IDs

Every order, message and photo needs a unique id. On one database, an auto-increment column is perfect. With many shards or services creating records at the same time, you need ids that are unique without coordination, and usually also compact (fit in 64 bits), roughly time-ordered (so newest-first queries and B-tree inserts stay efficient) and fast to generate.

Approach Size Sortable by time Coordination Notes
DB auto-increment 64 bit Yes Single DB is a bottleneck / SPOF Leaks business volume (/orders/1042)
Auto-increment with step (id % N = shard) 64 bit Roughly Fixed number of shards Hard to add shards
UUID v4 (random) 128 bit No None Random inserts fragment B-tree indexes
UUID v7 / ULID 128 bit Yes None Timestamp prefix + randomness
Snowflake 64 bit Yes Unique worker ids only Twitter's design; used widely
Ticket server / range allocation 64 bit Roughly A central allocator, called rarely Each node reserves blocks of 1,000 ids

Snowflake ids

Twitter's Snowflake packs three fields into a 64-bit integer:

text
 0 | 41 bits: milliseconds since a custom epoch | 10 bits: worker id | 12 bits: sequence
 ^ sign bit kept 0, so ids are positive
41 bits of ms   ~ 69 years of timestamps
10 bits         = 1,024 workers
12 bits         = 4,096 ids per worker per millisecond (~4 million per second per worker)

Because the timestamp is in the high bits, ids sort by creation time. The generator below uses a simulated clock so that the output is reproducible:

python · try it yourself
EPOCH_MS = 1_767_225_600_000          # 2026-01-01 00:00:00 UTC, our custom epoch

class Snowflake:
    def __init__(self, worker_id, clock):
        assert 0 <= worker_id < 1024
        self.worker_id, self.clock = worker_id, clock
        self.last_ms, self.sequence = -1, 0

    def next_id(self):
        now = self.clock()
        if now < self.last_ms:
            raise RuntimeError("clock moved backwards")
        if now == self.last_ms:
            self.sequence = (self.sequence + 1) & 0xFFF
            if self.sequence == 0:                       # 4,096 ids used this ms
                while now <= self.last_ms:               # wait for the next millisecond
                    now = self.clock()
        else:
            self.sequence = 0
        self.last_ms = now
        return ((now - EPOCH_MS) << 22) | (self.worker_id << 12) | self.sequence

def decode(snowflake_id):
    return {"ms_since_epoch": snowflake_id >> 22,
            "worker": (snowflake_id >> 12) & 0x3FF,
            "sequence": snowflake_id & 0xFFF}

ticks = iter([EPOCH_MS + 5_000, EPOCH_MS + 5_000, EPOCH_MS + 5_000, EPOCH_MS + 5_001])
gen = Snowflake(worker_id=7, clock=lambda: next(ticks))
ids = [gen.next_id() for _ in range(4)]
for i in ids:
    print(i, decode(i))
print("sorted by time:", ids == sorted(ids))
20971548672 {'ms_since_epoch': 5000, 'worker': 7, 'sequence': 0}
20971548673 {'ms_since_epoch': 5000, 'worker': 7, 'sequence': 1}
20971548674 {'ms_since_epoch': 5000, 'worker': 7, 'sequence': 2}
20975742976 {'ms_since_epoch': 5001, 'worker': 7, 'sequence': 0}
sorted by time: True

Many workers, no collisions

Two workers can generate ids in the same millisecond with no communication, because the worker bits differ. Merging their output and sorting by id gives (almost) creation order:

python · try it yourself
def make_id(ms, worker, seq):
    return (ms << 22) | (worker << 12) | seq

events = []   # (ms since epoch, worker, sequence, label)
for ms in [100, 101, 102]:
    for worker in [1, 2]:
        for seq in range(2):
            events.append((ms, worker, seq, f"w{worker}@{ms}ms#{seq}"))

ids = {make_id(ms, w, s): label for ms, w, s, label in events}
print("generated:", len(events), "unique:", len(ids))
for snowflake_id in sorted(ids)[:6]:
    print(f"{snowflake_id:>12}  {ids[snowflake_id]}")
generated: 12 unique: 12
   419434496  w1@100ms#0
   419434497  w1@100ms#1
   419438592  w2@100ms#0
   419438593  w2@100ms#1
   423628800  w1@101ms#0
   423628801  w1@101ms#1

Within the same millisecond, ids from worker 1 sort before worker 2, regardless of which was really first. Snowflake ids are k-sorted: ordered by time to within a millisecond (and within clock skew between machines), which is good enough for feeds and pagination but not for strict global ordering.

Pitfalls

  • Clock going backwards (NTP corrections): generators must refuse or wait, otherwise they may produce duplicates. The code above raises an error.
  • Worker id assignment: two processes with the same worker id will collide. Assign ids from a coordination service (ZooKeeper, etcd), from configuration, or from the pod's ordinal in a StatefulSet.
  • JavaScript precision: JS numbers are exact only up to 2^53, so 64-bit ids must be sent to browsers as strings.

UUIDs and index locality

Random UUIDs (v4) are trivially unique but scatter inserts across a B-tree index, so each insert touches a random page. Time-ordered ids append at the "right edge" of the index. A model counts how many distinct leaf pages the last 1,000 inserts touched:

python · try it yourself
import random
import uuid

rng = random.Random(42)
PAGE = 100                                       # keys per index leaf page

def pages_touched(keys):
    ordered = sorted(keys)
    position = {k: i for i, k in enumerate(ordered)}
    recent = keys[-1000:]
    return len({position[k] // PAGE for k in recent})

random_ids = [uuid.UUID(int=rng.getrandbits(128), version=4) for _ in range(50_000)]
time_ordered = list(range(50_000))               # what Snowflake / UUID v7 look like

print("UUID v4 inserts touched", pages_touched(random_ids), "of 500 leaf pages")
print("time-ordered ids touched", pages_touched(time_ordered), "of 500 leaf pages")
UUID v4 inserts touched 438 of 500 leaf pages
time-ordered ids touched 10 of 500 leaf pages

The random ids touched 438 of the 500 pages, so the whole index must stay in memory to insert quickly; the ordered ids touched only the last ten pages. That's why UUID v7 (a timestamp-prefixed UUID, standardised in RFC 9562) is replacing v4 as the default for database keys.

Test yourself

In a Snowflake id, why is the timestamp stored in the highest bits?

  1. To make ids shorter
  2. So that ids sort by creation time
  3. To hide the worker id
  4. Because it is the largest field

How many ids can one Snowflake worker generate per millisecond?

  1. 1,024
  2. 4,096
  3. 65,536
  4. Unlimited

What is the main database downside of random UUID v4 primary keys?

  1. They can collide often
  2. Inserts land on random index pages, hurting cache locality
  3. They can't be indexed
  4. They are only 32 bits