Sub topic 10
Giving every generator a unique worker ID
This chapter assumes you have read the Snowflake chapter. You should know the layout of a 64-bit Snowflake ID: a 41-bit timestamp, a 10-bit worker ID, and a 12-bit sequence. You should also be comfortable with leases and timeouts at a basic level. The question here is how each generator gets a worker ID that no other live generator has.
Why the worker ID carries the uniqueness guarantee
A Snowflake generator needs no network call to issue an ID. Two generators can only avoid each other because their worker IDs differ. The timestamp and sequence fields are the same kind of value on every machine. If two generators share a worker ID, nothing else in the ID separates them.
Suppose workers A and B both believe they are worker 7. Each issues sequence 0 in the same millisecond. Both produce the same 64-bit integer, and neither knows. The collision is silent. You find it later as a primary key violation, or worse, as two records overwriting each other in a store that accepts upserts.
The guarantee therefore has a precise form: at any moment, at most one live generator holds a given worker ID, and a reused worker ID never produces a timestamp earlier than its previous holder did. The second half of that sentence is easy to forget. We return to it in the section on reuse.
Assignment strategies
There are five common ways to hand out worker IDs.
| Strategy | How it works | Main risk |
|---|---|---|
| Static configuration | An operator writes a unique ID into each deployment's config | Copy-paste errors; cloned images keep the same ID |
| Derived from the environment | Hash of IP address, MAC address, or hostname, truncated to 10 bits | Hash collisions; reused IPs; containers on the same host |
| Orchestrator ordinal | A Kubernetes StatefulSet pod `app-3` uses ID 3 | Works only if you never run two sets with the same ID range |
| Lease from a coordination service | A generator claims a free ID in etcd, ZooKeeper, or a database table, and renews it | Needs a reachable service at startup; lease logic must be correct |
| Random choice | Pick a random 10-bit number | Birthday collisions happen with few workers |
Static configuration is fine for a small, stable fleet. It stops working when machines are created by autoscaling, because no human is available to edit a file.
Deriving the ID from the environment looks attractive, but 10 bits is small. Among only 40 workers choosing random 10-bit values, the chance that two match is about 1 − e^(−40·39/2048), roughly 53%. Hashing a hostname behaves the same way. A truncated hash is not an assignment, only a guess.
The StatefulSet ordinal is stable and unique within one set, so it is a good fit for that case. Stateless deployments get random pod names and no ordinals.
The lease approach is the most general, and the rest of this chapter focuses on it.
Leases: claiming an ID for a limited time
A lease is a claim that expires unless the holder renews it. When a generator starts, it asks the registry for any worker ID that is not currently leased. While it runs, it renews the lease on a schedule shorter than the lease length. If the process crashes, it stops renewing, and the lease expires on its own. Nobody has to detect the crash.
Two details make this safe, and both are easy to get wrong.
- The holder must stop on its own. A paused process, for example one stalled by a long garbage collection or a suspended VM, can wake up after its lease has expired and another generator has taken the ID. If it keeps issuing IDs, you have a duplicate. So the generator tracks its own deadline and refuses to issue IDs when the lease is close to expiring.
- The registry must delay reuse. After a lease expires, the registry waits an extra cooldown before giving the ID to someone else. This covers the case where the old holder is still running with a slightly slow or fast clock, and it covers timestamp ordering, as explained below.
A small lease registry in Python
This registry stands in for etcd or a database table. A real one would run as a separate service and be built on atomic operations such as compare-and-swap or a unique-key insert.
import threading
import time
class WorkerRegistry:
"""In-memory stand-in for a coordination service such as etcd or a SQL table."""
def __init__(self, max_workers=1024, lease_s=30.0, cooldown_s=5.0):
self.max_workers = max_workers
self.lease_s = lease_s
self.cooldown_s = cooldown_s
self._expires = {} # worker_id -> time the lease ends
self._owner = {} # worker_id -> owner name
self._lock = threading.Lock()
def acquire(self, owner):
now = time.monotonic()
with self._lock:
for worker_id in range(self.max_workers):
expiry = self._expires.get(worker_id)
# Free if never used, or if the lease ended and the cooldown has passed.
if expiry is None or now >= expiry + self.cooldown_s:
self._owner[worker_id] = owner
self._expires[worker_id] = now + self.lease_s
return worker_id
raise RuntimeError("no free worker IDs")
def renew(self, worker_id, owner):
now = time.monotonic()
with self._lock:
if self._owner.get(worker_id) != owner:
return False
if now >= self._expires[worker_id]:
return False # already expired: the claim is lost, even if nobody took it
self._expires[worker_id] = now + self.lease_s
return True
def release(self, worker_id, owner):
with self._lock:
if self._owner.get(worker_id) == owner:
# End the lease now. The cooldown still applies before reuse.
self._expires[worker_id] = time.monotonic()
class LeasedIdGenerator:
"""Wraps any ID generator and refuses to issue IDs without a safe lease."""
def __init__(self, registry, owner, make_generator, safety_s=5.0):
self.registry = registry
self.owner = owner
self.safety_s = safety_s
started = time.monotonic()
self.worker_id = registry.acquire(owner)
self.generator = make_generator(self.worker_id)
# Count the lease from before the call, so our deadline is never later
# than the registry's.
self.deadline = started + registry.lease_s
def renew(self):
started = time.monotonic()
if not self.registry.renew(self.worker_id, self.owner):
raise RuntimeError("lease lost; stop issuing IDs and restart")
self.deadline = started + self.registry.lease_s
def next_id(self):
if time.monotonic() > self.deadline - self.safety_s:
raise RuntimeError("lease too close to expiry; renew first")
return self.generator.next_id()
class DemoGenerator:
"""Stand-in for the Snowflake class: worker ID in the middle bits, a counter below."""
def __init__(self, worker_id):
self.worker_id = worker_id
self.count = 0
def next_id(self):
self.count += 1
return (self.worker_id << 12) | self.count
registry = WorkerRegistry(lease_s=30.0, cooldown_s=5.0)
a = LeasedIdGenerator(registry, "pod-a", DemoGenerator)
b = LeasedIdGenerator(registry, "pod-b", DemoGenerator)
print(a.worker_id, b.worker_id) # 0 1
print(a.next_id(), b.next_id())
# A short lease shows the self-fencing: after the pause the generator refuses to issue IDs.
short = WorkerRegistry(lease_s=0.2, cooldown_s=0.2)
c = LeasedIdGenerator(short, "pod-c", DemoGenerator, safety_s=0.05)
print(c.next_id())
time.sleep(0.3)
try:
c.next_id()
except RuntimeError as err:
print("refused:", err)The wrapper takes the generator as a function argument. In production you would pass your Snowflake class, so make_generator becomes lambda worker_id: Snowflake(worker_id).
The code measures time with time.monotonic(), which never jumps backwards. Wall-clock time is still used inside the Snowflake timestamp, but lease deadlines should not depend on it.
Why reuse needs a cooldown
Take a worker ID that was last used at timestamp T by a generator that crashed. A new generator receives the same ID and starts issuing IDs with its own clock. If the new machine's clock is 3 seconds behind the old one, its IDs carry timestamps below T. Those timestamps may match IDs the old holder already issued, with the same worker ID and the same sequence numbers.
The cooldown prevents this. Set it to at least the largest clock difference you tolerate between machines, plus the time it takes to detect that a holder is gone. A cooldown of a few seconds is common. You can also store the last issued timestamp in the registry and make the new holder wait until its own clock passes that value. This stronger rule needs a write to the registry, so each generator would have to report timestamps periodically.
Other failure modes
- Cloned machines. A VM image or container snapshot taken after a worker ID was written to disk gives every copy the same ID. Fetch the ID at startup. Do not bake it into an image.
- Exhaustion. Ten bits give 1,024 IDs. A fleet that churns quickly, with many short-lived jobs each taking a lease, can run out because expired IDs sit in cooldown. Release leases on clean shutdown, and measure how many IDs are leased or cooling at any time.
- Registry outage. Generators already running can continue until their deadline. New generators cannot start. Pick a lease length that tolerates short registry outages, for example a 60-second lease renewed every 15 seconds.
- Split registry. If the registry itself can return the same ID to two clients, for example because of a stale replica read, the guarantee is gone. Use a store with linearizable writes for the claim.
- Mixed assignment schemes. If some services use static IDs 0–99 and others lease from the registry, the two groups can overlap. Give each scheme its own non-overlapping range, or use one scheme everywhere.
Testing the assignment
Write tests that exercise the failure paths, not only the happy path.
- Acquire IDs from many threads at once and check that all values are distinct.
- Let a lease expire and check that
acquire()does not return that ID until after the cooldown. - Try
renew()after expiry and check that it returnsFalse, even if nobody else took the ID. - Pause a generator past its deadline and check that
next_id()raises.
For production, alert when a generator reports a lost lease and when the fraction of used worker IDs passes a threshold such as 80%.
Exercise
A fleet uses a registry with a 30-second lease and no cooldown. Generator A holds worker ID 9 and is paused by the hypervisor for 45 seconds. Generator B starts at second 31 and receives worker ID 9. When A resumes, it has not yet noticed the expiry. Explain how a duplicate ID can occur, and name two changes that would prevent it.
Show answer
A's lease expired at second 30, but A resumes at second 45 still holding ID 9 and issues IDs with worker ID 9. B has been issuing IDs with worker ID 9 since second 31. If A and B land on the same millisecond and sequence value, they produce the same ID. Two changes prevent this. First, A should track a local lease deadline and refuse to issue IDs once it is near or past it, so it would raise an error instead of issuing. Second, the registry should add a cooldown after expiry, so B would not receive ID 9 until the cooldown ended and would get a different ID.