Video in progress
How do you generate unique IDs in a system with several services and databases: UUID, a DB sequence or Snowflake?
A DB sequence is simple and compact, but ties everything to the DB. A UUID depends on nobody, but because it's 128 bits and random it bloats the B-tree index. A 64-bit Snowflake-style ID sorts by time and is generated without central coordination.
📖 Answer
A DB sequence or identity — a bigint, sequential, ideal for an index. But you have to go to the DB for every record, and with sharding each shard keeps its own sequence and the IDs collide (you can solve it with an offset and a step, but it's awkward). In Hibernate, grabbing several IDs ahead of time with SEQUENCE + allocationSize reduces the load.
A UUID v4 can be created by the client or the service itself, and collisions don't happen in practice. The problem is randomness: every insert lands in a random place in the B-tree, pages split, and the cache works badly. On a large table inserts get noticeably slower.
UUID v7 has a millisecond timestamp at the start, so it grows over time and goes into the index much better than v4. It's standardized in RFC 9562. Java's standard library has only UUID.randomUUID() (v4); for v7 you need a library.
Snowflake — 64 bits: 41 bits time | 10 bits node | 12 bits counter (plus one unused sign bit). A single node issues 4096 IDs per millisecond, it fits in a long and it sorts. You have to solve how to give each instance a unique node ID (configuration, ZooKeeper or a lease in the DB). If the clock goes backward, the generator has to wait so it doesn't produce duplicates.
What I usually do: with one DB, a sequence; when the ID is exposed outside or many services create IDs independently, UUID v7.
Sign up to mark studied questions and save your progress.