跳到主要内容
uencoder

生成 Snowflake IDs for distributed systems

Snowflake IDs (Twitter) 组合时间戳, machine ID, 和序列数字为 唯一, sortable IDs 在 distributed systems 无 coordination.

  1. 1

    Snowflake 是 64-位 ID: 41 bits 时间戳 (milliseconds 自 epoch, ~69 years), 10 bits machine ID (1024 machines), 12 bits 序列 (4096 IDs per millisecond per machine). 此 generates ~4 million IDs per 第二, sorted 通过时间, 具有否 coordination 之间 machines. Used 通过 Twitter, Discord, Instagram. machine ID 必须是 唯一 per generator — 分配 via ZooKeeper, Etcd, 或 machine ID 服务.

  2. 2
    时间戳转换器 →

    获取 the current millisecond timestamp for the Snowflake time component. The timestamp should be milliseconds since a custom epoch (not Unix epoch) to maximize the 41-bit range. For example, epoch 2020-01-01 gives ~69 years of IDs. The timestamp provides time-ordering and uniqueness across time.

  3. 3
    高精度计算器 →

    Combine components: id = (时间戳 << 22) | (machineId << 12) | 序列. 位 shifts 位置每个组件. Verify 位 widths: 时间戳 (41 bits) + machineId (10 bits) + 序列 (12 bits) = 64 bits. 序列 increments 内 millisecond 和 resets 当时间戳 advances.

  4. 4
    UUID / ULID 生成器 →

    生成 a UUID for comparison. Snowflake is 64 bits (8 bytes, fits in a BIGINT); UUID is 128 bits (16 bytes). Snowflake is sortable by time; UUID is not. Snowflake requires machine ID coordination; UUID does not. Use Snowflake for high-throughput distributed systems; use UUID for simpler systems or when no coordination is available.

常见问题

如何 I 分配唯一 machine IDs?
Options: (1) ZooKeeper/Etcd — atomically 声称 ID, 发布开 shutdown. (2) Config file — manually 分配 IDs 到每个服务器. (3) IP address hash — hash machine's IP 到 10-位 ID (collision 风险). (4) Cloud 元数据 — use 实例 ID 从 AWS/GCP. (5) Database 序列 — atomically increment. machine ID 必须是 唯一 — 重复原因 ID collisions.
什么 happens 当时间戳 overflows?
之后 ~69 years 从自定义 epoch, 41-位时间戳 overflows. 此 causes IDs 到 wrap around, breaking sortability 和 potentially 原因 collisions. Plan epoch 到是 close 到你的部署日期. 如果你 方法限制, migrate 到新 epoch (requires updating 所有 ID generation, 但 existing IDs 是不 affected).

解决此任务的工作流

相关工具