Want the details?
Why is a unique ID hard?
On one database, a counter that goes up by one (AUTO_INCREMENT, a sequence) is the simplest unique ID. With many app servers, and especially with many databases, there is no single place that can count without becoming slow or a single point of failure.
Good IDs usually need three things: unique (never repeated), fast to make (no waiting for another server), and often sortable by time (newer IDs are bigger, which keeps indexes efficient and makes "latest first" easy). Each method on the bench gets a different two or three of these.
How to read the bench
| Part on the bench | What it means in a real system |
|---|---|
| Boxes 1 to 3 | App servers that create orders. A lit lamp: the server is waiting for an ID. |
| Box with # | The central counter (a database sequence or a small ID service). Dim when it is not used; a cross when it is off. |
| Ball | A request for the next number, and the answer coming back. |
| Cards on the belt | New IDs, newest at the left. A dot means the ID is smaller than the one made just before it. |
The numbers
- 3 servers, each wants a new ID every 0.5 s: 6 a second.
- Counter: 0.12 s each way, 0.25 s per number (4 a second). In 30 s: 113 IDs, waits up to about 0.8 s.
- Random: 179 IDs in 30 s, no waiting, about half in time order. With 53 random bits, a repeat among a million IDs has a chance of about 1 in 18,000; real UUIDs use 122 random bits, which makes it practically impossible.
- Time + machine + sequence: 179 IDs in 30 s, no waiting, all in time order. The value is milliseconds × 4096 + server × 1024 + sequence.
- A 1-second clock jump makes server 2 wait about 0.5 s. No ID is repeated; the test checks this through hundreds of random jumps, outages and method changes.
In real systems
- Twitter's Snowflake made the time + machine + sequence layout famous: 41 bits of time, 10 bits of machine, 12 bits of sequence in one 64-bit number. Discord, Instagram and many others use similar IDs.
- UUID version 4 is fully random. UUID version 7 and ULID put the time first, so they are random enough and sortable by time.
- Ranges from a counter. A server can ask the central counter for 1,000 numbers at once and hand them out locally: far fewer trips, but IDs are only roughly in order.
- Clocks are not perfect. Time-based IDs must handle clocks that jump back (as on the bench) and need each machine number to be unique.
Words to know
- Single point of failure
- One part whose failure stops the whole system.
- UUID
- A 128-bit identifier; version 4 is random, version 7 starts with the time.
- Snowflake ID
- A 64-bit ID made of a timestamp, a machine number and a sequence.
- Monotonic
- Always growing: each new ID is bigger than the last.
- Clock skew
- The difference between the clocks of two machines, or a jump in one machine's clock.