Sub topic 10
Giving Every Generator a Unique Worker ID
This chapter assumes you know how a Snowflake-style ID is laid out (timestamp, worker ID, sequence) and can read bit-shifting code. The scheme only guarantees uniqueness if no two live generators share a worker ID. That makes worker ID assignment a coordination problem, and it is the one place where a Snowflake design still needs agreement between nodes.
Why duplicates appear
Two generators with the same worker ID and the same millisecond both start their sequence at 0. They produce identical IDs. Nothing in the ID format detects this. The collision appears later as a primary key violation, or worse, as silently overwritten rows in a store that accepts upserts.
With 10 worker bits you have 1024 values. That is plenty for a fixed fleet, but autoscaling and restarts can burn through assignments if you never reuse them, and can hand out the same value twice if you reuse them carelessly.
Common assignment strategies
| Strategy | How it works | Main risk |
|---|---|---|
| Static configuration | An operator writes a worker ID into each host's config | Copy and paste errors, cloned images |
| Derived from host data | Hash the IP address, hostname, or MAC address into 10 bits | Hash collisions, since 1024 slots fill quickly |
| Lease from a coordinator | The node claims an ID in ZooKeeper, etcd, or a database row, and renews it | Lease expires while the node is still running |
| Orchestrator ordinal | A Kubernetes StatefulSet pod index is the worker ID | Only works for stable, bounded replica counts |
Hashing is the weakest option. By the birthday bound from earlier in this tutorial, 40 nodes hashed into 1024 slots already have roughly a 53% chance of at least one collision. Use hashing only if you check for conflicts afterward.
Leases in practice
A lease is a claim on a worker ID that expires unless the holder renews it. The coordinator stores one row per worker ID with an owner and an expiry time. A node starting up claims any ID whose lease has expired, then renews on a timer.
import time
class LeaseTable:
"""In-memory stand-in for a coordinator such as a database table."""
def __init__(self, size=1024, ttl_seconds=30):
self.size = size
self.ttl = ttl_seconds
self.leases = {} # worker_id -> (owner, expires_at)
def claim(self, owner):
now = time.monotonic()
for worker_id in range(self.size):
held = self.leases.get(worker_id)
if held is None or held[1] <= now:
self.leases[worker_id] = (owner, now + self.ttl)
return worker_id
raise RuntimeError("no free worker IDs")
def renew(self, worker_id, owner):
held = self.leases.get(worker_id)
if held is None or held[0] != owner:
raise RuntimeError("lease lost; stop generating IDs")
self.leases[worker_id] = (owner, time.monotonic() + self.ttl)
table = LeaseTable()
print(table.claim("node-a")) # 0
print(table.claim("node-b")) # 1A real coordinator must make claim atomic. In a database, that means a single UPDATE ... WHERE expires_at < now() statement or a transaction, not a read followed by a write.
The expired lease problem
A lease only protects you if the old holder stops generating IDs before the lease expires. A node that pauses for a long garbage collection, or loses network access to the coordinator, may not know its lease ran out. Meanwhile another node claims the same worker ID.
Mitigations:
- Have the generator check its own lease deadline before every batch of IDs, using a monotonic clock, and refuse to issue IDs when less than a safety margin remains.
- Set the renewal interval well below the TTL, for example renew every 10 seconds on a 30 second lease.
- Wait one full TTL after startup before issuing IDs if the node cannot prove the previous owner is gone.
- Never reuse a worker ID immediately after a crash. Let the lease expire first.
Choosing a strategy
- Small, fixed fleet: static configuration or StatefulSet ordinals are simple and adequate.
- Elastic fleet: use leases, and make the generator stop on lease loss.
- No coordinator available at all: Snowflake is the wrong tool. Use random IDs such as UUID v4 or a time-ordered UUID v7, which need no assignment step.
Exercise
A Snowflake generator uses 10 worker bits and a lease TTL of 30 seconds. Node A is paused for 45 seconds by a long GC pause, and node B claims A's old worker ID during the pause. What check inside node A prevents duplicate IDs when it resumes, and why must that check use a monotonic clock?
Show answer
Before issuing IDs, node A compares the current time to its own lease deadline and refuses to generate if the lease has expired or is within a safety margin. After the pause the deadline has passed, so A must renew (and may be told the ID is gone) before generating again. A monotonic clock is needed because wall-clock time can be adjusted by NTP or an operator, which could make an expired lease look valid.