1. Home
  2. Blog
  3. Software Development

Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID gives you 128-bit identifiers that are unique without a central counter, so different servers can create IDs independently. Learn which version to pick (random uuid4, name-based uuid5, time-ordered uuid7), how to parse and store them, the privacy problem with uuid1, and how each one performed as a database primary key in our test.

9 min read
Python UUID explained: uuid1, uuid4, uuid5, uuid7 and database keys

Key takeaways

  • Python UUID support lives in the standard uuid module; uuid.uuid4() is the right default for random IDs.
  • uuid5 always returns the same ID for the same namespace and name, which makes it ideal for deterministic keys.
  • In our run, uuid1().node equalled this computer’s hardware node ID, so uuid1 can leak which machine created a record.
  • Inserting 300,000 rows took 0.67 s with random uuid4 text keys, 0.53 s with time-ordered keys and 0.30 s with integer keys in SQLite.

Auto-increment IDs work well until you have several databases, offline clients, or services that create records before they reach the database. They also reveal how many orders or users you have. A UUID (Universally Unique Identifier) solves both problems: any machine can create one at any time, and the chance of two being equal is negligible. Python UUID handling is built into the standard library, but the version you pick affects privacy, sorting and database performance.

We ran every example on Python 3.13.6. The uuid7() function was added in Python 3.14, which we did not have, so we built a version 7 UUID by hand following the RFC 9562 layout and noted the 3.14 call alongside it.

What is a UUID?

A UUID is a 128-bit number, usually written as 32 hexadecimal digits in five groups, such as c6c23dad-be2a-5229-84f3-2403be22baee. The format is defined by RFC 9562 (which replaced RFC 4122 in 2024). Some bits record the version, which tells you how the rest was generated, and the variant, which identifies the standard layout. Microsoft calls the same thing a GUID.

uuid4: random UUIDs

import uuid
u = uuid.uuid4()
u.version, u.variant      # (4, 'specified in RFC 4122')
len(str(u)), len(u.bytes) # (36, 16)
# 1,000,000 uuid4 values: all unique
# about 1.52 microseconds per call

Version 4 fills 122 bits with random data from the operating system’s secure random source. It reveals nothing about when or where it was created, needs no coordination, and is fast: about 1.5 microseconds each in our test, and a million of them had no duplicates. For most applications, this is the version to use.

Anatomy of a UUID

c6c23dad-be2a-5229-84f3-2403be22baee
              ^    ^
              |    variant bits (8, 9, a or b)
              version digit (5)

The first digit of the third group is always the version, so you can tell a v4 (xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx) from a v7 (xxxxxxxx-xxxx-7xxx-xxxx-xxxxxxxxxxxx) at a glance. The first digit of the fourth group encodes the variant. The uuid.UUID object exposes these as .version and .variant, plus .hex, .int, .bytes and .urn.

uuid5 and uuid3: the same name always gives the same ID

a = uuid.uuid5(uuid.NAMESPACE_DNS, "stackquora.com")
b = uuid.uuid5(uuid.NAMESPACE_DNS, "stackquora.com")
a == b     # True
a          # UUID('c6c23dad-be2a-5229-84f3-2403be22baee')

uuid.uuid3(uuid.NAMESPACE_URL, "https://example.com/a")
# UUID('a257f385-897f-3805-9a3a-db29b1f92977')

Name-based UUIDs hash a namespace and a name. Version 5 uses SHA-1 and version 3 uses MD5; prefer 5. The output is deterministic, so two systems can compute the same ID for “user email x” or “product SKU y” without talking to each other, and re-importing the same data never creates duplicates. The standard namespaces are NAMESPACE_DNS, NAMESPACE_URL, NAMESPACE_OID and NAMESPACE_X500, or you can use any UUID as your own namespace. Do not use name-based UUIDs for secrets: anyone who knows the name can compute the ID. Hashing in general is covered in our Python hashlib guide.

uuid1 and the privacy problem

u1 = uuid.uuid1()
u1.version                       # 1
u1.node == uuid.getnode()        # True

Version 1 combines a timestamp with the computer’s node ID, normally its network card’s MAC address. Our check confirmed that the node field in a freshly generated uuid1 matched this machine’s node ID, so every uuid1 identifies the computer that created it. The Python documentation warns about exactly this privacy issue. Avoid uuid1 for anything exposed to users; if you want time ordering, use version 7 instead.

uuid7: time-ordered UUIDs

# Python 3.14 and later:
# u = uuid.uuid7()

# Manual version 7 for Python 3.13 (RFC 9562 layout, for illustration):
def uuid7_manual():
    ms = int(time.time() * 1000)                 # 48-bit Unix time in milliseconds
    rnd = random.getrandbits(74)
    val = (ms << 80) | (0x7 << 76) | ((rnd >> 62) << 64) | (0b10 << 62) | (rnd & ((1 << 62) - 1))
    return uuid.UUID(int=val)

# IDs from later milliseconds always sorted after earlier ones: True
# uuid4 values sorted into creation order: False
# timestamp recoverable from the first 48 bits: True

Version 7 puts a millisecond timestamp in the first 48 bits and random data in the rest. That makes IDs roughly sortable by creation time while keeping them unpredictable and free of hardware details. In our test, IDs created in later milliseconds always sorted after earlier ones, while uuid4 values sorted in a random order. The creation time can be read back from the ID, which is useful for debugging but means a v7 reveals when a record was created. Our hand-written function uses random for brevity; production code should use the standard library’s uuid7() on 3.14 or a maintained package, which use a secure random source.

