Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 5 · Lab · 30 min · revision 1

Building a Snowflake-style generator

Build a 64-bit ID generator from a timestamp, a worker number and a sequence in standard-library Python, make it survive sequence overflow, a clock that steps backwards and a restart, see what two workers with the same number do, and prove uniqueness across four concurrent processes.

Contentsand lesson path

What you will learn

  • Implement a Snowflake-style generator that handles clock rollback and sequence overflow.

01. Goal and setup

You will build the last row of the comparison in the previous lesson: 64-bit IDs that sort roughly by time and need no network call, because each machine puts its own worker number inside every ID. The layout follows the one Twitter published in 2010 for Snowflake, now an archived repository; it does not describe how X generates IDs today.

You need Python 3.10 or newer; the lab was run with 3.10.12 and 3.12.13 on Linux. On Windows, use WSL or Git Bash, or save each python3 - <<'EOF' block as a .py file. Steps 3 to 7 use a fake clock that moves only when told to, so your IDs should match digit for digit.

02. Step 1: Check Python and create the folder

Terminal
python3 --version
mkdir snowflake-lab
cd snowflake-lab
Expected output (your version may be newer)
Python 3.12.13

03. Step 2: Plan the 64 bits and write the generator

Every ID is three numbers packed side by side, most significant first, so that IDs sort by time:

Bit layout
 bit 63 | bits 62 to 22               | bits 21 to 12  | bits 11 to 0
   0    | ms since 2026-01-01 (41)    | worker ID (10) | sequence (12)

id = (now_ms - EPOCH_MS) << 22  |  worker_id << 12  |  sequence
  • Bit 63 stays 0, so the ID is positive in a signed 64-bit column such as PostgreSQL bigint.
  • 41 bits of milliseconds hold about 69.7 years, counted from a custom epoch, 1 January 2026, so they last until September 2095. Counting from 1970 would waste 56 of those years.
  • 10 bits of worker ID allow 1,024 generators that never talk to each other, as long as no two share a number.
  • 12 bits of sequence allow 4,096 IDs per worker per millisecond.

Changing the split later changes the meaning of every stored ID. Save snowflake.py and fakeclock.py in snowflake-lab. Under a lock, so that threads can share one generator, next_id handles three cases:

  1. The clock went backwards. Up to max_wait_ms behind the last timestamp used, it waits; further behind, it raises ClockMovedBackwards.
  2. Same millisecond. The sequence goes up by one. After 4095 it waits for the next millisecond and restarts at 0.
  3. A new millisecond. The sequence restarts at 0.

Step 6 explains store; decode reverses the packing.

Python 3.12 · snowflake-lab/snowflake.py
"""A Snowflake-style 64-bit ID generator (standard library only).

Layout, most significant bit first:
  1 bit unused (0) | 41 bits ms since EPOCH_MS | 10 bits worker | 12 bits sequence
"""
import threading
import time

TIME_BITS, WORKER_BITS, SEQ_BITS = 41, 10, 12
MAX_TIME = (1 << TIME_BITS) - 1  # about 69.7 years of milliseconds
MAX_WORKER = (1 << WORKER_BITS) - 1  # 1023
MAX_SEQ = (1 << SEQ_BITS) - 1  # 4095
WORKER_SHIFT = SEQ_BITS  # 12
TIME_SHIFT = SEQ_BITS + WORKER_BITS  # 22
EPOCH_MS = 1_767_225_600_000  # custom epoch: 2026-01-01T00:00:00Z


class ClockMovedBackwards(RuntimeError):
    """The clock is further behind the last ID than we are willing to wait."""


def wall_clock_ms() -> int:
    return time.time_ns() // 1_000_000


