Expand description
Snowflake is a unique ID generator that generates IDs based on the current time, a worker ID, and a sequence value.
Snowflake IDs are not strictly sequential but are designed to be ordered. The ordering is based on the timestamp part of the ID, so IDs generated at later times will be numerically larger than those generated earlier. However, within the same millisecond, IDs can vary based on the sequence number. Here are key points about ordering:
- Temporal Ordering: IDs are ordered by the timestamp portion, so IDs generated at different times are in chronological order.
- Same Timestamp: When multiple IDs are generated within the same millisecond, the sequence number differentiates them. This ensures uniqueness but doesn’t guarantee a strict numerical order within that millisecond.
- Clock Skew: If system clocks are not synchronized across workers, or if a machine’s clock goes backward, it might lead to IDs that don’t strictly follow the expected order.
Default Snowflake ID structure:
- Sign bit: Always 0.
- Timestamp: 41 bits, representing milliseconds since a custom epoch.
- Worker ID: 10 bits, identifying the worker that generated the ID.
- Sequence: 12 bits, providing uniqueness within the same millisecond.
- Total: 64 bits.
The number of bits used for the worker ID and sequence number can be customized. The total number of bits must be 64, and the worker ID and sequence number must be at least 1 bit each.
§Examples
use twitter_snowflake::Snowflake;
// Create a new snowflake generator with a worker ID
let mut snowflake = Snowflake::new(1).unwrap();
// Generate a snowflake ID
let id = snowflake.generate().unwrap();
println!("Generated ID: {}", id);
§Errors
The Snowflake generator can return the following errors:
ArgumentError
: Indicates an invalid argument was provided to the Snowflake generator.ClockMoveBackwards
: Indicates that the system clock has moved backwards.WaitForNextPeriodTimeout
: Indicates that the generator has timed out while waiting for the next time period.InvalidEpoch
: Indicates that the epoch time must be greater than the current time.FailedConvertToMillis
: Indicates that the generator failed to convert the timestamp to milliseconds.
§Safety
The Snowflake generator is safe to use in a multi-threaded environment as long as each thread has its own instance of the generator.
Structs§
- Snowflake
- Snowflake
Builder - A builder for creating a Snowflake generator with custom configuration.