Skip to content

Orbit2x/uuid-generator-unique-identifiers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

UUID Generator - Complete Guide to Unique Identifiers

UUID Generator Free Tool

Need globally unique identifiers for databases, APIs, or distributed systems? Use the free UUID Generator to instantly generate UUIDs (v1, v4, v5, v7) with validation, bulk generation, and analysis tools.

What is a UUID?

A UUID (Universally Unique Identifier) is a 128-bit value used to uniquely identify information in computer systems. UUIDs are guaranteed to be unique across space and time without requiring a central authority.

UUID Format

xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

Where:
x = hexadecimal digit (0-9, a-f)
M = UUID version (1, 3, 4, 5, 6, 7, 8)
N = UUID variant (8, 9, a, b)

Example: 550e8400-e29b-41d4-a716-446655440000

Generate UUIDs instantly: UUID Generator Tool


UUID Versions Comparison

Version Algorithm Use Case Uniqueness Performance
UUID v1 Timestamp + MAC address Databases (time-ordered) Guaranteed Fast
UUID v3 MD5 hash of namespace + name Deterministic (legacy) Namespace-based Medium
UUID v4 Random (122 bits) General purpose Probabilistic Very Fast
UUID v5 SHA-1 hash of namespace + name Deterministic (modern) Namespace-based Medium
UUID v6 Reordered v1 (better sorting) Time-ordered databases Guaranteed Fast
UUID v7 Unix timestamp + random Modern time-ordered Guaranteed Fast

Recommendation: Use v4 for general use, v7 for time-ordered data (2024+), v5 for deterministic generation.

Compare versions: UUID Generator with Analysis


UUID Generation Code Examples

JavaScript (Node.js) - UUID v4

/**
 * Generate UUID v4 (Random) - Node.js
 * Uses crypto.randomUUID() (Node 16.7.0+)
 */

const crypto = require('crypto');

// Method 1: Native crypto.randomUUID()
function generateUUIDv4() {
  return crypto.randomUUID();
}

console.log(generateUUIDv4());
// Output: f47ac10b-58cc-4372-a567-0e02b2c3d479

// Method 2: Manual implementation
function generateUUIDv4Manual() {
  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);
  });
}

console.log(generateUUIDv4Manual());
// Output: 7c9e6679-7425-40de-944b-e07fc1f90ae7

// Bulk generation
function generateBulkUUIDs(count) {
  return Array.from({ length: count }, () => crypto.randomUUID());
}

const uuids = generateBulkUUIDs(10);
console.log(uuids);

// Generate online: https://orbit2x.com/uuid-generator

JavaScript (Browser) - UUID v4

/**
 * Generate UUID v4 in browser using Web Crypto API
 * Works in all modern browsers
 */

function generateUUID() {
  // Use crypto.randomUUID() if available (modern browsers)
  if (crypto.randomUUID) {
    return crypto.randomUUID();
  }

  // Fallback for older browsers
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
    (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  );
}

// Example usage
const id = generateUUID();
console.log(`Generated UUID: ${id}`);
// Output: Generated UUID: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d

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

console.log(isValidUUID(id)); // true
console.log(isValidUUID('invalid')); // false

// Try online: https://orbit2x.com/uuid-generator

Python - All UUID Versions

#!/usr/bin/env python3
"""
UUID Generator - Python Implementation
Supports UUID v1, v3, v4, v5
"""

import uuid
import time
from typing import List