class SnowflakeGenerator:
    def __init__(self, worker_id: int, *, epoch_ms: int = EPOCH_MS,
                 clock=wall_clock_ms, sleep=time.sleep, max_wait_ms: int = 5,
                 store=None, reserve_ms: int = 2_000):
        if not 0 <= worker_id <= MAX_WORKER:
            raise ValueError(f"worker_id must be 0..{MAX_WORKER}, got {worker_id}")
        self.worker_id = worker_id
        self.epoch_ms = epoch_ms
        self.clock = clock  # returns Unix time in ms; tests pass a fake
        self.sleep = sleep  # takes seconds, like time.sleep
        self.max_wait_ms = max_wait_ms  # longest backwards step we wait out
        self.last_ms = -1
        self.seq = 0
        self.lock = threading.Lock()  # one generator may serve many threads
        self.store = store  # stable storage for a time bound, or None
        self.reserve_ms = reserve_ms  # how far ahead each saved bound reaches
        self.bound = -1  # every ID handed out has a timestamp below this
        saved = store.load() if store is not None else None
        if saved is not None:  # a previous run left a bound behind
            self._resume(saved)

    def _resume(self, bound: int) -> None:
        """After a restart, never reuse a millisecond the last run may have used."""
        behind = bound - self.clock()
        if behind > self.reserve_ms + self.max_wait_ms:
            raise ClockMovedBackwards(
                f"clock is {behind} ms behind the saved bound; refusing")
        self._wait_for(bound)  # up to reserve_ms + max_wait_ms after a quick restart
        self.last_ms, self.seq = bound - 1, MAX_SEQ  # as if bound - 1 were full
        self.bound = bound

    def next_id(self) -> int:
        with self.lock:
            now = self.clock()
            if now < self.last_ms:  # the clock went backwards
                behind = self.last_ms - now
                if behind > self.max_wait_ms:
                    raise ClockMovedBackwards(
                        f"clock is {behind} ms behind the last ID; refusing")
                now = self._wait_for(self.last_ms)  # small step: wait it out
            if now == self.last_ms:
                if self.seq == MAX_SEQ:  # 4,096 IDs used in this millisecond
                    now = self._wait_for(self.last_ms + 1)
                    self.seq = 0
                else:
                    self.seq += 1
            else:
                self.seq = 0
            self.last_ms = now
            elapsed = now - self.epoch_ms
            if not 0 <= elapsed <= MAX_TIME:
                raise OverflowError("time is outside the 41-bit range of this epoch")
            if self.store is not None and now >= self.bound:
                self.store.save(now + self.reserve_ms)  # if this raises, no ID leaves
                self.bound = now + self.reserve_ms  # only after the save succeeded
            return (elapsed << TIME_SHIFT) | (self.worker_id << WORKER_SHIFT) | self.seq

    def _wait_for(self, target_ms: int) -> int:
        """Sleep until the clock reads at least target_ms; return that reading."""
        now = self.clock()
        while now < target_ms:
            self.sleep((target_ms - now) / 1000)
            now = self.clock()
        return now


def decode(id_: int, epoch_ms: int = EPOCH_MS) -> dict:
    return {
        "unix_ms": (id_ >> TIME_SHIFT) + epoch_ms,
        "worker": (id_ >> WORKER_SHIFT) & MAX_WORKER,
        "seq": id_ & MAX_SEQ,
    }
Python 3.12 · snowflake-lab/fakeclock.py
"""A clock you control, so every test and every output is exact."""


class FakeClock:
    def __init__(self, start_ms: int):
        self.now_ms = start_ms
        self.slept_ms = 0  # total time the generator spent waiting

    def __call__(self) -> int:  # used as the generator's clock
        return self.now_ms

    def sleep(self, seconds: float) -> None:  # used as the generator's sleep
        step = max(1, round(seconds * 1000))
        self.now_ms += step
        self.slept_ms += step
Terminal · snowflake-lab/ · check the shifts and limits
python3 -c "import snowflake as s; print(s.TIME_SHIFT, s.MAX_WORKER, s.MAX_SEQ)"
Expected output
22 1023 4095

04. Step 3: Make three IDs and take them apart

Worker 7 makes two IDs in one millisecond and a third in the next. The script prints each ID, its fields, and its 64 bits split into the four fields.

Terminal · snowflake-lab/
python3 - <<'EOF'
from fakeclock import FakeClock
from snowflake import SnowflakeGenerator, decode

clock = FakeClock(start_ms=1_794_906_000_000)  # 2026-11-17T09:00:00Z
gen = SnowflakeGenerator(worker_id=7, clock=clock, sleep=clock.sleep)
ids = [gen.next_id(), gen.next_id()]
clock.now_ms += 1  # one millisecond later
ids.append(gen.next_id())
for i in ids:
    bits = f"{i:064b}"
    print(i, decode(i))
    print("   ", bits[0], bits[1:42], bits[42:52], bits[52:])
EOF
Expected output
116100012441628672 {'unix_ms': 1794906000000, 'worker': 7, 'seq': 0}
    0 00000011001110001111000010110001010000000 0000000111 000000000000
116100012441628673 {'unix_ms': 1794906000000, 'worker': 7, 'seq': 1}
    0 00000011001110001111000010110001010000000 0000000111 000000000001
116100012445822976 {'unix_ms': 1794906000001, 'worker': 7, 'seq': 0}
    0 00000011001110001111000010110001010000001 0000000111 000000000000

The first two IDs differ only in the sequence. The third is larger than the first by 4,194,304, or 2^22, because 22 bits sit below the timestamp field.

05. Step 4: Overflow the sequence

Ask for 4,097 IDs while the fake clock stays on one millisecond. Python rarely reaches this rate, but faster languages do.

Terminal · snowflake-lab/
python3 - <<'EOF'
from fakeclock import FakeClock
from snowflake import SnowflakeGenerator, decode

clock = FakeClock(start_ms=1_794_906_000_000)
gen = SnowflakeGenerator(worker_id=7, clock=clock, sleep=clock.sleep)
ids = [gen.next_id() for _ in range(4_097)]  # the fake clock never moves by itself
for n in (1, 4_096, 4_097):
    print(f"ID number {n:>5,}:", decode(ids[n - 1]))
print("waited:", clock.slept_ms, "ms")
print("unique:", len(set(ids)) == len(ids), "| increasing:", ids == sorted(ids))
EOF
Expected output
ID number     1: {'unix_ms': 1794906000000, 'worker': 7, 'seq': 0}
ID number 4,096: {'unix_ms': 1794906000000, 'worker': 7, 'seq': 4095}
ID number 4,097: {'unix_ms': 1794906000001, 'worker': 7, 'seq': 0}
waited: 1 ms
unique: True | increasing: True

The 4,097th ID did not wrap to sequence 0 in the same millisecond, which would repeat ID number 1; the generator slept until the next millisecond. RFC 9562 gives the same rule for UUID counters: stall or return an error, but never knowingly return a duplicate after a rollover.

06. Step 5: Move the clock backwards

Wall clocks do go backwards: someone sets the time by hand, a virtual machine is restored from a snapshot, or the time sync daemon steps the clock. chrony corrects small errors gradually, but its makestep setting steps the clock when the error is large, typically at boot. This script steps the fake clock back by 4 ms and then by 250 ms:

Terminal · snowflake-lab/
python3 - <<'EOF'
from fakeclock import FakeClock
from snowflake import ClockMovedBackwards, SnowflakeGenerator, decode

clock = FakeClock(start_ms=1_794_906_000_000)
gen = SnowflakeGenerator(worker_id=7, clock=clock, sleep=clock.sleep, max_wait_ms=5)
first = gen.next_id()
clock.now_ms -= 4  # time sync steps the clock back 4 ms
second = gen.next_id()
print("4 ms back: waited", clock.slept_ms, "ms;", decode(second), second > first)
clock.now_ms -= 250  # a 250 ms step is too long to wait out
try:
    gen.next_id()
except ClockMovedBackwards as err:
    print("250 ms back:", err)
EOF
Expected output
4 ms back: waited 4 ms; {'unix_ms': 1794906000000, 'worker': 7, 'seq': 1} True
250 ms back: clock is 250 ms behind the last ID; refusing

For the small step, the generator waited 4 ms and continued its sequence. For the large step it refused, as the 2010 Snowflake README also describes: waiting 250 ms would stall every request and hide the fault, so callers retry on another worker and the error raises an alert. Without the check, old timestamps would be reused with sequences restarting at 0, recreating old IDs.

07. Step 6: Survive a restart

last_ms lives in memory, so a restarted process forgets which milliseconds it used, and clock steps often happen around restarts. The defence is a bound in stable storage that is always ahead of every timestamp handed out. Before it hands out an ID whose timestamp has reached the saved bound, next_id saves a new bound reserve_ms later (2 seconds here). The order matters: save first, and move the bound in memory only after the save succeeded; if the save fails, no ID leaves and the next call saves again. On start-up, the constructor waits until the clock reaches the saved bound, or refuses if the clock is more than reserve_ms plus max_wait_ms behind it. RFC 9562 Section 6.3 describes the same idea for time-based UUIDs: a stored timestamp larger than any yet used. Save store.py:

Python 3.12 · snowflake-lab/store.py
"""Stable storage for the generator's time bound: one integer."""
import os


class FileStore:
    """Keeps the bound in a file. save() returns only once the new value is on
    disk; a crash during save() leaves the old value, which is still safe because
    no ID at or above it has been handed out yet."""

    def __init__(self, path: str):
        self.path = path

    def load(self) -> int | None:
        try:
            with open(self.path) as f:
                return int(f.read())
        except FileNotFoundError:
            return None

    def save(self, value: int) -> None:
        tmp = self.path + ".tmp"
        with open(tmp, "w") as f:
            f.write(str(value))
            f.flush()
            os.fsync(f.fileno())  # the new value's bytes are on disk
        os.replace(tmp, self.path)  # readers see the old file or the new one
        if os.name == "posix":  # make the rename itself survive a power cut
            folder = os.open(os.path.dirname(os.path.abspath(self.path)), os.O_RDONLY)
            try:
                os.fsync(folder)
            finally:
                os.close(folder)


class MemoryStore:
    """The same interface in memory, for tests and demos."""

    def __init__(self, value: int | None = None):
        self.value = value

    def load(self) -> int | None:
        return self.value

    def save(self, value: int) -> None:
        self.value = value

Worker 7 runs for 4 seconds and "crashes" just before its next save. It restarts with the clock 1.5 s behind, once from the saved bound and once from a lagging mark: the highest timestamp used, saved every 2 seconds. Last, the clock is 2.5 s behind.

Terminal · snowflake-lab/
python3 - <<'EOF'
import os
from fakeclock import FakeClock
from snowflake import ClockMovedBackwards, SnowflakeGenerator
from store import FileStore, MemoryStore

T0 = 1_794_906_000_000  # 2026-11-17T09:00:00Z
if os.path.exists("bound.txt"):
    os.remove("bound.txt")  # start each run with an empty disk


def start(store, clock):  # a new process: empty memory, same disk
    return SnowflakeGenerator(7, clock=clock, sleep=clock.sleep,
                              store=store, reserve_ms=2_000)


clock, disk = FakeClock(T0), FileStore("bound.txt")
gen, old = start(disk, clock), set()
for _ in range(4_000):  # one ID per ms for 4 s; the next ID would save again
    old.add(gen.next_id())
    clock.now_ms += 1
print("crash at start + 4000 ms; bound on disk: start +", disk.load() - T0, "ms")

for name, saved in (("reserved bound", disk.load()), ("lagging mark", T0 + 2_000)):
    clock = FakeClock(T0 + 2_500)  # restart with the clock stepped back 1.5 s
    gen = start(MemoryStore(saved), clock)
    repeats = 0
    for _ in range(1_500):
        repeats += gen.next_id() in old
        clock.now_ms += 1
    print(f"{name}: waited {clock.slept_ms} ms, old IDs issued again: {repeats}")

try:  # restart with the clock stepped back 2.5 s
    start(disk, FakeClock(T0 + 1_500))
except ClockMovedBackwards as err:
    print("clock 2500 ms behind:", err)
EOF
Expected output
crash at start + 4000 ms; bound on disk: start + 4000 ms
reserved bound: waited 1500 ms, old IDs issued again: 0
lagging mark: waited 0 ms, old IDs issued again: 1500
clock 2500 ms behind: clock is 2500 ms behind the saved bound; refusing

From the saved bound, the restarted generator waited 1.5 s and repeated nothing. From the lagging mark, it started at once and issued 1,500 old IDs again, because the last 2 seconds before the crash were never recorded. With the clock 2.5 s behind, it refused to start. Because refusal is measured from the saved bound, right after a save even a step slightly larger than max_wait_ms is refused. Safety costs one durable write per reserve_ms and a start-up wait of up to reserve_ms plus max_wait_ms.

08. Step 7: Give two workers the same number

Now break the rule of one generator per worker ID: pod-a and pod-b both run as worker 7, pod-b's clock 3 ms ahead, and pod-c runs as worker 8. Each makes 10 IDs per millisecond for 100 ms:

Terminal · snowflake-lab/
python3 - <<'EOF'
from fakeclock import FakeClock
from snowflake import SnowflakeGenerator

clock_a = FakeClock(start_ms=1_794_906_000_000)
clock_b = FakeClock(start_ms=1_794_906_000_003)  # pod-b's clock runs 3 ms ahead
pod_a = SnowflakeGenerator(worker_id=7, clock=clock_a, sleep=clock_a.sleep)
pod_b = SnowflakeGenerator(worker_id=7, clock=clock_b, sleep=clock_b.sleep)  # copied
pod_c = SnowflakeGenerator(worker_id=8, clock=clock_a, sleep=clock_a.sleep)
a, b, c = set(), set(), set()
for _ in range(100):  # 100 milliseconds, 10 IDs per pod in each
    for _ in range(10):
        a.add(pod_a.next_id())
        b.add(pod_b.next_id())
        c.add(pod_c.next_id())
    clock_a.now_ms += 1
    clock_b.now_ms += 1
print(f"pod-a and pod-b (both worker 7) share {len(a & b):,} of {len(a):,} IDs")
print(f"pod-a and pod-c (workers 7 and 8) share {len(a & c):,} of {len(a):,} IDs")
EOF
Expected output
pod-a and pod-b (both worker 7) share 970 of 1,000 IDs
pod-a and pod-c (workers 7 and 8) share 0 of 1,000 IDs

The clock offset did not protect pod-a and pod-b: pod-a reached each millisecond 3 ms after pod-b had used it, with the same worker and sequence numbers, so 970 of 1,000 IDs collided without any error. So the real design work is assigning worker IDs, and each common way has a failure mode:

  • Static configuration, one number per host. A copied config file or a cloned machine silently shares a number.
  • A stable identity from the platform. A Kubernetes StatefulSet gives each pod an ordinal, 0 to N − 1, and aims to run at most one pod per identity; its documentation warns that force-deleting a pod can break that. Separate clusters or regions also need separate ranges.
  • A lease. A worker claims a free number with an expiry from a coordination service or a database table, and renews it. A process paused past its lease, for example by garbage collection, may still use a number someone else has claimed, so it must stop issuing before the lease can expire (see Distributed systems fundamentals).

A unique primary key is the loud last line of defence: it turns a duplicate into an insert error.

09. Step 8: Turn the checks into tests

Save test_snowflake.py. With a fake clock the suite takes well under a second. One test runs four generators in bursts of 5,000 IDs per millisecond; three cover restarts and a failed save.

Python 3.12 · snowflake-lab/test_snowflake.py
"""Unit tests for snowflake.py. A fake clock makes every case exact and instant."""
import unittest

from fakeclock import FakeClock
from snowflake import (EPOCH_MS, MAX_SEQ, ClockMovedBackwards, SnowflakeGenerator,
                       decode)
from store import MemoryStore

START = 1_794_906_000_000  # 2026-11-17T09:00:00Z


def make(worker_id=7, start=START, clock=None, **kwargs):
    clock = clock or FakeClock(start)
    gen = SnowflakeGenerator(worker_id, clock=clock, sleep=clock.sleep, **kwargs)
    return gen, clock


