Lesson 8 of 16
10. Unique ID Generation

10.7 Why does clock skew matter for time-based IDs?

3 min read+10 XP

The details

At the bank: If a branch's wall clock is set back by a minute, the branch may stamp "0930-B4-017" twice: once before the clock was corrected, once after.

In the system: Server clocks drift, and time-sync services like NTP correct them, sometimes backwards. A Snowflake generator that only checks "is it a new millisecond?" can, after a backward step, reach a millisecond it already used, reset its sequence to 0, and hand out an ID it already handed out (the Level 4 bug).

the clock steps back and a duplicate ID is generated.

Figure: the generator reaches 500 ms twice and stamps the same ID both times.

How generators protect themselves:

  • Remember the last timestamp used. If the clock reads earlier than that, don't reset the sequence.
  • Small step back: wait until the clock catches up. Big step back: refuse to generate and raise an alarm (Twitter's original Snowflake refused when it detected the clock going backwards).
  • Prefer clocks that slew (speed up or slow down gradually) instead of jumping, where your platform allows.
  • Don't treat time order as exact. IDs from different machines are only roughly time-ordered, because their clocks differ by a few milliseconds. Never rely on Snowflake order to decide which of two events on different machines happened first (Chapter 16).

Memory code: "Time-based IDs trust the clock, so never trust a clock that runs backwards."