| Crates.io | gen-id |
| lib.rs | gen-id |
| version | 0.3.0 |
| created_at | 2024-10-09 22:44:53.693787+00 |
| updated_at | 2024-12-24 11:45:35.785267+00 |
| description | Snowflakes. |
| homepage | |
| repository | https://github.com/wavey-ai/gen-id |
| max_upload_size | |
| id | 1403152 |
| size | 26,451 |
A Rust library for generating distributed, time-ordered, and optionally shardable IDs. Based on Twitter Snowflakes.
use gen_id::{IdGenerator, ConfigPreset, DEFAULT_EPOCH};
// Create a generator with sharding support
let generator = IdGenerator::new(ConfigPreset::ShardedConfig, DEFAULT_EPOCH);
// Generate a base ID for node 1
let original_id = generator.next_id(1);
// Create two derived IDs in different shards
let shard_0_id = generator.derive_sharded_id(original_id, 0);
let shard_1_id = generator.derive_sharded_id(original_id, 1);
// All derived IDs decode back to show the same original time, node, and sequence
let decoded = generator.decode_id(shard_1_id);
The key feature of this ID generator is the ability to create derived sharded IDs that maintain their relationship with the original ID. This is useful when you need to:
For example, if you have a user's post with ID 123456 and need to store related analytics across multiple shards, you can derive new IDs like this:
let post_id = generator.next_id(1); // Original post ID
let analytics_shard_1 = generator.derive_sharded_id(post_id, 1); // Analytics data in shard 1
let analytics_shard_2 = generator.derive_sharded_id(post_id, 2); // Analytics data in shard 2
These derived IDs:
The 64-bit ID is composed of different bit allocations depending on the configuration:
Total capacity: 16.7 million IDs per second per node (1,024 1000ms 16,384 nodes)
Total capacity: 16.7 million IDs per second per node (1,024 1000ms 16,384 nodes)
Key differences:
// Standard configuration with sharding
let gen = IdGenerator::new(ConfigPreset::ShardedConfig, DEFAULT_EPOCH);
// Configuration optimized for maximum nodes
let gen = IdGenerator::new(ConfigPreset::ShortEpochMaxNodes, DEFAULT_EPOCH);
let gen = IdGenerator::new(
ConfigPreset::Custom(
epoch, // Custom epoch timestamp
epoch_bits, // Timestamp bits
node_bits, // Node ID bits
shard_bits, // Shard bits
config_id, // Configuration identifier
),
epoch,
);
Enable WASM support in your Cargo.toml:
[dependencies]
gen-id = { version = "0.2.1", features = ["wasm"] }
Usage in JavaScript:
import init, { WasmIdGenerator } from "gen-id";
await init();
const DEFAULT_EPOCH = 1609459200000; // 2021-01-01
const generator = new WasmIdGenerator(1, DEFAULT_EPOCH); // 1 = ShardedConfig
const id = generator.next_id(1);
const shardedId = generator.derive_sharded_id(id, 5);
The generator is thread-safe and can be shared across threads using atomic operations for sequence number generation.
MIT