🍋
Menu
How-To Beginner 1 min read 197 words

How to Generate UUIDs and Unique Identifiers

Unique identifiers are fundamental to distributed systems. Learn the differences between UUID v4, v7, ULID, and other ID formats and when to use each.

Key Takeaways

  • In distributed systems, databases, and APIs, every record needs a unique identifier.
  • UUID v4 generates 122 bits of randomness, producing identifiers like `550e8400-e29b-41d4-a716-446655440000`.
  • UUID v7 embeds a Unix timestamp in the first 48 bits, making IDs sortable by creation time.
  • ULID (Universally Unique Lexicographically Sortable Identifier) encodes time and randomness in a 26-character Crockford Base32 string.

Why Unique IDs Matter

In distributed systems, databases, and APIs, every record needs a unique identifier. Auto-incrementing integers work for single databases but fail in distributed environments where multiple systems create records simultaneously.

UUID v4: Random

UUID v4 generates 122 bits of randomness, producing identifiers like 550e8400-e29b-41d4-a716-446655440000. The collision probability is astronomically low — you'd need to generate 2.71 quintillion UUIDs to have a 50% chance of collision.

UUID v7: Time-Sorted

UUID v7 embeds a Unix timestamp in the first 48 bits, making IDs sortable by creation time. This is ideal for database primary keys because sorted inserts are more efficient for B-tree indexes.

ULID: Lexicographic Sorting

ULID (Universally Unique Lexicographically Sortable Identifier) encodes time and randomness in a 26-character Crockford Base32 string. ULIDs sort correctly as strings, avoiding the need for special comparison logic.

Choosing the Right Format

Format Sortable Size URL-safe
UUID v4 No 36 chars No (hyphens)
UUID v7 Yes 36 chars No
ULID Yes 26 chars Yes
Snowflake Yes 19 digits Yes

Verwandte Tools

Verwandte Formate

Verwandte Anleitungen