Back to blog

UUID Explained: What Is a UUID? Format, v4 & Examples

What Is a UUID?

A UUID (Universally Unique Identifier) is a 128-bit identifier used to uniquely identify records, objects, or resources without needing a central system to assign numbers. Any application, server, or device can generate a UUID on its own, and the result is unique for all practical purposes.

In its standard text format, a UUID contains 32 hexadecimal characters and 4 hyphens, for a total length of 36 characters. The characters follow an 8-4-4-4-12 pattern, such as 550e8400-e29b-41d4-a716-446655440000.

A typical UUID looks like this:

550e8400-e29b-41d4-a716-446655440000

UUIDs are commonly used as database primary keys, API resource IDs, request and event IDs, and file names. The most common type, UUID v4, is generated from random numbers. You can generate UUID v4 values in your browser to see the format for yourself.


UUID Example

Here is the example UUID again, with each part labeled:

550e8400-e29b-41d4-a716-446655440000
│        │    │    │    │
│        │    │    │    └─ Group 5: 12 hex digits
│        │    │    └────── Group 4: starts with "a" → variant
│        │    └─────────── Group 3: starts with "4" → version 4
│        └──────────────── Group 2: 4 hex digits
└───────────────────────── Group 1: 8 hex digits
  • The first digit of the third group is the version. Here it is 4, so this is formatted as a UUID v4.
  • The first digit of the fourth group shows the variant. For standard UUIDs it is always 8, 9, a, or b. Here it is a.

This particular value is a widely reused documentation sample, not a freshly generated ID. Don't copy sample UUIDs into real systems. Generate new ones instead.


What Does UUID Stand For?

UUID stands for Universally Unique Identifier. The format is standardized by the IETF in RFC 9562, which replaced the older RFC 4122 in 2024.

You will also see the term GUID (Globally Unique Identifier), mainly in Microsoft technologies. In everyday use, GUID and UUID mean the same kind of 128-bit identifier. The UUID vs GUID section below explains the small differences.


UUID Format Explained

UUID 128-bit structure and 36-character canonical format breakdown

The standard text form of a UUID follows this pattern:

xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
  • 128 bits in total
  • 32 hexadecimal characters (0–9, a–f)
  • 4 hyphens, giving 36 characters overall
  • Five groups in an 8-4-4-4-12 layout
  • M: the version digit (for example 1, 4, or 7)
  • N: the variant digit. For standard UUIDs its top bits are 10, so it is always 8, 9, a, or b
GroupHex charactersBitsWhat it holds
1832Timestamp bits (time-based versions) or random bits (v4)
2416Timestamp bits or random bits
3416Version digit, then timestamp or random bits
4416Variant bits, then clock sequence or random bits
51248Node ID (v1), or random bits (v4)

UUIDs are case-insensitive. The standard recommends lowercase output, but systems should accept uppercase input too.


UUID Versions

The version digit tells you how a UUID was created. Here are the versions you are most likely to see:

VersionHow it is generatedTypical use
v1Timestamp + clock sequence + node ID (often a MAC address)Legacy systems. Can reveal creation time and hardware.
v3MD5 hash of a namespace + nameDeterministic IDs from names (v5 is generally preferred)
v4Random bitsGeneral-purpose IDs; the most common choice
v5SHA-1 hash of a namespace + nameDeterministic IDs, e.g. the same UUID for the same URL every time
v6Reordered v1 timestampTime-sortable replacement for v1
v7Unix millisecond timestamp + random bitsTime-ordered IDs that work well with database indexes

Version 2 (DCE Security) exists but is rarely used, and v8 is reserved for custom, vendor-specific layouts.

For a detailed comparison of time-based and random UUIDs, including privacy and indexing trade-offs, read UUID v4 vs UUID v1: Which Version Should You Use?.


What Is UUID v4?

UUID v4 random generation workflow illustration

A UUID v4 is a UUID generated almost entirely from random data. Of its 128 bits:

  • 4 bits are fixed to mark version 4
  • 2 bits are fixed to mark the standard variant
  • 122 bits are random

That leaves 2^122 possible values, or about 5.3 × 10^36. Because the space is so large, applications can generate v4 IDs independently on many machines without checking with each other first.

UUID v4 is popular because it is simple to generate, needs no clock or hardware information, and is built into most modern languages and browsers. To be safe, it should come from a cryptographically secure random number generator (CSPRNG), such as crypto.randomUUID() in JavaScript or uuid.uuid4() in Python.

Need some UUIDs now? The UUID Generator creates random UUID v4 values in bulk, right in your browser, using the Web Crypto API.


What Are UUIDs Used For?

UUIDs are useful whenever you need an ID that is unique across systems and can be created without asking a central database first:

  • Database primary keys: especially when records are created on several servers or merged from different sources.
  • API resource IDs: e.g. /orders/b9f2c178-831d-44a6-95b7-7e61833c82e0 instead of /orders/1002, which avoids exposing record counts.
  • Distributed systems: services, regions, or shards can create IDs without coordinating with each other.
  • File and object identifiers: naming uploads in object storage without filename clashes.
  • Event and message IDs: identifying events in queues and event streams.
  • Request correlation IDs: tracing one request across many services in logs.
  • Client-generated IDs: mobile or offline-first apps can create records locally and sync them later.
  • Idempotency keys: letting an API recognize a retried request so it is processed only once.

