AlgoViz

Unique ID generator

medium 28 min

Give every record its own number, from many servers at once.

See it run

Build an ID from its bits, then see what a full millisecond, a wrong clock and a crash do to it.

Operations

Build a Snowflake ID

Time, datacenter, machine and counter become one 64-bit number.

Step 1 of 7

A request

BitsValue
Time41-
Datacenter5-
Machine5-
Counter12-

A new order needs an ID. Nothing is filled in yet.

Step 1: A request

def make(ms, datacenter, machine, counter):    i = ms - EPOCH                 # 41 bits    i = i << 5 | datacenter        # 5 bits    i = i << 5 | machine           # 5 bits    i = i << 12 | counter          # 12 bits    return i
Coordination
Machine number, once
Weak point
Clock and number

Time is in the highest bits, so larger means later.

In the real world

The same unique id generator doing real jobs. Pick one and step through it.

Auto-increment on two servers.

Step 1 of 3

Both start at 1

Server AServer B
Order 1ID 1ID 1

Same ID

Server A and server B each count for themselves.

Step 1: Both start at 1

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • One machine number, two processes

    critical

    The same millisecond and counter give the same ID.

    Wrong
    MACHINE = 7   # in the image
    Right
    MACHINE = leases.take()   # renewed while we run
  • Ignoring the last time

    critical

    After a correction of the clock, IDs are repeated.

    Wrong
    now = clock()counter = 0
    Right
    now = clock()if now < last: wait_or_refuse()
  • Numbers in JSON

    major

    JavaScript rounds integers beyond 2^53.

    Wrong
    {"id": 395848345190559745}
    Right
    {"id": "395848345190559745"}
  • The ID as a secret

    critical

    Sequential and time-based IDs can be guessed.

    Wrong
    GET /photos/1042   # no check
    Right
    photo = find(1042)if photo.owner != user: return 404

Interview tips

  • Explain it in one line

    • Share out numbers before, or build them from parts nobody else has.
  • SNOW

    • Sortable, No coordination.
    • One machine one number, Works at scale.
  • Good numbers

    • 41 bits of ms: 69.7 years.
    • 12 bits: 4,096 a millisecond.
    • 10 bits: 1,024 machines.
  • Expect these questions

    • What if the clock goes back?
    • Who gives out machine numbers?
    • Why not UUIDv4?