UUID Generator
35b05e1e-9f3b-4e69-bc55-e39e8067104e
What is UUID?
A UUID (short for Universally Unique Identifier) is a 128-bit ID written as a string that’s designed to be unique across systems, devices, and time—so you can identify something (a user, order, blog post, file, request, etc.) without worrying that another system will generate the same ID.
A UUID usually looks like this:
550e8400-e29b-41d4-a716-446655440000
What makes it useful?
- No central counter needed (unlike auto-increment IDs).
- Great for distributed apps (microservices, multiple servers, offline clients).
- Safe to generate anywhere, then store/merge later.
Why UUIDs Exist (The Problem They Solve)
When you create records in a system—users, orders, blog posts, files—each one needs an ID so you can find it again later. The simplest approach is an auto-increment number like 1, 2, 3…. That works well in a single database, but it starts to break down when your app grows.
The core problem: avoiding ID collisions
In real-world apps, data often gets created in more than one place:
- Multiple servers writing to the same system
- Microservices creating records independently
- Mobile apps creating data offline, then syncing later
- Separate databases that eventually need to merge
- Background jobs and queues creating records at the same time
If you rely on “counting up” IDs, you usually need a central authority (one database or one service) to hand out the next number. That creates two big issues:
- Coordination overhead — Every creator must ask the same source for the next ID, which adds dependency and complexity.
- Collision risk during merging — If two databases both have a record with ID 123, merging them becomes messy because you can’t tell which 123 is which.
How UUIDs solve it
UUIDs are designed so you can generate an ID anywhere—on any server, device, or service—without checking a central counter. The chance of two systems generating the same UUID is incredibly small, which means:
- You can create records independently
- You can sync or merge data without renumbering
- You reduce reliance on a single “ID generator” service
Real-world example
Imagine you have a web app server in Singapore, a worker service in the US, and a mobile app that works offline. All three might create “new order” records. With UUIDs, they can safely generate IDs locally and later save/sync them to the same database without conflicts.
Key takeaway
UUIDs exist to make identifiers globally unique without coordination, which is especially important for distributed systems, offline-first apps, and data that might be merged later.
UUID vs ID vs GUID: What’s the Difference?
These terms often get mixed up because they’re all used to identify “something.” The difference is mostly about scope (local vs global) and naming (standard vs vendor term).
ID (Identifier)
ID is the generic term. It simply means “an identifier” — any value that uniquely identifies something within a specific context.
- Can be a number (123), string (user_abc), email, slug, etc.
- Usually unique only inside one system (like one database table).
- Auto-increment IDs are common examples.
Think of ID as: a label that’s unique here.
UUID (Universally Unique Identifier)
A UUID is a specific type of ID defined by a standard, designed to be unique across different systems without coordination.
- Always 128-bit
- Usually shown as 36 characters with hyphens (format 8-4-4-4-12)
- Often generated randomly (v4) or time-ordered (v7), depending on version
Think of UUID as: an ID that’s safe to generate anywhere and still be unique globally.
GUID (Globally Unique Identifier)
A GUID is essentially the same thing as a UUID in practice. The main difference is where the term comes from:
- GUID is Microsoft’s name for a UUID-style identifier.
- Most GUIDs follow the UUID format and are also 128-bit.
- In many dev discussions, people treat GUID and UUID as interchangeable.
Think of GUID as: Microsoft’s word for UUID.
UUID Format and Structure
A UUID is a 128-bit identifier that’s usually displayed as a human-readable string with 32 hexadecimal characters (0–9, a–f) plus 4 hyphens, making it easy to copy, store, and recognize.
A typical UUID looks like this:
550e8400-e29b-41d4-a716-446655440000
How Many Characters Is a UUID?
A standard UUID string is 36 characters total:
- 32 hex characters (the actual data)
- 4 hyphens (-) for readability
So: 32 + 4 = 36 characters.
Some systems may store UUIDs without hyphens (just the 32 hex characters), but the “classic” display format is 36.
UUID Parts: 8-4-4-4-12 Breakdown
UUIDs are grouped into five sections separated by hyphens:
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
That’s the 8-4-4-4-12 pattern:
- 8 hex characters
- 4 hex characters
- 4 hex characters
- 4 hex characters
- 12 hex characters
Each hex character represents 4 bits, so 32 × 4 = 128 bits. This is why UUIDs are always 128-bit, no matter what version you use.
UUID Version and Variant Bits (Simple Explanation)
Inside a UUID, a couple of characters aren’t “random.” They store metadata that tells you what type of UUID it is and how it should be interpreted.
Version
The UUID version indicates how the UUID was generated (random, time-based, name-based, etc.). In the common format, the first character of the 3rd group shows the version.
550e8400-e29b-41d4-a716-446655440000
The third group is 41d4 → the first character is 4, so this is a Version 4 UUID (random).
- v1 = time-based (with node info)
- v4 = random
- v5 = name-based (hash)
- v7 = time-ordered (modern, great for DB indexing)
Variant
The variant indicates the internal layout rules (which “UUID flavor” it follows). Most UUIDs you see are the standard RFC 4122 variant, and it’s encoded in the first character of the 4th group.
Example: ...-a716-... → that first character is a.
For RFC 4122 UUIDs, that character is usually one of: 8, 9, a, b.
You don’t usually need to worry about variant in day-to-day coding—just know it’s one reason why certain characters show up in specific positions.
UID Versions (v1, v3, v4, v5, v7)
Not all UUIDs are generated the same way. The “version” tells you the method used to create the UUID—random, time-based, or name-based. Different versions are better for different situations (databases, URLs, distributed systems, etc.).
UUID v4 (Random)
UUID v4 is the most common version. It’s generated using random values (cryptographic random on modern platforms), making it easy to create anywhere without coordination.
- Best for: general-purpose IDs, public links, request IDs
- Pros: simple, widely supported, extremely low collision chance
- Cons: random order can hurt database index performance at scale
UUID v1 (Time-based)
UUID v1 is generated using a timestamp plus a node identifier (often derived from a network interface / MAC address, or a randomized node value depending on implementation). This makes it roughly sortable by time.
- Best for: systems that want time ordering without extra columns
- Pros: time-based ordering, low collision risk
- Cons: may leak creation time and potentially node information; not ideal for public-facing IDs
UUID v3/v5 (Name-based, Deterministic)
UUID v3 and UUID v5 are name-based, meaning they’re generated from a namespace + name (like a URL, email, or username). They are deterministic: the same input always produces the same UUID.
- v3 uses MD5 hashing
- v5 uses SHA-1 hashing (generally preferred over v3)
- Best for: stable IDs derived from known strings (idempotent creation)
- Pros: repeatable output; no need to store mapping tables
- Cons: not random; if input is guessable, output can be reproduced
UUID v7 (Time-ordered, Modern Choice)
UUID v7 is a newer version designed to be time-ordered while still being highly unique. It encodes a Unix timestamp (in milliseconds) plus random bits. The big benefit is that generated IDs are roughly sortable by creation time, which is great for databases.
- Best for: database primary keys, event IDs, logs, high-write systems
- Pros: better index locality than v4; still globally unique
- Cons: not as universally available as v4 in older libraries yet
If you want UUIDs that perform better in databases than random v4, v7 is often the modern go-to choice.
How Unique Is a UUID?
In normal use, a UUID is “unique enough” that you can treat collisions as practically impossible. The whole point of UUIDs is that many systems can generate IDs independently without accidentally creating the same one.
What is a collision?
A collision happens when two different things end up with the exact same UUID. If that happened in a database, it would be a problem because IDs are supposed to uniquely identify records.
Why collisions are extremely unlikely (especially with v4)
The most common UUID is UUID v4, which is random. Even though a UUID is 128 bits, not all bits are random because some bits are reserved for the version and variant. In practice, v4 has 122 random bits.
That means there are about 2¹²² possible v4 UUIDs — a number so huge that generating duplicates by accident is wildly unlikely.
Plain-English intuition
Think of it like this: a UUID v4 is like picking a random grain of sand from an unimaginably large beach. If many people pick grains at the same time, the odds they pick the exact same grain are still tiny.
Even if your app generates a lot of UUIDs, the probability of a collision remains extremely low unless you’re generating at absurd, internet-scale volumes for a very long time.
So should you worry about collisions?
For almost all applications: no. The bigger risks are usually:
- Using a weak random generator (not cryptographically secure)
- Manually modifying/truncating UUID strings
- Copy/paste mistakes or bugs that reuse the same value
If you generate UUIDs using modern platform APIs (like crypto.randomUUID()), collisions are not a practical concern.
Common Use Cases for UUIDs
UUIDs are popular because they let you generate IDs anywhere without relying on a single central counter. That makes them especially useful when multiple systems create data at the same time or when records need to be merged later.
8.1 Database Primary Keys
UUIDs are often used as primary keys for database rows (users, posts, orders). They’re helpful when records can be created by different services or environments (web, mobile, workers) without coordinating ID assignment.
- Great when you need global uniqueness across multiple databases.
- Useful for offline-first apps that sync later.
- Many teams prefer v7 (time-ordered) for better index performance than random v4.
8.2 Distributed Systems and Microservices
In microservices, multiple services may create related records independently. UUIDs reduce the need for a central “ID service” and help avoid collisions when services run in parallel across regions.
- Services can generate IDs locally and still stay unique.
- Easy to merge data from multiple sources without renumbering.
- Works well across multiple environments (dev/staging/prod).
8.3 Public URLs and Sharing Links
UUIDs are commonly used in public links like share URLs (e.g., invite links, password reset links, shared docs links). Compared to auto-increment IDs, UUIDs are harder to guess, which helps reduce simple “ID guessing” attacks.
- Good for shareable resources you don’t want easily enumerable.
- Often paired with auth/permissions (UUIDs are not a replacement for security).
- Common in “magic links” or one-time tokens (sometimes combined with expiry).
8.4 Request/Trace IDs (Logging & Observability)
UUIDs are great for request IDs and trace IDs. You generate one ID per incoming request, then pass it through services and logs so you can follow the full journey of a request during debugging.
- Makes debugging easier: search logs by one ID.
- Helps correlate events across services and queues.
- Works nicely with observability tools (tracing, APM, log aggregators).
8.5 File Names / Object Storage Keys
UUIDs are often used for file names or object keys in storage systems (S3, Cloud Storage, Supabase storage, etc.). This avoids naming conflicts when many uploads happen at the same time.
- Prevents collisions for uploads from multiple users.
- Avoids problems with duplicate filenames like image.png.
- Great for CDN caching and easy linking when combined with metadata in your database.
UUIDs in Databases: Pros and Cons
UUIDs work great in many systems, but they’re not automatically “better” than auto-increment IDs. In databases, the main trade-off is: UUIDs make distributed creation easy, but they can add storage and indexing costs.
9.1 Benefits (Global Uniqueness, No Central Counter)
The biggest advantage of UUIDs is that they let you create unique primary keys without relying on one central counter.
- Global uniqueness: IDs won’t collide even across multiple databases, regions, or services.
- Great for distributed writes: microservices, workers, and mobile clients can generate IDs independently.
- Easier merges: combining datasets later is simpler since IDs don’t overlap.
- Safer public exposure: UUIDs are harder to guess than sequential IDs (still use proper auth).
9.2 Downsides (Index Size, Fragmentation, Performance)
The cost of UUIDs shows up mostly in storage and index performance.
- Bigger indexes: UUID columns take more space than small integers, so indexes become larger and slower to cache.
- Random insert order (v4): purely random UUIDs spread inserts across the index, causing more page splits and fragmentation over time.
- Slower joins: larger keys can make joins and lookups a bit heavier, especially at scale.
- Human-unfriendly: UUIDs are harder to type, debug by hand, or discuss compared to simple numbers.
Tip: if you want the uniqueness of UUIDs but better index behavior, UUID v7 (time-ordered) often performs better than random v4 for primary keys.
9.3 When to Avoid UUID as Primary Key
UUIDs aren’t always the best choice. Consider avoiding UUIDs as the main primary key when:
- You have a single database and don’t need distributed/offline ID generation.
- You’re optimizing heavily for write throughput and tight index performance, and sequential IDs already work well.
- You need short, human-friendly identifiers (for receipts, invoices, support tickets).
- Your database and tooling work best with sequential keys (or you already have mature patterns around numeric IDs).
A common compromise is: use a fast numeric primary key internally, and use UUIDs externally (public URLs), or use a time-ordered UUID version (like v7) when you truly need global uniqueness.
UUID Best Practices
UUIDs are easy to use, but the best results come from choosing the right version, storing them efficiently, and thinking about performance when UUIDs become primary keys. Below are practical best practices you can apply in most projects.
Which UUID Version Should You Use?
Pick the version based on your needs:
- Use v4 when you want a simple, widely supported random ID for general use (most apps).
- Use v7 when UUIDs will be a primary key in a database and you care about write/index performance (time-ordered UUIDs help).
- Use v5 when you need deterministic IDs (same input → same UUID), such as generating IDs from a stable name like a URL or email.
- Be cautious with v1 for public IDs since it can reveal creation time and may include node-related data depending on implementation.
UUIDs for URLs: Security & Guessability
UUIDs are often used in public URLs because they’re hard to guess compared to sequential IDs. This helps prevent simple “ID enumeration” (trying /users/1, /users/2, etc.).
- UUIDs improve guessability resistance, but they are not a security system.
- Always enforce authentication and authorization for protected data.
- For sensitive links (password reset, invites), add expiry and possibly a one-time-use token.
If the link must be unguessable and time-limited, treat it like a token, not just a “record ID”.
Store as TEXT vs BINARY
UUIDs can be stored as a string (TEXT/CHAR) or as a compact binary value. The best option depends on your database and how much you care about performance and storage.
- TEXT/CHAR: easiest to read and debug, but uses more space (includes hyphens if stored in canonical form).
- BINARY (16 bytes): smaller and often faster for indexes and joins, but harder to read without formatting.
- If your DB has a native UUID type (like PostgreSQL), use it—it usually stores efficiently while still being convenient to query.
Rule of thumb: use the database’s native UUID type if available; otherwise consider binary storage if you’re optimizing at scale.
Indexing Tips (v4 vs v7)
Index performance is where UUID choices matter most:
- v4 is random, so inserts hit many parts of the index. Over time this can cause more fragmentation and slower writes in large tables.
- v7 is time-ordered, so new rows tend to insert near the “end” of the index, improving locality and often improving write performance.
- If you must use v4 as a primary key, make sure you have enough memory for indexes and monitor write performance as data grows.
- Consider adding a separate created_at column for time sorting, even if you use UUIDs.
Practical recommendation: v4 for general IDs, v7 for database primary keys at scale.
How to Generate a UUID (Examples)
Generating a UUID is usually built-in or available through a small library depending on your stack. Below are practical examples you can copy for common environments.
JavaScript / Node.js
Modern browsers and Node.js support UUID generation through the Web Crypto API. This is the simplest and most reliable option because it uses cryptographically secure randomness.
// Browser + modern Node.js const id = crypto.randomUUID(); console.log(id);
If you’re on an older Node.js version, you can use the popular uuid package:
import { v4 as uuidv4 } from "uuid";
const id = uuidv4();
console.log(id);PostgreSQL
PostgreSQL can generate UUIDs using extensions. Two common approaches are pgcrypto (recommended) or uuid-ossp.
Using pgcrypto:
-- Enable extension (once per database) CREATE EXTENSION IF NOT EXISTS pgcrypto; -- Generate UUID SELECT gen_random_uuid(); -- Example column default CREATE TABLE users ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), name text NOT NULL );
Using uuid-ossp:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; SELECT uuid_generate_v4();
MySQL
MySQL has a built-in function UUID() that returns a UUID string.
SELECT UUID(); -- Example: default value (common approach is to set it in app code) -- MySQL defaults for UUID can vary by version/usage, so many teams generate in the app.
If you want more compact storage, you can store UUIDs in BINARY(16) and convert using UUID_TO_BIN() / BIN_TO_UUID() (MySQL 8+).
-- Store compactly (MySQL 8+) SELECT UUID_TO_BIN(UUID()); -- Convert back to string SELECT BIN_TO_UUID(UUID_TO_BIN(UUID()));
Python
Python includes UUID generation in the standard library via the uuid module.
import uuid # Random UUID (v4) id = uuid.uuid4() print(id) # String form print(str(id))
UUID Examples You Can Copy
Here are real-looking UUID examples you can copy for testing, UI mockups, seed data, and documentation.
UUID v4-style (random) examples
c1a9b0b4-2f1f-4c7e-9d5d-1c2f3a4b5c6d 8f3c2a10-6c8e-4f2c-b1d2-9a7e6c5b4a3f 2b7d9c61-1f4a-4c0d-8a2f-7e9c1b3a5d6f a4f6e3d2-9b1c-4a7f-8d3e-5c2b1a0f9e8d 0d6a1c92-7e3b-4b8a-9c1e-2f5d7a8b3c4e
Tip: These follow the usual UUID formatting and look like v4 (the “4” in the 3rd group).
UUID without hyphens (compact style)
c1a9b0b42f1f4c7e9d5d1c2f3a4b5c6d 8f3c2a106c8e4f2cb1d29a7e6c5b4a3f 2b7d9c611f4a4c0d8a2f7e9c1b3a5d6f
Some systems store UUIDs like this internally, then format with hyphens for display.
Uppercase UUID examples (sometimes used in legacy systems)
C1A9B0B4-2F1F-4C7E-9D5D-1C2F3A4B5C6D 8F3C2A10-6C8E-4F2C-B1D2-9A7E6C5B4A3F
UUIDs are case-insensitive in hex, but most apps standardize on lowercase.
“Nil” UUID (all zeros)
00000000-0000-0000-0000-000000000000
This special UUID is often used as a placeholder or “empty” value (but don’t use it as a real unique ID).
13. Troubleshooting and Common Mistakes
UUIDs are simple, but a few common mistakes can cause bugs in production—especially when UUIDs are stored in a database, used in URLs, or generated across different environments.
1) Using weak randomness (or Math.random)
Don’t generate UUID-like strings using Math.random(). It’s not designed for strong uniqueness and can repeat more easily than you expect.
Use platform APIs like crypto.randomUUID() (browser/Node) or trusted UUID libraries.
2) Truncating UUIDs to “make them shorter”
Cutting a UUID down (like keeping only the first 8 characters) massively increases the chance of collisions. If you need shorter IDs, use a different ID scheme designed for shortness (like ULID/KSUID/nanoid), not a chopped UUID.
3) Mixing formats (with hyphens vs without)
Some systems store UUIDs without hyphens (32 chars), while others use the canonical 36-char format. If you mix them, comparisons can fail and APIs can reject input.
- Choose one format for your API boundary (usually the 36-char hyphenated format).
- Normalize input before saving or comparing.
4) Treating UUIDs as security tokens
UUIDs (especially v4) are hard to guess, but they’re not a replacement for authentication/authorization. A UUID in a URL should not automatically grant access to private data.
If you need a secure share link, use proper permissions and add controls like expiry and one-time usage.
5) Database performance surprises (especially with v4)
Random UUIDs (v4) can cause index fragmentation and slower writes on large tables. This isn’t a “bug,” but it can look like one when traffic grows.
- If UUIDs are primary keys at scale, consider v7 (time-ordered) for better index locality.
- Monitor index size and write latency as the table grows.
6) Storing UUIDs inefficiently
Storing UUIDs as long strings can increase storage and index size. If your database supports a native UUID type (like PostgreSQL), use it. Some databases also support compact binary storage (16 bytes).
7) Case sensitivity and validation issues
Hex is case-insensitive, but some validators expect lowercase, uppercase, or a strict format. If your app rejects valid UUIDs, it’s often a formatting or validation rule mismatch.
- Standardize on lowercase + hyphens for APIs.
- Validate using a reliable library or strict regex.
8) Accidentally reusing the same UUID
Many “collision” reports are actually app bugs—like caching a UUID and reusing it for multiple records, or generating it once at module load instead of per request.
Make sure UUID generation happens at the right moment (e.g., when creating a new record), not at import-time.
Key takeaway
Most UUID issues come from formatting differences, weak generators, or database indexing behavior—not from UUIDs themselves. Use secure generators, don’t truncate, and pick the right version for your database needs.