ToolPopToolPop
Back to BlogGuides

UUID/GUID Generator: Complete Guide to Unique Identifiers for Developers

UUIDs provide globally unique identifiers without coordination. Learn the different versions, when to use them, and how to implement them correctly.

ToolPop TeamMarch 17, 202515 min read

What is a UUID?

A UUID (Universally Unique Identifier) is a 128-bit identifier that's designed to be unique across space and time without requiring a central authority. GUIDs (Globally Unique Identifiers) are Microsoft's implementation of the same concept.

UUID Format

550e8400-e29b-41d4-a716-446655440000
|      | |  | |  | |  | |          |
|      | |  | |  | |  | +----------+-- Node (48 bits)
|      | |  | |  | +--+-- Clock sequence (14 bits)
|      | |  | +--+-- Version (4 bits) + Variant (2 bits)
|      | +--+-- Time high (16 bits)
+------+-- Time low (32 bits) + Time mid (16 bits)

Key characteristics:

  • 32 hexadecimal digits
  • 4 hyphens (8-4-4-4-12 format)
  • 36 characters total
  • Case insensitive

UUID Versions

UUID v1 (Time-based)

Generated from timestamp and MAC address.

// Example v1 UUID
"6fa459ea-ee8a-11eb-9a03-0242ac130003"
//                 ^ Version 1

Pros:

  • Sortable by creation time
  • Can extract timestamp
  • Guaranteed unique on single machine
Cons:
  • Exposes MAC address (privacy concern)
  • Predictable
  • Clock issues can cause duplicates

UUID v4 (Random)

Generated from random or pseudo-random numbers.

// Example v4 UUID
"550e8400-e29b-41d4-a716-446655440000"
//                 ^ Version 4

Pros:

  • No information leakage
  • Simple to generate
  • Most widely used
Cons:
  • Not sortable
  • Requires good random source
  • Tiny collision probability

UUID v7 (Time-ordered)

New standard combining timestamp with randomness.

// Example v7 UUID
"018e8400-e29b-71d4-a716-446655440000"
//                 ^ Version 7

Pros:

  • Sortable by creation time
  • Database index friendly
  • No MAC address exposure
  • Better than v1 for most uses
Cons:
  • Relatively new (2024 RFC)
  • Less library support currently

Other Versions

VersionMethodUse Case
v2DCE SecurityLegacy systems
v3MD5 hashDeterministic from name
v5SHA-1 hashDeterministic from name
v6Reordered v1Time-sortable v1

Generating UUIDs

JavaScript (Browser)

// Native crypto API (v4)
function generateUUID() {
  return crypto.randomUUID();
}

// Manual implementation (v4)
function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

Node.js

import { randomUUID } from 'crypto';

// Built-in (v4)
const uuid = randomUUID();

// Using uuid package
import { v4 as uuidv4, v7 as uuidv7 } from 'uuid';
const id = uuidv4();
const timeId = uuidv7();

Python

import uuid

# Version 4 (random)
uuid.uuid4()  # UUID('550e8400-e29b-41d4-a716-446655440000')

# Version 1 (time-based)
uuid.uuid1()

# Version 5 (SHA-1 from namespace + name)
uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')

# Convert to string
str(uuid.uuid4())  # '550e8400-e29b-41d4-a716-446655440000'

Java

import java.util.UUID;

// Version 4
UUID uuid = UUID.randomUUID();

// From string
UUID parsed = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");

// To string
String str = uuid.toString();

Go

import "github.com/google/uuid"

// Version 4
id := uuid.New()

// From string
parsed, err := uuid.Parse("550e8400-e29b-41d4-a716-446655440000")

// To string
str := id.String()

PostgreSQL

-- Enable extension
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Generate v4
SELECT uuid_generate_v4();

-- Generate v1
SELECT uuid_generate_v1();

-- Use as default
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name VARCHAR(100)
);

UUID vs. Other ID Strategies

Auto-increment IDs

id SERIAL PRIMARY KEY  -- 1, 2, 3, ...

AspectAuto-incrementUUID
Size4-8 bytes16 bytes
UniquenessPer tableGlobal
GuessableYesNo
GenerationDatabaseAnywhere
Merge conflictsCommonRare

Snowflake IDs (Twitter)

64-bit IDs combining timestamp + machine + sequence:

1541815603606036480

Use when:

  • Need sortable IDs
  • Have distributed system
  • Want smaller than UUID

ULID

Lexicographically sortable, 128-bit identifier:

01ARZ3NDEKTSV4RRFFQ69G5FAV

Use when:

  • Need sortable UUIDs
  • Want URL-friendly format
  • Need better index performance

NanoID

Compact, URL-friendly random IDs:

V1StGXR8_Z5jdHi6B-myT

Use when:

  • Need shorter IDs
  • URL/filename safe required
  • Less collision resistance acceptable

Database Considerations

Indexing UUIDs

Random UUIDs (v4) cause index fragmentation:

-- UUID v4: Random insertion points
-- UUID v7: Sequential insertion (better)

-- Consider ordered UUID storage
CREATE TABLE items (
  id UUID PRIMARY KEY,
  -- Store as binary for efficiency
  -- id BINARY(16) PRIMARY KEY
);

Storage Size

FormatSize
UUID string36 bytes
UUID binary16 bytes
Integer ID4-8 bytes

Query Performance

-- String comparison (slower)
WHERE id = '550e8400-e29b-41d4-a716-446655440000'

-- Binary comparison (faster)
WHERE id = UNHEX(REPLACE('550e8400-e29b-41d4-a716-446655440000', '-', ''))

Best Practices

1. Choose the Right Version

ScenarioRecommended
General purposev4 or v7
Sortable by timev7
Deterministicv5
Legacy compatibilityv1

2. Use Binary Storage When Possible

# PostgreSQL native UUID type
# MySQL BINARY(16)
# Store efficiently, query with functions

3. Validate Input

function isValidUUID(str) {
  const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return regex.test(str);
}

4. Don't Expose Internal IDs

// ❌ Exposes database structure
/api/users/1
/api/orders/2

// ✅ UUIDs hide sequence
/api/users/550e8400-e29b-41d4-a716-446655440000
/api/orders/6fa459ea-ee8a-11eb-9a03-0242ac130003

5. Generate Client-Side When Appropriate

// Offline-capable apps can generate IDs
const newItem = {
  id: crypto.randomUUID(),
  name: 'Item',
  createdAt: new Date()
};

// Sync later without conflicts
await syncToServer(newItem);

Collision Probability

UUID v4 has 122 random bits. The probability of collision:

UUIDs GeneratedCollision Probability
1 billion~0.00000000001%
1 trillion~0.00001%
2.7 quintillion50%
You'd need to generate 1 billion UUIDs per second for 86 years to have a 50% chance of collision.

Security Considerations

UUID v1 Leaks Information

// v1 UUID contains:
// - Timestamp (when created)
// - MAC address (which machine)

// Don't use v1 for:
// - Public-facing IDs
// - Security-sensitive contexts

UUIDs are Not Secrets

// ❌ Don't use UUID as password/token
const resetToken = crypto.randomUUID(); // Insufficient entropy

// ✅ Use proper crypto for secrets
const resetToken = crypto.randomBytes(32).toString('hex');

Don't Trust Client UUIDs

// Client can send any UUID
// Always validate and authorize

app.put('/api/items/:id', async (req, res) => {
  const item = await Item.findById(req.params.id);

  // Verify ownership
  if (item.userId !== req.user.id) {
    return res.status(403).json({ error: 'Forbidden' });
  }

  // Proceed with update
});

Conclusion

UUIDs are essential for modern distributed systems. Choose v4 for general use, v7 for sortable IDs, and always consider your database and performance requirements.

Use our free UUID Generator to quickly create UUIDs during development. Generate single IDs or bulk batches in any version you need.

Tags
uuid generatorguid generatorunique identifieruuid v4uuid v7random idunique id generator
Share this article

Try Our Free Tools

Put these tips into practice with our free online tools. No signup required.

Explore Tools