03. Data & Storage / Lesson 7 of 11

Unique IDs at Scale

Give every row a different id when many machines create rows at the same time.

  • 8 min
  • Intermediate
  • 9 steps
  • Id size8 bytes (good)
  • Ids per second5,000/s (good)
  • Sorted by timeyes (good)
  • Duplicate risknone (good)

INSERT INTO orders

row 1 → id 1

row 2 → id 2

✓ row 3 → id 3

AppDatabaseorders table
  • Request
  • Response
  • Write
  • Failed request
Step 1/9

Step 1 of 9: One database counts: 1, 2, 3...

Read every step as text
  1. Step 1: One database counts: 1, 2, 3...

    Every row needs an id that nobody else has. With one database the easy answer is an auto-increment column: the database keeps a counter and gives the next number to each new row.

    It is small (8 bytes), simple, and sorted by creation. Its limit is that one machine does all the counting. Say it can hand out about 5,000 new ids a second.

    If one database is enough for you, auto-increment is the best choice. Do not leave it early.

  2. Step 2: Two databases, two counters

    Now we shard the orders table. Each shard has its own counter, so both give out 1, 2, 3. Order 3 on shard A and order 3 on shard B are different orders with the same id.

    A quick fix is to make shard A hand out odd numbers and shard B even ones. It works for two shards, but adding a third means changing every counter. And every insert still needs a trip to the database that owns the counter.

    An id that is only unique inside one shard cannot be used to talk about a row across the system.

  3. Step 3: UUIDs: pick a random number big enough to be unique

    A UUID (version 4) is a 128-bit number, of which 122 bits are random, written like 3f2a9c1e-7b4d-4e8a-9c05-1d6b8e2f7a43. Each app server makes its own, with no talking to anyone and no central counter.

    Collisions are possible but absurdly rare: you would need about 2.7 quintillion UUIDs for a 50% chance of even one duplicate. At a billion a second that takes about 86 years.

    No coordination means no bottleneck, and ids can be made on a phone, in a browser or offline.

  4. Step 4: UUIDs are big and random

    A UUID is 16 bytes, twice as big as an 8-byte number. For 1,000,000,000 rows the id column alone is 16 GB instead of 8 GB, and every index that stores the id repeats that cost.

    Worse, they are random. In a B-tree index (see Indexes) each new id lands on a random leaf page, so the database keeps loading and rewriting pages all over the index instead of adding to the end. They are also not sorted by time, and hard for people to read.

    Newer UUID versions (such as v7) put a timestamp first to fix the ordering. That is the same idea as Snowflake, coming up.

  5. Step 5: A ticket server hands out blocks of ids

    Keep one small database whose only job is the counter. An app server asks for a block of 1,000 ids, say 5,001 to 6,000, then hands them out from memory, and asks again only when it runs out.

    If the ticket server answers 5,000 requests a second, that is up to 5,000,000 ids a second, and ids stay 8 bytes. A crashed app server wastes the rest of its block, which is harmless. Run two ticket servers (one odd, one even) so that none is a single point of failure. Flickr described this design.

    Ids from different servers are only roughly in time order, because each server holds a block.

  6. Step 6: Snowflake: pack the time and the machine into 64 bits

    A Snowflake id (the design Twitter published) is a 64-bit number built from parts: 1 unused bit, 41 bits of time in milliseconds since a start date you choose, 10 bits for the machine number and 12 bits for a counter inside the millisecond.

    Two machines never share a machine number, and one machine never repeats a counter in the same millisecond. That makes every id unique with no talking. 41 bits of milliseconds last about 69.7 years, 1,024 machines can run at once, and each makes up to 4,096 ids per millisecond, 4,096,000 a second.

    Across 1,024 machines that is over 4,194,304,000 ids a second, more than any real system needs.

  7. Step 7: Bigger id means newer

    The time is in the top bits, so comparing two ids compares their creation times first. Sorting by id sorts by time, and "newest first" needs no extra column. You can even read the creation time back out of the id.

    New ids always go to the right end of the index, the same as with auto-increment, so inserts are fast and cache friendly. The order is exact to the millisecond only: two machines in the same millisecond give an arbitrary order.

    This is what UUIDs lacked: ids that are unique everywhere and still in time order.

  8. Step 8: What if the clock goes backwards?

    Snowflake trusts the machine's clock. A time-sync correction can move the clock back, say 2 seconds. The generator would then reuse timestamps it has already used, and with the same machine number and counter it would make ids that already exist.

    The generator therefore remembers the last timestamp it used. If the clock is behind it, it waits until the clock catches up (or refuses to make ids). Two other rules: never give two live machines the same machine number, and when the counter hits 4,096 inside one millisecond, wait for the next one.

    Clock-based ids are only as good as the clocks. Use a time source you trust, and guard against going back.

  9. Step 9: Unique ids in one picture

    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.