System Design · 03. Data & Storage · 8 min · Intermediate
Unique IDs at Scale
Give every row a different id when many machines create rows at the same time.
In short
Auto-increment is perfect on one database and breaks with shards. UUIDs need no coordination but are 16 bytes and random. A ticket server hands out blocks; Snowflake packs time, machine and counter into 8 bytes.
Snowflake ids stay unique with no talking, sort by time and allow 4,096,000 ids a second per machine. Their one weakness is the clock, so guard against it going back.
Key ideas
- Across 1,024 machines that is over 4,194,304,000 ids a second, more than any real system needs. (step 6)
Good to know
- If one database is enough for you, auto-increment is the best choice. Do not leave it early. (step 1)
- No coordination means no bottleneck, and ids can be made on a phone, in a browser or offline. (step 3)
- This is what UUIDs lacked: ids that are unique everywhere and still in time order. (step 7)
Watch out
- An id that is only unique inside one shard cannot be used to talk about a row across the system. (step 2)
- Newer UUID versions (such as v7) put a timestamp first to fix the ordering. That is the same idea as Snowflake, coming up. (step 4)
- Ids from different servers are only roughly in time order, because each server holds a block. (step 5)
- Clock-based ids are only as good as the clocks. Use a time source you trust, and guard against going back. (step 8)
Key numbers
- Id size
- 8 bytes
- Ids per second
- 4,096,000/s each
- Sorted by time
- yes
- Duplicate risk
- none (guarded)
Terms
- Auto-increment id
- A counter inside one database that gives each new row the next number.
- UUID
- A 128-bit identifier, mostly random, that can be made anywhere without coordination.
- Id collision
- Two different rows getting the same id, which random 128-bit ids make practically impossible.
- Ticket server
- A small database that hands out blocks of ids so app servers can count locally.
- Snowflake id
- A 64-bit id made of a timestamp, a machine number and a per-millisecond counter.
- Sequence number
- The counter in an id that separates ids made by the same machine in the same millisecond.
- Time-ordered ids
- Ids that sort by creation time, so the newest rows are at the end of an index.
- Clock skew
- Clocks on different machines, or one clock over time, disagreeing or jumping, which can break clock-based ids.