Data Structures5 min readLast updated: Sat Mar 23 2024 00:00:00 GMT+0000 (Coordinated Universal Time)

What is a UUID / GUID?

In a traditional database, we use an Auto-Increment Integer for IDs: 1, 2, 3, 4...
This has a problem: It requires a central database to count. You cannot generate ID #5 on your phone offline, because you don't know if someone else already took #5.

The Solution: UUID (Universally Unique Identifier)

A UUID is a 128-bit number, usually displayed as a 36-character hexadecimal string:
123e4567-e89b-12d3-a456-426614174000

Why is it unique?

It is generated using a combination of:

  1. Current timestamp.
  2. Random numbers.
  3. Network card MAC address (sometimes).

The total number of possible UUIDs is $2^{128}$. This number is so astronomically large that you could generate 1 billion UUIDs per second for 100 years and the probability of generating the same one twice is virtually zero.

Pros and Cons

  • Pros: Decentralized. You can generate an ID on a mobile phone while offline, sync it later, and guarantee no conflicts.
  • Cons: They are large (16 bytes vs 4 bytes for an integer). They are hard to type or read over the phone. They fragment database indexes.

Use integers for internal efficiency. Use UUIDs for public URLs and distributed systems.