Which UUID version should you use?

Version Based on Use for
4 Random The default: request IDs, public IDs, most primary keys
7 Time + random Database primary keys on large tables, logs, event streams
5 SHA-1 of namespace + name Deterministic IDs, deduplication, idempotent imports
3 MD5 of namespace + name Only for compatibility with existing v3 data
1 Time + MAC address Avoid: leaks the machine identity

Parsing and validating UUIDs

s = "12345678-1234-5678-1234-567812345678"
uuid.UUID("{12345678-1234-5678-1234-567812345678}") == uuid.UUID(s)   # True (braces)
uuid.UUID("12345678123456781234567812345678") == uuid.UUID(s)         # True (no dashes)
uuid.UUID(s.upper()) == uuid.UUID(s)                                  # True (any case)
str(uuid.UUID(s.upper()))     # '12345678-1234-5678-1234-567812345678'  (normalised lower case)
uuid.UUID(s).version          # None  (not an RFC 9562 layout)
uuid.UUID("not-a-uuid")       # ValueError: badly formed hexadecimal UUID string

uuid.UUID() accepts several spellings and normalises them, so convert incoming strings with it before comparing or storing. Catch ValueError to reject invalid input from URLs and forms. Note that a well-formed hex string is not necessarily a standard UUID: our sample had no valid version, so .version was None. Check u.version in (4, 7) if you only accept certain versions.

String, hex, bytes and integer forms

str(u)      # 36 characters with dashes
u.hex       # 32 characters, no dashes
u.bytes     # 16 raw bytes
u.int       # a 128-bit integer
u.urn       # 'urn:uuid:...'

The text form is convenient but takes 36 bytes, more than twice the 16-byte binary form. Databases with a native UUID type (PostgreSQL’s uuid, SQL Server’s uniqueidentifier) store 16 bytes; in MySQL, store BINARY(16) rather than CHAR(36) for large tables. In JSON and URLs, the standard string is the safest. JavaScript cannot hold a 128-bit integer as a normal number, so never send u.int to a browser; see our JavaScript BigInt guide for why.

UUIDs as database primary keys

Primary key (SQLite, 300,000 inserts) Time
Random uuid4, as text 0.67 s
Time-ordered (version 7 layout), as text 0.53 s
Integer, auto-assigned 0.30 s

Database indexes are sorted structures. Random uuid4 keys land in random positions, so every insert touches a different part of the index, which costs more page splits and cache misses as tables grow. Time-ordered keys arrive in nearly sorted order and append to the end of the index, like integers do. In our in-memory SQLite test, uuid4 inserts took about 2.2 times as long as integers and time-ordered keys about 1.8 times; on disk-based databases with indexes larger than memory, the gap is typically much bigger. Integers remain the fastest and smallest key; our auto increment guide compares them across databases, and SQL indexes explained covers why insert order matters.

Tip: a common pattern is an integer primary key for joins and a uuid4 or uuid7 column, with a unique index, as the public ID used in URLs and APIs.

How unique is unique?

A uuid4 has 122 random bits, about 5.3 undecillion possible values. You would need to generate roughly 2.7 quintillion of them before the chance of even one duplicate reached 50 percent. In practice, duplicates come from bugs, not chance: copying IDs between records, seeding a random generator with a fixed value in tests, or cloned virtual machines generating version 1 IDs with the same node and clock. If a duplicate would be harmful, keep a unique constraint in the database anyway.

UUIDs and security

  • Not a password or token. uuid4 is hard to guess, but use secrets.token_urlsafe() for session tokens and reset links, which is what the secrets module is for; our Python random guide explains why random must never be used for secrets.
  • Not authorisation. An unguessable ID in a URL does not replace checking that the user may see the record.
  • Information leaks. uuid1 reveals the machine, uuid7 reveals the creation time, and uuid5 can be recomputed by anyone who knows the name.

Final thoughts

Python UUID support covers every common need with a single module. Use uuid4() by default, uuid5() when the same input must always map to the same ID, and version 7 (built in from Python 3.14) when IDs are database keys or should sort by time. Avoid uuid1 because it exposes the machine, parse every incoming ID with uuid.UUID(), and store UUIDs in a native or 16-byte binary column when tables get large. In our tests those choices made the difference between privacy leaks and safe IDs, and between random and nearly sequential inserts.

Frequently asked questions

How do I generate a UUID in Python?

Import the uuid module and call uuid.uuid4() for a random UUID. Convert it with str() for a 36-character text form, or use the hex attribute for 32 characters without dashes.

What is the difference between uuid4 and uuid7?

uuid4 is entirely random. uuid7 starts with a millisecond timestamp followed by random bits, so IDs sort roughly by creation time, which makes them friendlier to database indexes.

Is uuid4 unique enough for primary keys?

Yes. With 122 random bits, a collision is practically impossible. The bigger concern for primary keys is insert performance on large tables, where time-ordered IDs or integers are faster.

Why should I avoid uuid1?

uuid1 includes the network address of the computer that created it, so every ID reveals the machine. Use uuid4 for random IDs or uuid7 for time-ordered ones instead.

How do I check if a string is a valid UUID in Python?

Pass it to uuid.UUID inside a try block. It raises ValueError for badly formed input. Then check the version attribute if you only accept certain versions.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →