Algorithms · Huge scale
Snowflake IDs
Snowflake: Twitter’s IDs that tell time. Thousands of machines making unique IDs at once, without ever asking each other.
The problem
Every tweet needs its own ID, and no two tweets can ever share one. By 2010 Twitter was storing tweets on many machines at once, and all of them were creating new records at the same moment.
So Twitter announced Snowflake: a way to make unique 64-bit IDs across many machines without the machines talking to each other. As a bonus, the IDs sort roughly by time.
The obvious way
Keep one shared counter. Need an ID? Ask the counter for the next number. This works on one machine. With many machines, they all queue at that single counter, and a lock makes them take turns. If the counter is slow or down, nobody can make IDs. The code below runs this version too, so you can see it.
The clever idea
Think of a coat-check ticket that reads "Tuesday, 14:03:07, desk 2, ticket 5". Two desks can never clash, because the desk number is baked into the ticket. And nobody had to phone a central office.
Snowflake packs one 64-bit number the same way: 1 unused sign bit, then 41 bits of milliseconds since a custom epoch, then 10 bits of machine (worker) id, then 12 bits of a per-millisecond sequence number. Time goes first, so newer IDs are bigger.
How the code does it
Look at this line. The time is shifted left 22 places (10 worker bits plus 12 sequence bits), the worker id is shifted left 12, and the sequence sits at the bottom. Two workers differ in the worker slot, and one worker differs in the sequence slot. decode simply reverses the shifts.
The counter version in locked_next counts every "trip to central": 12 IDs cost 12 trips. Snowflake's workers cost 0, because the sequence trick only needs each worker's own memory and a clock. The table also shows time never goes backwards, which is what "sorts roughly by time" means.
Trade-offs
Snowflake IDs are only roughly time-ordered. Two workers in the same millisecond are ordered by worker id, not by who really went first. You also need each worker to have a different id, and workers need a sensible clock. Each worker can make only 4096 IDs per millisecond, because the sequence has 12 bits. Don't use it when you need strictly gap-free, strictly ordered numbers, such as invoice numbers.
Where else you'll see it
Discord and Instagram use similar timestamp-first ID schemes. The original code is archived at github.com/twitter-archive/snowflake, so you can compare it with the toy version above.
Workers 2 and 3 each make an ID in the very same millisecond. What keeps the IDs different?
- The sequence number
- The worker id bits
- The unused sign bit
Show the answer
The worker id bits. The worker id sits in its own 10-bit slot, so workers 2 and 3 differ there even with the same time and sequence. The sequence only separates IDs from the same worker.
- Change step // 6 to step // 12
- Change the worker ids to 5, 6, 7
- Change range(12) to range(30)
The code
Python, with what each line means beside it. It compares the clever way with one shared counter.
EPOCH = 1_700_000_000_000 # our own demo start time (ms)Pick a start time for our clock class Snowflake:A generator belongs to one worker def __init__(self, worker):Set up when a worker is created self.worker = workerRemember which worker we are self.last_ms = -1Remember the last millisecond we used self.seq = 0Start the per-millisecond count at zero def next_id(self, now_ms):Make a new ID, given the current time if now_ms == self.last_ms:Same millisecond as last time? self.seq += 1Bump the sequence number else:Otherwise self.last_ms, self.seq = now_ms, 0Remember the new millisecond, reset sequence return ((now_ms - EPOCH) << 22) | (self.worker << 12) | self.seqGlue time, worker, sequence into one number def decode(i):Take an ID apart again return [i, i >> 22, (i >> 12) & 1023, i & 4095]Return id, time, worker, and sequence # Obvious way: ONE shared counter. Every machine must ask it, and a lockObvious way: everyone asks one central counter# makes them take turns so nobody gets the same number twice.A lock makes machines wait their turncounter, trips = 0, 0Start the counter and a trip tallydef locked_next():Ask the central counter for a number global counter, tripsReach for the shared variables trips += 1 # a network trip to the single central counterCount one more trip to the center counter += 1 # imagine a lock held around this lineAdd one to the counter return counterHand back the number workers = [Snowflake(w) for w in (1, 2, 3)]Create three workers numbered 1, 2, 3ids = []Start with an empty list of IDsfor step in range(12):Twelve rounds, one ID each now = EPOCH + 1000 + step // 6 * 5 # fake clock: 5 ms per roundCompute the pretend clock for this round ids.append(workers[step % 3].next_id(now))Next worker in turn makes an ID locked_next()The obvious way also takes a number show([["id", "ms", "worker", "seq"]] + [decode(i) for i in ids[:6]], "Decoded IDs")Show the first six IDs decodedshow([sum(decode(i)[2] == w for i in ids) for w in (1, 2, 3)], "IDs per worker")Show how many IDs each worker madeshow({"counter: trips to central": trips, "snowflake: trips to central": 0,Compare both ways in one table "all unique": len(set(ids)) == 12,Check all IDs are unique "time never goes backwards": [i >> 22 for i in ids] == sorted(i >> 22 for i in ids)}, "Obvious vs clever")Check time never goes backwards- sequence trick lines 10–13Same millisecond means the sequence counts up. A new millisecond resets it, so one worker can't repeat itself.
- packing bits line 14Shifting left slides each piece into its own slot of the 64-bit number. The OR glues the pieces together.
- unpacking line 17Shift right to drop the low bits. Mask with & to keep only a slot's bits.
- the bottleneck lines 19–26Every ID costs a trip to one place. If that place is slow or down, everyone waits.
Read more
- github.com: Snowflake IDs
- The real code: twitter-archive/snowflake
- Ask Bento: What if the clock jumps backwards?
- Ask Bento: How do UUIDs avoid collisions?
- Ask Bento: How does sharding use these IDs?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.