How it works
Each worker keeps its last timestamp and sequence in memory. If the clock advances, reset the sequence to zero; if it remains in the same millisecond, increment it. When 4,096 sequence values have been used, wait for the next millisecond or reject with a defined backpressure response, meaning an explicit “slow down” error the caller can act on. Wrapping to zero in the same millisecond would repeat an ID.
Trace one worker. At millisecond 1,000 it has issued sequence 4,094. The next call takes 4,095, the last value. The call after that finds the range spent, spins until the clock reads 1,001, and takes sequence 0. The wait is under a millisecond, so waiting usually beats failing. At 25,000 IDs per second shared across a fleet, an average of 25 per millisecond, exhaustion should be rare; a rising count suggests traffic has concentrated on too few workers.
Make generation thread-safe within the process. A lock, atomic state transition, or a single generator loop must ensure two threads cannot observe the same timestamp and sequence pair. If the process restarts within the same millisecond under the same worker ID, it may reuse a sequence; preserve last-issued time where needed, wait beyond the prior slot, or lease a new worker identity.
One side effect: at low traffic most IDs carry sequence 0, so their low bits barely vary. Sharding by ID modulo a power of two would then send almost everything to one shard, so hash the ID first.
A worker has issued all 4,096 sequence values in the current millisecond. What must it avoid?
It must not reset the sequence while the timestamp is unchanged. Wait until the next millisecond or fail according to the API contract.
Use this as a guide for self review; written answers are not graded.Keep in mind
- A full sequence range requires waiting or backpressure, not wraparound.
- Worker state and restart behavior are part of uniqueness.