✏️ Explanatory Question
Level: Hard — A deep InnoDB internals question; random UUIDs as a clustered PK can silently cripple write performance.
AUTO_INCREMENT BIGINT to random UUIDs (for distributed uniqueness and to hide row counts). Soon, INSERT performance tanks on large tables, disk usage balloons, and the buffer pool thrashes. Why does a random UUID PK hurt InnoDB so badly, and how do you keep UUIDs without the pain?
In InnoDB, the primary key IS the physical storage order (the clustered index). Rows are stored on disk pages sorted by PK. This makes the nature of the PK critical to write performance.
| Aspect | AUTO_INCREMENT | Random UUID (v4) |
|---|---|---|
| Insert position | Always at the end | Random (middle of pages) |
| Page splits | Rare | Frequent |
| Page fill | ~93% (tight) | ~50% (fragmented) |
| Buffer pool | Hot pages cached | Thrashing (random I/O) |
| PK size | 8 bytes (BIGINT) | 16 bytes binary / 36 char |
| Secondary index bloat | Small (PK stored in each) | Large (bigger PK copied everywhere) |
You can keep global uniqueness without the random-insert penalty by using a time-ordered UUID (UUIDv7, or a rearranged UUIDv1). Because the leading bits are a timestamp, new ids are mostly sequential — restoring append-friendly inserts.
-- BAD: UUID as CHAR(36) -> 36 bytes, huge, random
CREATE TABLE orders_bad (
id CHAR(36) PRIMARY KEY, -- random UUIDv4 string
data VARCHAR(255)
);
-- BETTER: store as BINARY(16) -> half the size, still random (v4)
CREATE TABLE orders_ok (
id BINARY(16) PRIMARY KEY,
data VARCHAR(255)
);
-- Insert: UUID_TO_BIN(UUID())
-- BEST: time-ordered UUID stored as BINARY(16) -> sequential inserts
CREATE TABLE orders_best (
id BINARY(16) PRIMARY KEY, -- UUIDv7 / ordered UUID
data VARCHAR(255)
);
-- MySQL 8.0 trick: UUID_TO_BIN(uuid, 1) swaps time fields to make v1
-- UUIDs time-sortable, giving near-sequential insert order
INSERT INTO orders_best (id, data)
VALUES (UUID_TO_BIN(UUID(), 1), 'payload');
| Choice | Best For |
|---|---|
| AUTO_INCREMENT BIGINT | Single DB, best performance, internal ids |
| UUIDv7 / ordered UUID (BINARY 16) | Distributed systems needing global uniqueness + good writes |
| Random UUIDv4 | Only when unpredictability is essential and write volume is low |