pub struct Snowflake(/* private fields */);
Expand description
Generated Snowflake
§Implementation
Let me describe snowflake ID (SID in below) in simple words.
Firstly, we have to know this structure of SID.
SIDs are actually i64 types. It’s length 64bit and 1bit for sign.
So it looks like this:
| sign | data | # sign not used.
| 1bit | 63bit |
Next, I’ll introduce standard SID design to you. Why STANDARD? Because there are some variant, just ignore them use Twitter’s(formally X) design only.
The standard SID contains these content:
- Timestamp: 41bit
- Identifier(or Machine ID?): 10bit
- Sequence Number: 12bit
Our SID structure looks like this
| sign | data |
| 0 | Timestamp | Identifier | Sequence Number |
| 1bit | 41bit | 10bit | 12bit |
✨ So cool, you in just understood the SID structure!
Ok, let’s deep in DARK.
§Timestamp
In standard design, timestamp can start at any time.
But here, the precision we need for the timestamp is to the millisecond, so exactly 41bits.
§Identifier
Base the design of distributed systems, we will have many machine(or instance) running at same time.
So we must distinguish between them. Based identifier have 10bit, we can have 1024 instance at same time, thats so cool!
§Sequence Number
Have you just noticed the Sequence Number
? It have 12bit, means it can process at most 4096 message(or other things if you want) in one millisecond.
Above all, we can know: the entire system can produce at most 1024 * 4096 = 4194304
pieces of message at one millisecond!
§Out of assigned
But there is always the possibility that we will encounter a situation: all the SIDs for this millisecond have been assigned!
At this time, the instance must waiting for next millisecond. At next millisecond, we will have new 4096 SID can be assigned.