引言
每条记录需要唯一 id,在何处生成它是影响存储、索引与性能的设计决定。数据库序列简单但集中生成并泄露顺序。随机 UUID 无需协调但损害索引局部性与存储。UUIDv7、ULID 与 Snowflake 等时间有序 id 无需协调即给唯一性并可按创建时间排序,保持索引高效。在其中选择取决于你需要 id 提供什么。
Id 必须提供什么
id 必须唯一,显然,但还须:运行多节点时可无协调生成、想要高效分页与索引时可按创建时间排序、不想泄露计数或顺序时不透明、存数十亿时紧凑。没有单一方案给全部,因此选择取决于哪些属性要紧。
两大张力是协调对本地生成、可排序对不透明。数据库序列协调且顺序;随机 UUID 本地且不透明;时间有序 id 本地且可排序但泄露创建时间与大致顺序。
随机 UUID 及其成本
UUIDv4 是 122 随机位,随处生成无需协调且实际无碰撞。成本在它是随机的,因此插入分散于索引:每次插入触碰随机页,造成页分裂与差缓存局部性,索引增长碎片化。写密集表上这是可测的吞吐成本。
随机 UUID 也大(16 字节)比 64 位整数,因此耗更多存储与索引空间。它们不透明,是其优点,但索引成本真实,这正是时间有序替代存在的原因。
时间有序 Id:UUIDv7 与 ULID
UUIDv7 把毫秒时间戳放在高位、其余填随机,因此 id 仍唯一且本地但按创建时间排序。ULID 类似:48 位时间戳加随机,编码为紧凑字符串。两者保持插入大致顺序,恢复索引局部性,同时对多数用途仍足够不透明。
它们泄露创建时间与大致顺序,当 id 用户可见且顺序敏感时要紧。时间戳粗(毫秒),同一毫秒创建的 id 靠随机部分排序;严格的每毫秒顺序需要加计数器,如 Snowflake。
Snowflake 及其变体
Snowflake 把时间戳、节点 id 与每毫秒序列打包进 64 位:唯一性来自组合而非随机。它紧凑(放进 bigint)、可排序,且无需协调,因为每个节点在配置时有不同节点 id。
麻烦是节点 id:它必须跨机群唯一且稳定,是一个协调点(从配置服务、机器身份或每地区 id 范围分配)。重复节点 id 产生重复 id,时钟漂移可产生乱序 id,因此时钟必须足够单调。
为存储与索引选择
对数据库主键,时间有序 id 保持索引高效:插入到右端、页顺序填充、按 id 的范围扫描遵循时间顺序。随机 UUID 分散写;序列的顺序 bigint 高效但集中。时间有序 id 是分布式系统的常见甜点。
若 id 仅内部用,Snowflake bigint 最紧凑。若必须是 UUID(标准或期望它的客户端),UUIDv7 给 UUID 格式加时间排序,这就是它作为主键比 UUIDv4 的现代推荐的原因。
唯一性与失败模式
每种方案都有唯一性论证:UUID 随机(碰撞概率可忽略),或节点 id 加序列。失败模式是假设被打破之处:重复的 Snowflake 节点 id、向后跳的时钟(复用同一毫秒)、或两节点同种子随机器。
守护时钟:若时间倒退,或等到追上或谨慎复用序列,使 id 永不重复或乱序。把节点 id 唯一性当作运维不变量测试,因为重复节点 id 是静默唯一性 bug,表现为主键冲突。
常见陷阱与小结
不要在没有接受索引成本下把 UUIDv4 用作写密集表主键;改用 UUIDv7。不要给两节点同 Snowflake 节点 id。不要忽略倒退的时钟。也不要假定任何 id 方案消除在存储层验证唯一性的需要,那里重复必须被拒绝。
分布式 id 生成器给每个节点一种无需按 id 协调即铸造唯一 id 的方式。按需要的属性选择:UUIDv7 给时间有序 UUID、ULID 给紧凑可排序字符串、Snowflake 给带节点 id 的紧凑 bigint、UUIDv4 只在无透明度胜于索引成本时。守护假定不变量(节点 id、时钟),让存储层作为后盾强制唯一性。
代码示例
# id properties to weigh
[ ] unique (all schemes)
[ ] generatable without a coordinator (for many nodes)
[ ] sortable by creation time (for pagination + index locality)
[ ] opaque (no leaked counts/ordering)
[ ] compact (storage at scale)
# no scheme gives all; pick by what matters for the record
# UUIDv4
+ no coordination, opaque, collision-free in practice
- 16 bytes (vs 8 for a bigint)
- RANDOM => writes scatter across the index: page splits, poor locality
# the random write pattern is the main cost on a write-heavy table
// UUIDv7: 48-bit ms timestamp + version/variant + randomness (illustrative).
function uuidv7(): string {
const ts = Date.now();
const timeHex = ts.toString(16).padStart(12, '0'); // 48 bits of time
const rand = crypto.getRandomValues(new Uint8Array(10)); // 80 bits of randomness
const r = Buffer.from(rand).toString('hex');
// layout: time | ver 7 | randA | variant | randB (RFC 9562)
return `${timeHex.slice(0,8)}-${timeHex.slice(8,12)}-7${r.slice(0,3)}-${r.slice(3,7)}-${r.slice(7,19)}`;
}
// sortable by creation time => inserts stay roughly sequential
# Snowflake 64-bit layout (common variant)
[ 41 bits timestamp ][ 10 bits node id ][ 12 bits sequence ]
# - unique from the node id + sequence, not randomness
# - compact (bigint), sortable, no runtime coordination
# - requires a UNIQUE, STABLE node id per instance (a config point)
# - guarded against clock going backwards (reject or wait)
# pick by use
internal PK, want compact -> Snowflake bigint
must be a UUID -> UUIDv7 (time-ordered, unlike v4)
human-readable sortable -> ULID (compact string, time-ordered)
no ordering wanted at all -> UUIDv4 (accept the index cost)
# failure modes to guard
[ ] duplicated node id (Snowflake) => duplicate ids; enforce uniqueness
[ ] clock goes backwards => reuse the ms; wait or bump the sequence
[ ] random seeded identically => collisions; use a CSPRNG
# make node-id uniqueness an operational check, not an assumption