class SnowflakeTests(unittest.TestCase):
    def test_fields_round_trip(self):
        gen, _ = make(worker_id=1023)
        self.assertEqual(decode(gen.next_id()),
                         {"unix_ms": START, "worker": 1023, "seq": 0})

    def test_ids_fit_in_a_signed_64_bit_column(self):
        gen, clock = make()
        clock.now_ms = EPOCH_MS + (1 << 41) - 1  # the last millisecond of the epoch
        self.assertLess(gen.next_id(), 2**63)

    def test_sequence_overflow_waits_for_the_next_millisecond(self):
        gen, clock = make()
        ids = [gen.next_id() for _ in range(MAX_SEQ + 2)]
        self.assertEqual(decode(ids[-1]), {"unix_ms": START + 1, "worker": 7, "seq": 0})
        self.assertEqual(clock.slept_ms, 1)
        self.assertEqual(ids, sorted(set(ids)))  # unique and increasing

    def test_small_backward_step_is_waited_out(self):
        gen, clock = make(max_wait_ms=5)
        first = gen.next_id()
        clock.now_ms -= 4
        self.assertGreater(gen.next_id(), first)
        self.assertEqual(clock.slept_ms, 4)

    def test_large_backward_step_is_refused(self):
        gen, clock = make(max_wait_ms=5)
        gen.next_id()
        clock.now_ms -= 250
        with self.assertRaises(ClockMovedBackwards):
            gen.next_id()

    def test_bad_worker_ids_and_times_are_rejected(self):
        with self.assertRaises(ValueError):
            make(worker_id=1024)
        gen, _ = make(start=EPOCH_MS - 1)  # a clock set before the custom epoch
        with self.assertRaises(OverflowError):
            gen.next_id()

    def test_four_workers_unique_and_each_increasing(self):
        clock = FakeClock(START)
        gens = [SnowflakeGenerator(w, clock=clock, sleep=clock.sleep) for w in range(4)]
        streams = {w: [] for w in range(4)}
        for step in range(20_000):  # bursts of up to 5,000 IDs in one millisecond
            for w, gen in enumerate(gens):
                streams[w].append(gen.next_id())
            if step % 5_000 == 4_999:
                clock.now_ms += 1
        all_ids = [i for ids in streams.values() for i in ids]
        self.assertEqual(len(set(all_ids)), len(all_ids))
        for ids in streams.values():
            self.assertTrue(all(a < b for a, b in zip(ids, ids[1:])))

    def test_restart_after_crash_before_a_save_repeats_nothing(self):
        disk = MemoryStore()
        gen, clock = make(store=disk, reserve_ms=2_000)
        before = []
        for _ in range(4_000):  # the next ID would have saved a new bound
            before.append(gen.next_id())
            clock.now_ms += 1
        clock.now_ms -= 1_500  # crash; the clock is 1.5 s behind on restart
        restarted, _ = make(clock=clock, store=disk, reserve_ms=2_000)
        after = [restarted.next_id() for _ in range(2_000)]
        self.assertGreater(min(after), max(before))
        self.assertEqual(clock.slept_ms, 1_500)

    def test_failed_save_hands_out_nothing_beyond_the_saved_bound(self):
        class FlakyStore(MemoryStore):  # the first save after the first one fails
            saves = 0

            def save(self, value):
                self.saves += 1
                if self.saves == 2:
                    raise OSError("disk full")
                super().save(value)

        disk = FlakyStore()
        gen, clock = make(store=disk, reserve_ms=2_000)
        gen.next_id()
        clock.now_ms += 2_000  # this ID needs a new bound, and saving it fails
        with self.assertRaises(OSError):
            gen.next_id()
        ids = [gen.next_id() for _ in range(3)]  # the caller retries: save again
        self.assertEqual(disk.load(), START + 4_000)
        self.assertTrue(all(decode(i)["unix_ms"] < disk.load() for i in ids))

    def test_restart_far_behind_the_saved_bound_is_refused(self):
        disk = MemoryStore(START + 4_000)
        with self.assertRaises(ClockMovedBackwards):
            make(start=START + 1_500, store=disk, reserve_ms=2_000)


if __name__ == "__main__":
    unittest.main()
Terminal · snowflake-lab/
python3 -m unittest test_snowflake
Illustrative output (the run time on the "Ran" line varies)
..........
----------------------------------------------------------------------
Ran 10 tests in 0.125s

OK

10. Step 9: Four workers at once on the real clock

