Sub topic 3
Worker IDs, Clock Hazards, and Choosing an ID Scheme
Assume you know basic Python, relational databases and indexes, binary numbers, and the idea that several machines can fail independently.
Giving Every Generator a Unique Worker ID
A Snowflake-style ID usually combines:
- A timestamp.
- A worker ID.
- A sequence number for IDs created in the same time unit.
The worker ID must be unique among all active generators. If two workers use ID 7 at the same timestamp and sequence value, they can produce the same final ID.
A static configuration file works only when the deployment is small and stable. Common production approaches include:
- Assigning IDs from a central registry when a worker starts.
- Giving each virtual machine a reserved range.
- Deriving an ID from a database lease, where the worker periodically proves it is still alive.
- Using orchestration metadata, provided the identifier cannot be reused while an old process is still running.
Leases need fencing. If a paused worker wakes after its lease expires, it must not continue generating IDs with the old assignment.
Clock Skew and Backwards Clocks
The timestamp field depends on a local clock. NTP synchronization reduces clock differences but does not eliminate them. A clock can move backward after correction, virtual-machine migration, or operator error.
A generator should detect now < last_timestamp. It can then:
- Stop and alert.
- Wait until the clock catches up.
- Use a logical timestamp that never decreases.
Each option affects availability or complexity. Never silently reuse timestamps and sequence values. Also handle sequence exhaustion when a worker creates more IDs than its sequence field allows in one time unit.
> callout warning > A unique worker ID cannot protect against duplicates if the same worker restarts with an earlier timestamp and resets its sequence incorrectly.
Predictable IDs and What They Reveal
Time-ordered or Snowflake IDs often reveal creation time, approximate traffic rate, and sometimes the worker count. Sequential IDs also make it easy to guess neighboring records. Do not use such IDs as authorization checks. Enforce access control separately, or use an unguessable public identifier.
Choosing a Scheme
Choose based on the system’s constraints:
- Use a central sequence when one database is authoritative and coordination is acceptable.
- Use UUID v4 when independent generation and low collision risk matter more than ordering.
- Use UUID v7 or ULID when you need sortable IDs with good index locality.
- Use Snowflake-style IDs when compact, ordered, high-throughput integers are valuable and worker assignment and clock handling are reliable.
Exercise
Why can two healthy generators still create duplicate Snowflake IDs?
Show answer
They can duplicate IDs if they share a worker ID, or if one worker reuses a timestamp and sequence combination after its clock moves backward.