class UUIDGenerator:
    """UUID generation and validation utilities"""

    # Namespaces for UUID v3/v5
    NAMESPACE_DNS = uuid.NAMESPACE_DNS
    NAMESPACE_URL = uuid.NAMESPACE_URL
    NAMESPACE_OID = uuid.NAMESPACE_OID
    NAMESPACE_X500 = uuid.NAMESPACE_X500

    @staticmethod
    def generate_v1() -> str:
        """
        Generate UUID v1 (Timestamp + MAC address)
        Time-ordered, but reveals MAC address
        """
        return str(uuid.uuid1())

    @staticmethod
    def generate_v3(namespace: uuid.UUID, name: str) -> str:
        """
        Generate UUID v3 (MD5 hash of namespace + name)
        Deterministic - same input always produces same UUID
        """
        return str(uuid.uuid3(namespace, name))

    @staticmethod
    def generate_v4() -> str:
        """
        Generate UUID v4 (Random)
        Most common version, 122 random bits
        """
        return str(uuid.uuid4())

    @staticmethod
    def generate_v5(namespace: uuid.UUID, name: str) -> str:
        """
        Generate UUID v5 (SHA-1 hash of namespace + name)
        Deterministic, preferred over v3
        """
        return str(uuid.uuid5(namespace, name))

    @staticmethod
    def generate_bulk(count: int, version: int = 4) -> List[str]:
        """Generate multiple UUIDs at once"""
        if version == 1:
            return [str(uuid.uuid1()) for _ in range(count)]
        elif version == 4:
            return [str(uuid.uuid4()) for _ in range(count)]
        else:
            raise ValueError("Bulk generation only supports v1 and v4")

    @staticmethod
    def validate(uuid_string: str) -> bool:
        """Validate UUID format"""
        try:
            uuid.UUID(uuid_string)
            return True
        except ValueError:
            return False

    @staticmethod
    def get_version(uuid_string: str) -> int:
        """Extract UUID version"""
        try:
            return uuid.UUID(uuid_string).version
        except ValueError:
            return -1

    @staticmethod
    def get_timestamp(uuid_v1_string: str) -> float:
        """Extract timestamp from UUID v1"""
        try:
            uuid_obj = uuid.UUID(uuid_v1_string)
            if uuid_obj.version != 1:
                raise ValueError("Only UUID v1 contains timestamp")
            # UUID v1 timestamp is 100-nanosecond intervals since 1582-10-15
            timestamp = (uuid_obj.time - 0x01b21dd213814000) / 10000000
            return timestamp
        except Exception as e:
            raise ValueError(f"Invalid UUID v1: {e}")

# Example usage
if __name__ == "__main__":
    gen = UUIDGenerator()

    print("=== UUID v1 (Timestamp + MAC) ===")
    uuid_v1 = gen.generate_v1()
    print(f"UUID v1: {uuid_v1}")
    print(f"Version: {gen.get_version(uuid_v1)}")
    print(f"Timestamp: {time.ctime(gen.get_timestamp(uuid_v1))}")

    print("\n=== UUID v3 (MD5 hash) ===")
    uuid_v3 = gen.generate_v3(gen.NAMESPACE_DNS, "example.com")
    print(f"UUID v3 (DNS:example.com): {uuid_v3}")
    print(f"Same input: {gen.generate_v3(gen.NAMESPACE_DNS, 'example.com')}")
    print("(Always produces same UUID for same input)")

    print("\n=== UUID v4 (Random) ===")
    uuid_v4 = gen.generate_v4()
    print(f"UUID v4: {uuid_v4}")
    print(f"Another v4: {gen.generate_v4()}")
    print("(Each call produces different UUID)")

    print("\n=== UUID v5 (SHA-1 hash) ===")
    uuid_v5 = gen.generate_v5(gen.NAMESPACE_URL, "https://orbit2x.com")
    print(f"UUID v5 (URL:orbit2x.com): {uuid_v5}")

    print("\n=== Bulk Generation ===")
    bulk_uuids = gen.generate_bulk(5, version=4)
    for i, u in enumerate(bulk_uuids, 1):
        print(f"{i}. {u}")

    print("\n=== Validation ===")
    print(f"Valid: {gen.validate(uuid_v4)}")
    print(f"Invalid: {gen.validate('not-a-uuid')}")

    print("\n👉 Generate online: https://orbit2x.com/uuid-generator")

Output:

=== UUID v1 (Timestamp + MAC) ===
UUID v1: 6ba7b810-9dad-11d1-80b4-00c04fd430c8
Version: 1
Timestamp: Fri Jan  3 00:15:32 2026

=== UUID v3 (MD5 hash) ===
UUID v3 (DNS:example.com): 9073926b-929f-31c2-abc9-fad77ae3e8eb
Same input: 9073926b-929f-31c2-abc9-fad77ae3e8eb
(Always produces same UUID for same input)

=== UUID v4 (Random) ===
UUID v4: f47ac10b-58cc-4372-a567-0e02b2c3d479
Another v4: 7c9e6679-7425-40de-944b-e07fc1f90ae7
(Each call produces different UUID)

=== UUID v5 (SHA-1 hash) ===
UUID v5 (URL:orbit2x.com): a6edc906-2f9f-5fb2-a373-efac406f0ef2

👉 Generate online: https://orbit2x.com/uuid-generator

Go - UUID Generator

package main

import (
    "fmt"
    "github.com/google/uuid"
    "time"
)

// UUIDGenerator provides UUID generation utilities
type UUIDGenerator struct{}

// GenerateV1 creates UUID v1 (timestamp + MAC)
func (g *UUIDGenerator) GenerateV1() string {
    return uuid.Must(uuid.NewUUID()).String()
}

// GenerateV4 creates UUID v4 (random)
func (g *UUIDGenerator) GenerateV4() string {
    return uuid.New().String()
}

// GenerateV5 creates UUID v5 (SHA-1 hash)
func (g *UUIDGenerator) GenerateV5(namespace uuid.UUID, name string) string {
    return uuid.NewSHA1(namespace, []byte(name)).String()
}

// GenerateBulk creates multiple UUIDs
func (g *UUIDGenerator) GenerateBulk(count int) []string {
    uuids := make([]string, count)
    for i := 0; i < count; i++ {
        uuids[i] = uuid.New().String()
    }
    return uuids
}

// Validate checks if string is valid UUID
func (g *UUIDGenerator) Validate(uuidStr string) bool {
    _, err := uuid.Parse(uuidStr)
    return err == nil
}

// GetVersion extracts UUID version
func (g *UUIDGenerator) GetVersion(uuidStr string) (int, error) {
    u, err := uuid.Parse(uuidStr)
    if err != nil {
        return -1, err
    }
    return int(u.Version()), nil
}

// GetTimestamp extracts timestamp from UUID v1
func (g *UUIDGenerator) GetTimestamp(uuidStr string) (time.Time, error) {
    u, err := uuid.Parse(uuidStr)
    if err != nil {
        return time.Time{}, err
    }

    if u.Version() != 1 {
        return time.Time{}, fmt.Errorf("only UUID v1 contains timestamp")
    }

    // Extract timestamp from UUID v1
    timestamp := u.Time()
    // Convert 100-nanosecond intervals since 1582-10-15 to Unix time
    unixTime := timestamp.UnixTime()
    return time.Unix(unixTime/1e9, unixTime%1e9), nil
}

func main() {
    gen := UUIDGenerator{}

    fmt.Println("=== UUID v1 (Timestamp + MAC) ===")
    uuidV1 := gen.GenerateV1()
    fmt.Printf("UUID v1: %s\n", uuidV1)
    version, _ := gen.GetVersion(uuidV1)
    fmt.Printf("Version: %d\n", version)

    fmt.Println("\n=== UUID v4 (Random) ===")
    uuidV4 := gen.GenerateV4()
    fmt.Printf("UUID v4: %s\n", uuidV4)
    fmt.Printf("Another v4: %s\n", gen.GenerateV4())

    fmt.Println("\n=== UUID v5 (SHA-1 hash) ===")
    uuidV5 := gen.GenerateV5(uuid.NameSpaceDNS, "example.com")
    fmt.Printf("UUID v5 (DNS:example.com): %s\n", uuidV5)
    fmt.Printf("Same input: %s\n", gen.GenerateV5(uuid.NameSpaceDNS, "example.com"))

    fmt.Println("\n=== Bulk Generation ===")
    bulkUUIDs := gen.GenerateBulk(5)
    for i, u := range bulkUUIDs {
        fmt.Printf("%d. %s\n", i+1, u)
    }

    fmt.Println("\n=== Validation ===")
    fmt.Printf("Valid: %v\n", gen.Validate(uuidV4))
    fmt.Printf("Invalid: %v\n", gen.Validate("not-a-uuid"))

    fmt.Println("\n👉 Generate online: https://orbit2x.com/uuid-generator")
}