Now run four processes, each with its own worker ID and the real clock, at full speed. check_unique.py keeps each worker's IDs in a compact array. Each list must strictly increase (a worker never repeats itself), and every ID must carry its own worker's bits (workers cannot produce each other's values). It then merges the sorted lists with heapq.merge and counts equal neighbours, a direct check using almost no extra memory.

Python 3.12 · snowflake-lab/check_unique.py
"""Generate IDs in several processes at once on the real clock and prove uniqueness.

Usage: python3 check_unique.py [ids_per_worker] [workers]
"""
import heapq
import sys
from array import array
from concurrent.futures import ProcessPoolExecutor

from snowflake import SnowflakeGenerator, decode


def run_worker(worker_id: int, count: int) -> array:
    gen = SnowflakeGenerator(worker_id)  # real clock, real sleep
    ids = array("q")  # 8 bytes per ID instead of a Python int object
    for _ in range(count):
        ids.append(gen.next_id())
    return ids


def main() -> None:
    per_worker = int(sys.argv[1]) if len(sys.argv) > 1 else 250_000
    workers = int(sys.argv[2]) if len(sys.argv) > 2 else 4
    with ProcessPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(run_worker, w, per_worker) for w in range(workers)]
        streams = [f.result() for f in futures]

    total = sum(len(s) for s in streams)
    print(f"{workers} workers x {per_worker:,} IDs = {total:,} IDs")
    increasing = all(all(a < b for a, b in zip(s, s[1:])) for s in streams)
    print("each worker strictly increasing:", increasing)
    own_bits = all(decode(i)["worker"] == w for w, s in enumerate(streams) for i in s)
    print("worker bits match the worker:", own_bits)
    # Each stream is sorted, so a k-way merge visits all IDs in order using
    # almost no extra memory; equal neighbours would be duplicates.
    duplicates, previous = 0, None
    for i in heapq.merge(*streams):
        duplicates += i == previous
        previous = i
    print("duplicates across all workers:", duplicates)
    in_range = all(0 < i < 2**63 for s in streams for i in s)
    print("all IDs positive and below 2**63:", in_range)


if __name__ == "__main__":
    main()
Terminal · snowflake-lab/
python3 check_unique.py
Expected output (takes a few seconds)
4 workers x 250,000 IDs = 1,000,000 IDs
each worker strictly increasing: True
worker bits match the worker: True
duplicates across all workers: 0
all IDs positive and below 2**63: True

The IDs differ on every run; the check results do not. Keep the __main__ guard: on macOS and Windows each worker process imports the script again.

11. Check your understanding

Practice check · 3 questions

Reasoning about your generator

Three questions about the generator you built and its failure modes.

Q1. By mistake, two pods run as worker 12. Pod B's clock is 40 ms ahead of pod A's, and both issue a few hundred IDs in every millisecond, all day. What happens?
Q2. A teammate copies your generator but sets the custom epoch to 0, the Unix epoch, and keeps 41 timestamp bits. What changes for the IDs it makes in 2026?
Q3. You must show that 10 million IDs from four worker processes, with worker IDs 0 to 3, contain no duplicates, without keeping a set of 10 million IDs. Which checks together are enough?
Practice only: not graded, not saved, not evidence.

12. Apply it

Finish this skill's practice task with the code you now have:

  1. Run python3 check_unique.py 2500000: 10 million IDs across four concurrent workers. On an 8-core Linux desktop with Python 3.12 it took about 13 seconds and 150 MB of memory; yours will differ.
  2. Give each worker its own FileStore, such as bound-{worker_id}.txt. Restart one with a FakeClock 1,000 ms before its saved bound: it waits 1,000 ms. At 2,500 ms before, it refuses.
  3. Write a short CLOCK.md: what the generator does when the clock moves back by less and by more than max_wait_ms, what happens after a restart, and your values for max_wait_ms and reserve_ms.
  4. Choose a worker ID assignment for your own deployment and list how it could hand out the same number twice.

13. Review prompt

Without looking at your code: draw the 64-bit layout and explain each width. What must a generator do after sequence 4095? What are the two answers to a clock that moved backwards, and when is each right? Why must the saved bound be ahead of the IDs handed out? Name two ways to assign worker IDs and how each can fail.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check