Switching a growing application from auto-incrementing integers to random UUIDv4 primary keys is one of the fastest ways to accidentally cripple MySQL InnoDB insert throughput and double your AWS RDS RAM requirements. Yet exposing sequential `AUTO_INCREMENT` integers (`/invoices/1042`) also leaks business volume and invites predictable enumeration.
The modern solution standardized in **RFC 9562**—**`UUIDv7` stored as `BINARY(16)`**—gives you globally unique, non-guessable identifiers *while* keeping MySQL InnoDB’s clustered B-Tree sequential and compact.
Head-to-Head Comparison: BIGINT vs. UUIDv4 vs. UUIDv7 in MySQL 8.4 InnoDB
| Primary Key Design | Key Size (Per Row) | InnoDB B-Tree Insertion Pattern | Secondary Index Bloat (50M Rows, 3 Secondary Indexes) | Exposes Sequential IDs? |
|---|---|---|---|---|
BIGINT UNSIGNED AUTO_INCREMENT |
8 bytes | Strictly sequential append (optimal page fill ~93%) | Baseline (minimal RAM footprint) | Yes (unless paired with public UUID column) |
UUIDv4 as CHAR(36) utf8mb4 |
36–144 bytes | Random B-Tree page splits (~50–65% page fill, heavy IOPS) | Massive (+4–6 GB extra RAM across secondary indexes!) | No |
UUIDv7 as BINARY(16) |
16 bytes | Time-ordered monotonic append (minimal page splits) | Only +8 bytes vs `BIGINT` per secondary entry | Low (48-bit ms prefix + 74 random bits) |
Why Random UUIDv4 Hurts MySQL InnoDB So Much
Unlike PostgreSQL (which stores table rows in an unordered heap), **MySQL InnoDB is a clustered index**: every table row is physically sorted inside the Primary Key B-Tree on `16 KB` pages, and **every secondary index stores a copy of the Primary Key inside every leaf entry** as its row pointer!
- Random B-Tree Thrashing: With `UUIDv4`, new inserts jump randomly across the entire key space. Once the index exceeds `innodb_buffer_pool_size`, nearly every `INSERT` must read a cold `16 KB` page from disk, split it in half when full, and write dirty random pages back—causing severe write amplification and buffer-pool cache churn.
- `CHAR(36)` Secondary-Index Multiplication: If a 50M-row `orders` table has 4 secondary indexes (`customer_id`, `status`, `created_at`, `merchant_id`), storing a `CHAR(36)` PK copies 36 bytes into 200 million secondary index entries—wasting gigabytes of expensive NVMe storage and buffer pool RAM!
How RFC 9562 UUIDv7 + BINARY(16) Solves Both Problems
`UUIDv7` encodes a **48-bit big-endian Unix millisecond timestamp** in its most-significant bits followed by 74 cryptographically random bits. Because consecutive milliseconds always sort higher than previous ones, inserts append cleanly to the right-hand edge of InnoDB’s clustered B-Tree—preserving buffer-pool locality just like `AUTO_INCREMENT` while remaining safe to generate client-side or across distributed app servers without central coordination!
Generating RFC 9562 UUIDv7 in Pure PHP 8.3 (Zero Extensions Required)
<?php
/**
* Generate a 16-byte RFC 9562 UUIDv7 binary string for MySQL BINARY(16) primary keys.
*/
function generateUuidV7Bytes(): string
{
$ms = (int) floor(microtime(true) * 1000);
$rand = random_bytes(10);
// 48-bit big-endian Unix ms timestamp
$timeHex = str_pad(dechex($ms), 12, '0', STR_PAD_LEFT);
$bytes = hex2bin($timeHex) . $rand;
// Set RFC 9562 version = 7 (0111xxxx) and variant = 10xxxxxx
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x70);
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
return $bytes; // Exactly 16 raw bytes ready for BINARY(16)
}
function uuidBytesToString(string $bytes16): string
{
$hex = bin2hex($bytes16);
return sprintf('%s-%s-%s-%s-%s',
substr($hex, 0, 8), substr($hex, 8, 4), substr($hex, 12, 4),
substr($hex, 16, 4), substr($hex, 20, 12)
);
}
MySQL 8.x Built-In Helpers (`UUID_TO_BIN` & `BIN_TO_UUID`)
CREATE TABLE invoices (
id BINARY(16) NOT NULL,
customer_id BIGINT UNSIGNED NOT NULL,
total_cents INT UNSIGNED NOT NULL,
PRIMARY KEY (id),
KEY idx_invoices_customer (customer_id)
) ENGINE=InnoDB;
-- In SQL queries (Note: UUIDv7 is ALREADY time-ordered — pass swap_flag = 0!):
SELECT BIN_TO_UUID(id, 0) AS invoice_uuid, total_cents
FROM invoices
WHERE id = UUID_TO_BIN('01938a4e-7c1b-7b2a-9c4f-1a2b3c4d5e6f', 0);
Critical Tip: MySQL 8’s `UUID_TO_BIN(str, 1)` bit-swapping helper was invented for *UUIDv1*. **Do NOT pass `1` for `UUIDv7`**, because `UUIDv7` already puts its timestamp in the leading 48 bits! Always use `0` (natural byte order).
The Hybrid Pattern: Internal BIGINT PK + Public UUIDv7 Column
If your table has 8+ secondary indexes or high-frequency foreign-key joins, keeping an internal `BIGINT UNSIGNED AUTO_INCREMENT` as the `PRIMARY KEY` and adding a `UNIQUE KEY (public_id BINARY(16))` column for URLs and REST APIs gives you the smallest possible 8-byte internal join pointers *plus* unguessable public IDs. Compare more engine internals in MySQL vs PostgreSQL Performance & Architecture.
Frequently Asked Questions
Does PostgreSQL suffer the same UUIDv4 penalty as MySQL InnoDB?
PostgreSQL uses an unordered Heap rather than a clustered primary key, so secondary indexes only store 6-byte `ctid` pointers—making UUIDs cheaper in secondary indexes. However, `UUIDv7` (native `uuidv7()` in PostgreSQL 18 / extensions in 17) still improves PostgreSQL B-Tree primary-index cache locality and reduces WAL full-page writes dramatically compared to `UUIDv4`.