Generate secure v4 UUIDs for database and entity keys.
Understand the architecture of Universally Unique Identifiers, why v4 vs v7 matters for database performance, and the security of PRNGs.
A Universally Unique Identifier (UUID) is a 128-bit number used to identify information in computer systems. Because the number of possible UUIDs is so vast (2122 for version 4), they can be generated independently across distributed systems without needing a central authority to prevent collisions.
Not all UUIDs are the same. UUID v4 is completely random (except for 6 bits used for versioning). UUID v7, recently standardized, embeds a Unix timestamp in the first 48 bits, making it time-ordered and much friendlier for database indexing.
Math.random() is not cryptographically secure. An attacker can predict future outputs if they observe enough generated numbers. True UUID v4 generation must rely on crypto.getRandomValues() to ensure unpredictable entropy.Using a random UUID v4 as a Primary Key in a SQL database (like PostgreSQL or MySQL) can cause severe fragmentation in B-Tree indexes. Since the IDs are inserted in a random order, the database must constantly split pages on disk.
UUID v7 solves this by placing a timestamp at the start of the ID. New IDs are always "greater" than old IDs, allowing sequential, append-only disk writes that vastly improve insert performance.
window.crypto.randomUUID() when available, which natively relies on the OS-level entropy pool (e.g., /dev/urandom) to generate secure v4 UUIDs.Uint8Array) to splice the current epoch time into the random byte array.Common mistakes when implementing UUIDs:
Math.random() if the Crypto API is unavailable, dramatically increasing the risk of collisions.Why is UUID v7 heavily recommended over UUID v4 for SQL database Primary Keys?