UUID vs GUID

GUID (Globally Unique Identifier) is the name Microsoft uses for the same identifier format, for example in Windows, .NET (System.Guid), and SQL Server (UNIQUEIDENTIFIER). UUID is the name used in the IETF standard and most other ecosystems.

In most practical contexts the two terms are interchangeable: both are 128-bit values written in the same 8-4-4-4-12 text format.

The main nuance is binary byte order. Some Microsoft APIs store the first three groups in little-endian order, while the standard specifies big-endian (network) order. This only matters when you convert raw bytes between systems; the text form is the same.


UUID vs Auto-Increment IDs

UUID versus auto-increment database ID comparison graphic

AspectUUIDAuto-Increment Integer
Uniqueness scopeUnique across tables, databases, and systemsUnique within one table/sequence
GenerationAnywhere: client, service, or databaseUsually by the database at insert time
DistributionWorks without coordination between nodesNeeds coordination (offsets, ranges) across nodes
Storage size16 bytes binary (36 characters as text)4 bytes (INT) or 8 bytes (BIGINT)
Index localityRandom v4 values insert at scattered positions; v7 is time-orderedSequential inserts append to the end of the index
PredictabilityRandom v4 values are hard to guessEasy to guess and enumerate
ReadabilityLong and hard to read aloudShort and easy to debug (id = 42)

Neither option is better in every case. Auto-increment IDs are compact and simple for a single database. UUIDs fit better when IDs are created in many places, when datasets need merging, or when you don't want public IDs to reveal how many records exist.


Are UUIDs Unique? Collision Probability

UUIDs are not mathematically guaranteed to be unique: the number of possible values is finite, so a duplicate (a collision) is theoretically possible. In practice, correctly generated UUID v4 values are extremely unlikely to collide.

The chance of at least one collision among n random v4 UUIDs can be approximated with the birthday-problem formula:

p ≈ n² / (2 × 2^122)      (accurate while p is small)
UUID v4 values generatedApproximate chance of at least one collision
1 billion (10^9)about 1 in 10^19
1 trillion (10^12)about 1 in 10^13
100 trillion (10^14)about 1 in 10^9
about 2.7 × 10^18about 50%

For scale, 2.7 × 10^18 is roughly what you would get by generating one billion UUIDs every second for about 86 years. Normal applications create far fewer.

In real systems, duplicate UUIDs almost always come from implementation problems rather than probability. Common causes include a non-cryptographic generator like Math.random(), a poorly seeded random source, or cloned virtual machines that share random state. Use your platform's built-in CSPRNG-backed UUID function. If duplicates would be harmful, keep a UNIQUE constraint in the database.


UUIDs in Databases

UUIDs work well as database keys, but they come with trade-offs:

  • Storage: a UUID takes 16 bytes in binary form, compared with 4–8 bytes for an integer. Storing UUIDs as text (VARCHAR(36)) uses 36 bytes per value, plus larger indexes.
    • PostgreSQL: use the native UUID type.
    • MySQL 8+: use BINARY(16) with UUID_TO_BIN() / BIN_TO_UUID().
  • Index locality: random v4 values land at scattered positions in a B-tree index. On large, write-heavy tables this can cause more page splits and less effective caching. Time-ordered UUID v7 keeps new values close together.
  • Workload matters: for small tables or read-heavy workloads the difference is often negligible. Measure with your own data and database.
  • Static lookup tables: a short list of fixed values (such as roles or status codes) rarely benefits from UUID keys.

A PostgreSQL table using UUID primary keys:

-- gen_random_uuid() is built into PostgreSQL 13+
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) NOT NULL UNIQUE,
    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    total_amount_cents INTEGER NOT NULL
);

UUIDs in Distributed Systems and APIs

Distributed systems are where UUIDs help most:

  • No central bottleneck: each service, region, or shard can create IDs independently instead of asking one database for the next number.
  • Easier data merging: records from separate databases can be combined without renumbering keys.
  • Offline creation: clients can assign IDs before a record reaches the server, which helps with offline sync and optimistic UI updates.

Request correlation IDs

A UUID attached at the edge of a system can follow a request through every downstream service, making logs easy to connect:

import { Request, Response, NextFunction } from "express";
import { randomUUID } from "node:crypto";

export function correlationId(req: Request, res: Response, next: NextFunction) {
  const id = (req.headers["x-correlation-id"] as string) || randomUUID();
  req.headers["x-correlation-id"] = id;
  res.setHeader("X-Correlation-ID", id);
  next();
}

Validating UUIDs in APIs

Validate UUID inputs at the API boundary, and normalize them to lowercase before lookups or cache keys:

const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

function parseId(input: string): string | null {
  return UUID_REGEX.test(input) ? input.toLowerCase() : null;
}

For more validation patterns, including a strict UUID v4 regex, see the Regex Cheat Sheet & Common Patterns, and test them with the Regex Tester.


UUID Security Considerations

  • A UUID is not a secret. Random v4 UUIDs are hard to guess when generated with a CSPRNG, but the UUID standard itself warns against assuming UUIDs are hard to guess or using them as security capabilities. UUIDs show up in URLs, logs, browser history, and analytics.
  • Always check authorization. An endpoint like GET /api/documents/{uuid} must still verify that the current user is allowed to access that document. Don't rely on the ID being hard to guess.
  • Use real secrets for secrets. For session tokens, password reset links, or API keys, use purpose-built random tokens with enough entropy, plus expiry and revocation.
  • Be careful with UUID v1. It can embed the generating machine's MAC address and the exact creation time. Prefer v4 or v7 for IDs that are exposed publicly.
  • Avoid weak randomness. Never build UUIDs from Math.random() or similar non-cryptographic generators.

How to Generate a UUID

JavaScript / TypeScript

Modern browsers (in secure HTTPS contexts) and Node.js provide crypto.randomUUID(), which returns a random UUID v4:

// Browsers and Node.js 19+ (global crypto)
const id = crypto.randomUUID();

// Node.js 14.17+ via the crypto module
import { randomUUID } from "node:crypto";
const id2 = randomUUID();

For other versions (such as v1, v5, or v7), use the uuid npm package:

import { v4 as uuidv4, v5 as uuidv5 } from "uuid";

const randomId = uuidv4();
// v5: the same name + namespace always gives the same UUID
const URL_NAMESPACE = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
const stableId = uuidv5("https://www.devtoolkit.my", URL_NAMESPACE);

Python

import uuid

random_id = uuid.uuid4()                                   # random v4
named_id = uuid.uuid5(uuid.NAMESPACE_URL, "https://www.devtoolkit.my")  # deterministic v5
print(random_id, random_id.version)

PHP

<?php
// Native PHP: random_bytes() is cryptographically secure
function uuid_v4(): string {
    $data = random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // version 4
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // variant 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

Online

To get test data, seed a database, or fill in an API request, use the DevToolkit UUID Generator. It creates up to 10,000 random UUID v4 values at once, with options for uppercase and no-hyphen output, entirely in your browser.

UUID validation example

A UUID-looking string is not automatically a valid identifier. For UUID v4, validate the hyphenated shape and the version/variant bits before storing it:

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

This pattern checks lowercase hexadecimal UUID v4 strings in the standard 8-4-4-4-12 format. It does not prove that a value is unique or that it was generated securely. Test it with the DevToolkit Regex Tester, or generate fresh values with the UUID Generator.


Frequently Asked Questions (FAQ)

What does UUID stand for?

UUID stands for Universally Unique Identifier. It is a standardized 128-bit value used to identify records, objects, and resources without needing a central system to hand out IDs. The format is defined in RFC 9562, which replaced RFC 4122 in 2024.

What does a UUID look like?

A UUID is usually written as 36 characters: 32 hexadecimal digits split into five groups by four hyphens in an 8-4-4-4-12 pattern, for example 550e8400-e29b-41d4-a716-446655440000.

What is UUID v4?

UUID v4 is a randomly generated UUID. Of its 128 bits, 4 bits mark the version and 2 bits mark the variant, and the remaining 122 bits are random. It is the most widely used UUID version for general application identifiers.

Can UUIDs collide?

Yes, in theory, because the number of possible values is finite. In practice, correctly generated UUID v4 values have 122 random bits, so a collision is extremely unlikely at normal application volumes. Real-world duplicates are usually caused by a faulty or poorly seeded random number generator rather than by the math.

Is a UUID the same as a GUID?

In most practical contexts, yes. GUID (Globally Unique Identifier) is the name Microsoft uses for the same 128-bit identifier format. The text representation is the same; the main historical difference is byte ordering when some Microsoft systems store GUIDs in binary form.

Are UUIDs secure?

A UUID is an identifier, not a security mechanism. Random UUID v4 values are hard to guess when generated with a cryptographically secure random number generator, but they should not be treated as passwords, API keys, or access tokens. Always enforce authentication and authorization on the server.

When should I use a UUID instead of an auto-increment ID?

UUIDs are useful when IDs must be generated in many places without coordination, such as distributed systems, offline-first apps, or public APIs where sequential IDs would reveal record counts. Auto-increment integers are smaller and simpler and often work well for a single database. The right choice depends on your architecture.


Summary

  • UUID means Universally Unique Identifier: a 128-bit ID written as 36 characters (8-4-4-4-12).
  • The version digit (first character of the third group) tells you how it was generated. v4 is random and the most common.
  • Collisions are possible in theory but extremely unlikely with a proper cryptographic random generator.
  • GUID is Microsoft's name for the same format.
  • UUIDs suit distributed systems, public IDs, and client-side generation. Auto-increment integers are smaller and simpler for single databases.
  • UUIDs are identifiers, not secrets. Always enforce authorization.

Related Guides and Tools

For implementation details, read how UUID v4 generators work and the UUID v4 regex pattern.