PHP - UUID Generator

<?php
/**
 * UUID Generator - PHP Implementation
 * Supports UUID v4 (random) and v5 (SHA-1 hash)
 */

class UUIDGenerator {
    // Standard namespaces for UUID v5
    const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
    const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
    const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8';
    const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8';

    /**
     * Generate UUID v4 (random)
     */
    public static function generateV4(): string {
        $data = random_bytes(16);

        // Set version (4) and variant (RFC 4122)
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    /**
     * Generate UUID v5 (SHA-1 hash of namespace + name)
     */
    public static function generateV5(string $namespace, string $name): string {
        // Convert namespace to binary
        $nhex = str_replace(['-', '{', '}'], '', $namespace);
        $nstr = '';
        for ($i = 0; $i < strlen($nhex); $i += 2) {
            $nstr .= chr(hexdec($nhex[$i] . $nhex[$i + 1]));
        }

        // Calculate hash
        $hash = sha1($nstr . $name);

        // Set version (5) and variant
        return sprintf(
            '%08s-%04s-%04x-%04x-%012s',
            substr($hash, 0, 8),
            substr($hash, 8, 4),
            (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,
            (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,
            substr($hash, 20, 12)
        );
    }

    /**
     * Generate bulk UUIDs
     */
    public static function generateBulk(int $count): array {
        return array_map(fn() => self::generateV4(), range(1, $count));
    }

    /**
     * Validate UUID format
     */
    public static function validate(string $uuid): bool {
        return (bool) preg_match(
            '/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
            $uuid
        );
    }

    /**
     * Get UUID version
     */
    public static function getVersion(string $uuid): int {
        if (!self::validate($uuid)) {
            return -1;
        }
        return (int) $uuid[14];
    }
}

// Example usage
echo "=== UUID v4 (Random) ===\n";
$uuidV4 = UUIDGenerator::generateV4();
echo "UUID v4: {$uuidV4}\n";
echo "Version: " . UUIDGenerator::getVersion($uuidV4) . "\n";

echo "\n=== UUID v5 (SHA-1 hash) ===\n";
$uuidV5 = UUIDGenerator::generateV5(UUIDGenerator::NAMESPACE_DNS, 'example.com');
echo "UUID v5 (DNS:example.com): {$uuidV5}\n";
echo "Same input: " . UUIDGenerator::generateV5(UUIDGenerator::NAMESPACE_DNS, 'example.com') . "\n";

echo "\n=== Bulk Generation ===\n";
$bulkUUIDs = UUIDGenerator::generateBulk(5);
foreach ($bulkUUIDs as $i => $uuid) {
    echo ($i + 1) . ". {$uuid}\n";
}

echo "\n=== Validation ===\n";
echo "Valid: " . (UUIDGenerator::validate($uuidV4) ? 'true' : 'false') . "\n";
echo "Invalid: " . (UUIDGenerator::validate('not-a-uuid') ? 'true' : 'false') . "\n";

echo "\n👉 Generate online: https://orbit2x.com/uuid-generator\n";
?>

UUID v7 (2024+) - Time-Ordered with Random

UUID v7 is the newest version (RFC 9562, 2024), combining Unix timestamp with random data for time-ordered, globally unique IDs.

UUID v7 Structure

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           unix_ts_ms                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          unix_ts_ms           |  ver  |       rand_a          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|var|                        rand_b                             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                            rand_b                             |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

unix_ts_ms: 48-bit Unix timestamp in milliseconds
ver: 4-bit version (0111 for v7)
rand_a: 12-bit random data
var: 2-bit variant (10 for RFC 4122)
rand_b: 62-bit random data

JavaScript UUID v7 Implementation

/**
 * Generate UUID v7 (Unix timestamp + random)
 * RFC 9562 (2024) - Time-ordered for database indexing
 */
function generateUUIDv7() {
  // Get current timestamp in milliseconds
  const timestamp = BigInt(Date.now());

  // Generate random bytes
  const randomBytes = crypto.getRandomValues(new Uint8Array(10));

  // Build UUID v7
  const timestampHex = timestamp.toString(16).padStart(12, '0');

  // Extract parts
  const timeLow = timestampHex.slice(0, 8);
  const timeMid = timestampHex.slice(8, 12);

  // Version 7 (0111) in most significant 4 bits
  const timeHiAndVersion = (parseInt(timestampHex.slice(12, 16) || '0', 16) & 0x0fff | 0x7000)
    .toString(16).padStart(4, '0');

  // Variant (10) in most significant 2 bits
  const clockSeqHiAndReserved = ((randomBytes[0] & 0x3f) | 0x80)
    .toString(16).padStart(2, '0');

  const clockSeqLow = randomBytes[1].toString(16).padStart(2, '0');

  // Remaining random bytes
  const node = Array.from(randomBytes.slice(2))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');

  return `${timeLow}-${timeMid}-${timeHiAndVersion}-${clockSeqHiAndReserved}${clockSeqLow}-${node}`;
}

// Example: Generate 5 UUID v7s (notice time-ordering)
console.log("=== UUID v7 (Time-Ordered) ===");
for (let i = 0; i < 5; i++) {
  console.log(generateUUIDv7());
  // Small delay to show timestamp progression
  await new Promise(resolve => setTimeout(resolve, 10));
}

// Output (notice first segment increases over time):
// 018d3f5c-8a23-7f1a-9b4e-123456789abc
// 018d3f5c-8a2d-7c2f-a3d5-234567890bcd
// 018d3f5c-8a37-7e4b-b1c6-345678901cde
// 018d3f5c-8a41-7a5c-c2d7-456789012def
// 018d3f5c-8a4b-7b6d-d3e8-567890123ef0

// Try online: https://orbit2x.com/uuid-generator

Generate UUID v7 online: UUID Generator Tool


UUID Use Cases

1. Database Primary Keys

Problem: Auto-increment IDs don't work well in distributed databases.

Solution: Use UUID v4 or v7 for globally unique, decentralized IDs.

-- PostgreSQL with UUID
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Insert without specifying ID
INSERT INTO users (email) VALUES ('user@example.com');

-- Query by UUID
SELECT * FROM users WHERE id = '550e8400-e29b-41d4-a716-446655440000';

Advantages:

  • ✅ Globally unique (no collisions in distributed systems)
  • ✅ Can generate client-side (no database round-trip)
  • ✅ Non-sequential (harder to enumerate)

Disadvantages:

  • ❌ Larger storage (16 bytes vs 4/8 bytes for INT/BIGINT)
  • ❌ Slower indexing (random order, except v7)

Recommendation: Use UUID v7 for time-ordered database indexing (best of both worlds).

2. API Request IDs

Problem: Track API requests across microservices.

Solution: Generate UUID for each request.

// Express.js middleware
app.use((req, res, next) => {
  req.id = crypto.randomUUID();
  res.setHeader('X-Request-ID', req.id);
  console.log(`[${req.id}] ${req.method} ${req.url}`);
  next();
});

// Example log output:
// [550e8400-e29b-41d4-a716-446655440000] GET /api/users
// [7c9e6679-7425-40de-944b-e07fc1f90ae7] POST /api/orders

3. Session IDs

Problem: Need secure, unique session identifiers.

Solution: Use UUID v4 for session tokens (better than sequential IDs).

import uuid
from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'your-secret-key'

@app.route('/login', methods=['POST'])
def login():
    # Generate session ID
    session_id = str(uuid.uuid4())
    session['id'] = session_id
    session['user'] = request.form['username']

    return {'session_id': session_id}

4. File Upload Naming

Problem: Avoid filename collisions when users upload files.

Solution: Use UUID as filename.

const multer = require('multer');
const { v4: uuidv4 } = require('uuid');
const path = require('path');

const storage = multer.diskStorage({
  destination: './uploads/',
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const filename = `${uuidv4()}${ext}`;
    cb(null, filename);
  }
});

const upload = multer({ storage });

// Upload: photo.jpg → 550e8400-e29b-41d4-a716-446655440000.jpg

5. Distributed Caching Keys

Problem: Generate cache keys for distributed systems (Redis, Memcached).

Solution: Use UUID v5 for deterministic, namespace-based keys.

import uuid
import redis

# Connect to Redis
r = redis.Redis(host='localhost', port=6379)

# Generate deterministic cache key
CACHE_NAMESPACE = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')

def get_cache_key(resource_type, resource_id):
    """Generate UUID v5 cache key"""
    name = f"{resource_type}:{resource_id}"
    return str(uuid.uuid5(CACHE_NAMESPACE, name))

# Example: Cache user data
user_id = 12345
cache_key = get_cache_key('user', user_id)
# Always produces: a6edc906-2f9f-5fb2-a373-efac406f0ef2

r.set(cache_key, '{"name": "John", "email": "john@example.com"}', ex=3600)

Generate cache keys: UUID Generator with Namespaces


UUID Best Practices

✅ Do's

  1. Use UUID v4 for general purpose - Random, secure, no dependencies
  2. Use UUID v7 for database primary keys - Time-ordered, better indexing (2024+)
  3. Use UUID v5 for deterministic generation - Same input always produces same UUID
  4. Store as binary (16 bytes) - More efficient than string (36 bytes)
  5. Index UUID columns - Essential for query performance
  6. Generate client-side when possible - Reduces database load

❌ Don'ts

  1. Don't use UUID v1 if privacy matters - Reveals MAC address and timestamp
  2. Don't use UUID v3 - MD5 is deprecated, use v5 instead
  3. Don't rely on lexicographic sorting - UUIDs v4 are random (use v7 for sorting)
  4. Don't expose UUIDs in URLs for sensitive data - Use signed tokens instead
  5. Don't assume collision is impossible - Probability is extremely low but not zero

UUID Collision Probability

How Likely is a UUID Collision?

UUID v4 (122 random bits):

Total possible UUIDs: 2^122 ≈ 5.3 × 10^36

Probability of collision:
- 1 billion UUIDs: ~0.00000000000001% (1 in 10^18)
- 1 trillion UUIDs: ~0.00000001% (1 in 10^12)

To have 50% chance of collision:
You need to generate 2.71 × 10^18 UUIDs (2.71 quintillion)

Comparison:

  • Chance of UUID collision: 1 in 10^18
  • Chance of winning lottery jackpot: 1 in 10^7 (100 billion times more likely!)
  • Chance of being struck by lightning: 1 in 10^6 (1 trillion times more likely!)

Conclusion: UUID collisions are so unlikely they can be considered impossible in practice.


UUID Format Validation

Validation Regex

^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

Breakdown:
[0-9a-f]{8}     - 8 hex digits (time_low)
[0-9a-f]{4}     - 4 hex digits (time_mid)
[1-5][0-9a-f]{3} - Version (1-5) + 3 hex digits
[89ab][0-9a-f]{3} - Variant (8, 9, a, b) + 3 hex digits
[0-9a-f]{12}    - 12 hex digits (node)

Validate UUIDs online: UUID Generator with Validator

JavaScript Validator

function validateUUID(uuid) {
  const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

  if (!regex.test(uuid)) {
    return { valid: false, error: 'Invalid UUID format' };
  }

  const version = parseInt(uuid[14], 16);
  const variant = parseInt(uuid[19], 16);

  return {
    valid: true,
    version,
    variant: variant >= 8 && variant <= 11 ? 'RFC 4122' : 'Unknown'
  };
}

// Test cases
console.log(validateUUID('550e8400-e29b-41d4-a716-446655440000'));
// { valid: true, version: 4, variant: 'RFC 4122' }

console.log(validateUUID('not-a-uuid'));
// { valid: false, error: 'Invalid UUID format' }

// Try online: https://orbit2x.com/uuid-generator

UUID Conversion & Formatting

Convert UUID to Different Formats

class UUIDFormatter {
  /**
   * Convert UUID to different formats
   */
  static toHex(uuid) {
    return uuid.replace(/-/g, '');
  }

  static toBase64(uuid) {
    const hex = this.toHex(uuid);
    const bytes = hex.match(/.{2}/g).map(b => parseInt(b, 16));
    return btoa(String.fromCharCode(...bytes));
  }

  static toBinary(uuid) {
    const hex = this.toHex(uuid);
    return BigInt('0x' + hex).toString(2).padStart(128, '0');
  }

  static toURN(uuid) {
    return `urn:uuid:${uuid}`;
  }

  static fromHex(hex) {
    return [
      hex.slice(0, 8),
      hex.slice(8, 12),
      hex.slice(12, 16),
      hex.slice(16, 20),
      hex.slice(20, 32)
    ].join('-');
  }
}

// Example conversions
const uuid = '550e8400-e29b-41d4-a716-446655440000';

console.log('UUID:', uuid);
console.log('Hex:', UUIDFormatter.toHex(uuid));
// 550e8400e29b41d4a716446655440000

console.log('Base64:', UUIDFormatter.toBase64(uuid));
// VQ6EAOKbQdSnFkRmVUQAAA==

console.log('Binary:', UUIDFormatter.toBinary(uuid).slice(0, 32) + '...');
// 01010101000011101000010000000000...

console.log('URN:', UUIDFormatter.toURN(uuid));
// urn:uuid:550e8400-e29b-41d4-a716-446655440000

// Convert online: https://orbit2x.com/uuid-generator

Tools & Resources

Online UUID Tools

UUID Libraries

JavaScript/Node.js:

  • uuid - Most popular UUID library
  • Native crypto.randomUUID() (Node 16.7.0+, browsers)

Python:

  • Built-in uuid module (standard library)

Go:

PHP:


FAQ

Q: Which UUID version should I use?

A:

  • UUID v4 - General purpose, random (most common)
  • UUID v7 - Database primary keys, time-ordered indexing (2024+)
  • UUID v5 - Deterministic generation (same input → same UUID)
  • UUID v1 - Avoid unless you need timestamp + MAC address

Generate all versions: UUID Generator Tool

Q: Are UUIDs guaranteed unique?

A: UUID v1 is guaranteed unique (timestamp + MAC). UUID v4 is probabilistically unique with collision chance of ~1 in 10^18 (effectively impossible). For absolute guarantee, use centralized ID generation or UUID v7.

Q: Can I use UUIDs as database primary keys?

A: Yes! Use UUID v7 for best performance (time-ordered, better indexing). Store as BINARY(16) or native UUID type for efficiency.

Q: How do I generate bulk UUIDs?

A: Use UUID Generator bulk mode to generate 1-10,000 UUIDs at once, or use code examples above.

Q: What's the difference between GUID and UUID?

A: GUID (Globally Unique Identifier) is Microsoft's term for the same concept. UUIDs and GUIDs are structurally identical, just different naming conventions.

Q: Can I extract timestamp from UUID?

A: Only from UUID v1 and v7. UUID v4 is random and contains no timestamp. Use code examples above to extract v1 timestamps.


Related Tools


Made with ❤️ by Orbit2x - Free Developer Tools

Generate UUIDs now: UUID Generator

About

UUID Generator - Complete Guide to Unique Identifiers

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors