Appearance
MySQL InnoDB Clustered Index Architecture
The Fundamental Difference: Clustered vs Heap Storage
MySQL InnoDB và PostgreSQL tổ chức bảng khác nhau: InnoDB lưu dòng ngay trong cây B-Tree của PRIMARY KEY (clustered index), PostgreSQL lưu dòng trong heap riêng và mọi index chỉ trỏ tới heap.
PostgreSQL (heap):
text
Primary Key Index: [1] → heap_page_5, offset_3
[5] → heap_page_2, offset_7
[10] → heap_page_8, offset_1
Heap (Table Data): [page_2: row_5, row_12, ...]
[page_5: row_1, row_8, ...]
[page_8: row_10, row_15, ...]
Secondary Index: [email='abc'] → heap_page_5, offset_3Index lưu con trỏ (TID: số trang + vị trí) tới heap; dữ liệu dòng nằm riêng trong heap.
MySQL InnoDB (clustered index):
text
Primary Key (Clustered Index):
[1] → FULL ROW DATA (id=1, name='John', email='j@x.com', age=25, ...)
[5] → FULL ROW DATA (id=5, name='Jane', email='jane@x.com', age=30, ...)
[10] → FULL ROW DATA (id=10, name='Bob', email='bob@x.com', age=28, ...)
Secondary Index (email):
[email='abc'] → PK value: 5
→ nếu cần cột ngoài index: tra tiếp cây PRIMARY để lấy cả dòng
→ "double lookup"⚠️ GOTCHA: PRIMARY KEY của InnoDB = chính bảng; không có heap riêng. Mỗi secondary index lưu thêm giá trị PK, nên PK rộng (ví dụ UUID dạng CHAR(36) = 36 byte) làm MỌI index phình ra. Nếu bảng không khai báo PK, InnoDB dùng UNIQUE index đầu tiên có toàn cột NOT NULL; nếu cũng không có thì tự sinh GEN_CLUST_INDEX với row ID ẩn 6 byte. Mặc định tốt là PK hẹp và tăng dần (BIGINT AUTO_INCREMENT, hoặc BINARY(16) có thứ tự thời gian); PK ngẫu nhiên như UUIDv4 đắt hơn khi bảng lớn hơn buffer pool (xem mục UUID bên dưới).
→ See also: Cross-Database Migration (PostgreSQL ↔ MySQL) for handling this architectural difference when migrating
Clustered Index Leaf Node Structure
text
InnoDB B-Tree leaf page (mặc định 16 KB, innodb_page_size):
┌─────────────────────────────────────────────────────┐
│ File Header + Page Header │
├─────────────────────────────────────────────────────┤
│ Infimum & Supremum Records (bản ghi biên) │
├─────────────────────────────────────────────────────┤
│ User Records (ROW DATA): │
│ [PK=1] → [col1, col2, col3, col4, ...FULL ROW] │
│ [PK=2] → [col1, col2, col3, col4, ...FULL ROW] │
│ [PK=5] → [col1, col2, col3, col4, ...FULL ROW] │
│ ... │
├─────────────────────────────────────────────────────┤
│ Free Space │
├─────────────────────────────────────────────────────┤
│ Page Directory (con trỏ tới các bản ghi) │
├─────────────────────────────────────────────────────┤
│ File Trailer (checksum) │
└─────────────────────────────────────────────────────┘
Mặc định 16 KB mỗi trang (PostgreSQL: 8 KB, chọn lúc biên dịch).Implications:
- Dòng rộng = ít dòng mỗi trang = quét nhiều trang hơn, cây có thể sâu hơn. Cột BLOB/TEXT dài với
ROW_FORMAT=DYNAMIC(mặc định) được đẩy sang trang riêng (off-page), nên dòng trong cây thường nhỏ hơn tổng kích thước dữ liệu. - Chọn PRIMARY KEY quyết định thứ tự vật lý của dữ liệu và kích thước mọi secondary index.
- Đổi PRIMARY KEY hoặc cấu trúc dòng thường dựng lại cả bảng (xem mục "Table Reorganization" bên dưới).
Secondary Index Structure: The Double Lookup Problem
Lá của secondary index lưu (giá trị cột index, giá trị PK), không lưu cả dòng. Khi truy vấn cần cột ngoài index, InnoDB tra secondary index để lấy PK rồi tra tiếp cây clustered (PRIMARY) để lấy cả dòng: đó là "double lookup".
sql
-- MySQL 8.4 (chạy trong một database thử)
SET SESSION cte_max_recursion_depth = 1000000;
CREATE TABLE users (
id INT PRIMARY KEY, -- clustered index
email VARCHAR(255),
name VARCHAR(100),
age INT,
address TEXT,
INDEX idx_email (email) -- secondary index: lá = (email, id)
);
INSERT INTO users (id, email, name, age, address)
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i < 100000)
SELECT i, CONCAT('user', i, '@example.com'), CONCAT('name', i), 20 + i % 50, 'addr' FROM n;
ANALYZE TABLE users;
-- Cần cột ngoài index: tra idx_email lấy id, rồi tra PRIMARY lấy cả dòng
EXPLAIN FORMAT=TREE SELECT * FROM users WHERE email = 'user5@example.com';
-- Chỉ cần cột nằm trong index (email + id ẩn): không đụng cây clustered
EXPLAIN FORMAT=TREE SELECT id, email FROM users WHERE email = 'user5@example.com';Kết quả thật (MySQL 8.4.13):
text
-> Index lookup on users using idx_email (email='user5@example.com') (cost=0.35 rows=1)
-> Covering index lookup on users using idx_email (email='user5@example.com') (cost=0.35 rows=1)Why this matters:
- Truy vấn qua secondary index lấy cột ngoài index phải tra thêm cây clustered; truy vấn covering thì không ("Covering index lookup").
SELECT *hầu như luôn cần bước tra thứ hai, trừ khi index chứa mọi cột của bảng.- PK luôn nằm sẵn trong mọi secondary index, nên
SELECT id, emailở trên vẫn là covering mà không cần khai báo thêm. - Chi phí bước hai phụ thuộc dữ liệu có trong buffer pool hay không: đo bằng
EXPLAIN ANALYZEvàSHOW STATUS LIKE 'Innodb_buffer_pool_reads'.
Wide Primary Keys: The Hidden Cost
sql
-- MySQL 8.4 (chạy trong một database thử; ~500 000 hàng, vài giây)
SET SESSION cte_max_recursion_depth = 1000000;
-- BAD: PK rộng
CREATE TABLE orders_uuid (
order_uuid CHAR(36) PRIMARY KEY, -- 36 byte với UUID dạng chữ
customer_id INT,
product_id INT,
amount DECIMAL(10,2),
created_at TIMESTAMP,
INDEX idx_customer (customer_id),
INDEX idx_product (product_id),
INDEX idx_created (created_at)
);
-- GOOD: PK hẹp, UUID giữ lại làm UNIQUE secondary index (nếu cần tra theo UUID)
CREATE TABLE orders_int (
id INT AUTO_INCREMENT PRIMARY KEY, -- 4 byte
order_uuid CHAR(36) UNIQUE,
customer_id INT,
product_id INT,
amount DECIMAL(10,2),
created_at TIMESTAMP,
INDEX idx_customer (customer_id),
INDEX idx_product (product_id),
INDEX idx_created (created_at)
);
INSERT INTO orders_uuid
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i+1 FROM n WHERE i < 500000)
SELECT LOWER(CONCAT_WS('-', SUBSTR(MD5(i),1,8), SUBSTR(MD5(i),9,4), SUBSTR(MD5(i),13,4),
SUBSTR(MD5(i),17,4), SUBSTR(MD5(i),21,12))),
i % 50000, i % 1000, i % 1000 / 10, TIMESTAMP('2026-01-01') + INTERVAL i SECOND
FROM n;
INSERT INTO orders_int (order_uuid, customer_id, product_id, amount, created_at)
SELECT order_uuid, customer_id, product_id, amount, created_at FROM orders_uuid ORDER BY created_at;
ANALYZE TABLE orders_uuid, orders_int;
-- Kích thước từng index (trang 16 KB)
SELECT table_name, index_name,
ROUND(stat_value * @@innodb_page_size / 1048576, 1) AS mb
FROM mysql.innodb_index_stats
WHERE database_name = DATABASE() AND stat_name = 'size'
AND table_name IN ('orders_uuid', 'orders_int')
ORDER BY table_name, index_name;Kết quả thật (500 000 hàng, MySQL 8.4.13, 2026-11-20; số lệch nhẹ giữa các lần chạy):
text
table index MB
orders_int PRIMARY 40.6
orders_int idx_created 7.5
orders_int idx_customer 13.5
orders_int idx_product 11.5
orders_int order_uuid 37.6 (UNIQUE secondary trên CHAR(36))
orders_uuid PRIMARY 62.8
orders_uuid idx_created 23.6
orders_uuid idx_customer 43.7
orders_uuid idx_product 37.6Đọc kết quả:
- Ba index giống nhau (customer, product, created): 104.9 MB với PK UUID so với 32.5 MB với PK INT, khoảng 3,2 lần (không phải 5-6 lần như tính thô theo số byte: mỗi bản ghi còn có phần đầu bản ghi, và trang không đầy tuyệt đối).
- Nếu vẫn giữ
order_uuidlàm UNIQUE index (37.6 MB) thì tổng cả bảng là 110.7 MB so với 167.7 MB: tiết kiệm khoảng 34%, không phải 6 lần. - Kích thước thật phụ thuộc kiểu cột, thứ tự chèn và fill factor: đo bằng truy vấn trên dữ liệu của bạn.
Rule of thumb: mặc định dùng INT/BIGINT AUTO_INCREMENT làm PRIMARY KEY trong MySQL (dùng BIGINT nếu có thể vượt khoảng 2,1 tỷ dòng); chỉ dùng khóa rộng hoặc sinh phía client khi có lý do (ID phân tán, ẩn thứ tự), và khi đó chọn giá trị có thứ tự thời gian.
Covering Indexes in MySQL: Must Account for PK
Mỗi secondary index của InnoDB chứa sẵn các cột PK. Hệ quả: truy vấn chỉ đọc cột index + cột PK là covering (Extra: Using index) mà không cần khai báo PK vào index; ngược lại PK rộng làm index rộng.
sql
-- MySQL 8.4 — chạy sau khối tạo orders_int ở mục "Wide Primary Keys: The Hidden Cost"
-- idx_customer có lá (customer_id, id): chứa PK ẩn
EXPLAIN SELECT id, customer_id FROM orders_int WHERE customer_id = 100;
-- Kết quả thật, cột Extra: Using index
-- created_at không nằm trong idx_customer: phải tra cây clustered
EXPLAIN SELECT customer_id, created_at FROM orders_int WHERE customer_id = 100;
-- Kết quả thật, cột Extra: NULL
ALTER TABLE orders_int ADD INDEX idx_cover (customer_id, created_at), ALGORITHM=INPLACE, LOCK=NONE;
EXPLAIN SELECT customer_id, created_at FROM orders_int WHERE customer_id = 100;
-- Kết quả thật, cột Extra: Using index (key = idx_cover)Covering index rule in MySQL:
- Truy vấn tránh được bước tra cây clustered khi mọi cột nó cần (SELECT, WHERE, ORDER BY) đều nằm trong index hoặc là cột PK.
SELECT * FROM orders_int WHERE customer_id = 100không covering, vì cần mọi cột của bảng.- PRIMARY KEY nằm sẵn trong mọi secondary index (chi phí không thấy được trong định nghĩa index): PK rộng làm TẤT CẢ index lớn hơn.
- PostgreSQL khác: index-only scan phải liệt kê cột trong index (hoặc
INCLUDE) và cần visibility map đã được VACUUM.
Table Reorganization: ALTER TABLE Rebuilds Clustered Index
Vì dữ liệu nằm trong cây clustered, một số ALTER phải dựng lại cả bảng. Thuật toán nào được phép phụ thuộc loại thay đổi: kiểm tra bằng cách ghi ALGORITHM và LOCK tường minh để MySQL từ chối thay vì âm thầm khoá bảng.
sql
-- MySQL 8.4 — chạy sau khối tạo orders_int ở mục "Wide Primary Keys: The Hidden Cost"
-- Đổi kiểu cột chỉ chạy được bằng COPY (dựng lại bảng); INPLACE bị từ chối:
ALTER TABLE orders_int MODIFY COLUMN amount DECIMAL(12,2), ALGORITHM=INPLACE;
-- ERROR 1846: ALGORITHM=INPLACE is not supported. Reason: Cannot change column type INPLACE. Try ALGORITHM=COPY.
ALTER TABLE orders_int MODIFY COLUMN amount DECIMAL(12,2), ALGORITHM=COPY, LOCK=NONE;
-- ERROR 1846: LOCK=NONE is not supported. Reason: COPY algorithm requires a lock. Try LOCK=SHARED.
-- Chạy được, nhưng chặn ghi (INSERT/UPDATE/DELETE phải chờ) tới khi sao chép xong:
ALTER TABLE orders_int MODIFY COLUMN amount DECIMAL(12,2), ALGORITHM=COPY, LOCK=SHARED;
-- Thêm/xoá cột: INSTANT chỉ đổi metadata (thêm/xoá ở vị trí bất kỳ từ 8.0.29)
ALTER TABLE orders_int ADD COLUMN note VARCHAR(10), ALGORITHM=INSTANT;
ALTER TABLE orders_int DROP COLUMN note, ALGORITHM=INSTANT;
-- Dựng lại bảng nhưng vẫn cho đọc/ghi đồng thời:
ALTER TABLE orders_int ENGINE=InnoDB, ALGORITHM=INPLACE, LOCK=NONE;
-- Thêm index: INPLACE, không dựng lại bảng
ALTER TABLE orders_int ADD INDEX idx_amount (amount), ALGORITHM=INPLACE, LOCK=NONE;Các thao tác khác dựng lại bảng: đổi thứ tự cột, OPTIMIZE TABLE, ALTER TABLE ... ENGINE=InnoDB (kể cả khi đã là InnoDB), đổi PRIMARY KEY.
⚠️ Rủi ro: ALGORITHM=COPY chặn ghi trong suốt thời gian sao chép và cần thêm chỗ đĩa cỡ bảng; với bảng lớn hãy thử trên bản sao để đo thời gian, kiểm tra độ trễ replica, và cân nhắc công cụ ngoài như gh-ost hoặc pt-online-schema-change nếu không chấp nhận chặn ghi. Cách lui: ALTER COPY chỉ thay bảng khi xong, huỷ giữa chừng thì bảng cũ còn nguyên.
So với PostgreSQL: nhiều ALTER chỉ đổi catalog, nhưng không phải mọi ALTER TYPE:
sql
-- PostgreSQL 18 (psql, vì dùng \gset)
CREATE TABLE numeric_demo (id BIGINT PRIMARY KEY, amount NUMERIC(10,2));
INSERT INTO numeric_demo SELECT g, g FROM generate_series(1, 1000) g;
SELECT pg_relation_filenode('numeric_demo') AS before \gset
ALTER TABLE numeric_demo ALTER COLUMN amount TYPE NUMERIC(12,2);
SELECT pg_relation_filenode('numeric_demo') = :before AS no_rewrite; -- true: tăng precision, giữ scale
ALTER TABLE numeric_demo ALTER COLUMN amount TYPE NUMERIC(12,3);
SELECT pg_relation_filenode('numeric_demo') = :before AS no_rewrite; -- false: đổi scale viết lại cả bảngComparison: PostgreSQL vs MySQL Index Architecture
| Aspect | PostgreSQL (Heap) | MySQL InnoDB (Clustered) |
|---|---|---|
| Primary Key Storage | Index riêng → heap | Cây PK = dữ liệu bảng |
| Secondary Index Leaf | TID (trang heap + vị trí) | Giá trị PRIMARY KEY |
| Lấy cả dòng qua secondary index | index → TID → đọc heap | secondary → PK → tra cây clustered |
| PK Selection Impact | Nhỏ (chỉ index PK) | Lớn (PK có mặt trong mọi index) |
| Wide PK Cost | Chủ yếu index PK | MỌI secondary index |
| Covering Index | Liệt kê cột (hoặc INCLUDE) | Cột index + cột PK có sẵn |
| Đổi kiểu cột | Tuỳ loại: có loại chỉ đổi catalog, có loại viết lại heap | Cần ALGORITHM=COPY (dựng lại bảng); thêm/xoá cột có thể INSTANT |
| Page Size | 8 KB (mặc định, chọn lúc biên dịch) | 16 KB (mặc định, innodb_page_size) |
| Index-Only Scans | Cần visibility map (VACUUM) | Covering index (Using index) |
When MySQL Clustered Index Wins:
- Tra theo PK:
SELECT * FROM users WHERE id = 5(một lần đi xuống cây, dòng nằm ngay trong lá) - Quét khoảng theo PK:
SELECT * FROM orders WHERE id BETWEEN 100 AND 200(các dòng nằm liền nhau trong cây clustered)
When MySQL Clustered Index Loses:
- Truy vấn qua secondary index cần cột ngoài index:
SELECT * FROM users WHERE email = 'x@y.com'(tra thêm cây clustered) - PK rộng: mọi index phình ra
- Đổi cấu trúc bảng (ví dụ đổi kiểu cột) có thể phải dựng lại cả bảng
Real-World Impact: Case Study
Số đo thật nằm ở mục Wide Primary Keys: The Hidden Cost: với 500 000 hàng, ba secondary index giống nhau tốn 104.9 MB khi PK là CHAR(36) so với 32.5 MB khi PK là INT (khoảng 3,2 lần), và bảng có thêm UNIQUE index trên UUID chỉ nhỏ hơn khoảng 34% tổng thể.
Ngoại suy cho bảng 50 triệu hàng (kịch bản minh hoạ, không phải đo): nhân kích thước index lên khoảng 100 lần nếu cây không sâu thêm, tức hàng chục GB index phải nằm trong buffer pool. Chênh lệch thời gian truy vấn SELECT * FROM orders WHERE customer_id = 12345 không được ghi ở đây vì chưa đo: dùng EXPLAIN ANALYZE và SHOW STATUS LIKE 'Innodb_buffer_pool_reads' trên dữ liệu của bạn.
Key Takeaway: trong InnoDB, PRIMARY KEY quyết định kích thước mọi secondary index và thứ tự chèn của dữ liệu; mặc định chọn PK hẹp, tăng dần (INT/BIGINT AUTO_INCREMENT) trừ khi có yêu cầu ID phân tán.
UUID vs ULID: The B-Tree Fragmentation Problem
Critical Issue: Random UUIDs (UUIDv4) kill database performance through B-Tree fragmentation, even with narrow primary keys. ULIDs/UUIDv7 solve this by being time-sortable.
The Root Cause: Random UUIDs Fragment B-Trees
Why UUIDs Hurt Performance:
Random UUIDs scatter inserts across the B-Tree structure instead of appending sequentially:
text
UUIDv4 (Random):
├─ Insert 1: UUID = 8f4e3c2a-... → Lands in page 527 (middle of tree)
├─ Insert 2: UUID = 1a2b3c4d-... → Lands in page 12 (beginning of tree)
├─ Insert 3: UUID = f9e8d7c6-... → Lands in page 983 (end of tree)
└─ Result: Every insert lands randomly, causes page splits everywhere
Sequential INT:
├─ Insert 1: ID = 1 → Appends to rightmost page
├─ Insert 2: ID = 2 → Appends to rightmost page
├─ Insert 3: ID = 3 → Appends to rightmost page
└─ Result: All inserts append sequentially, no fragmentationSpecific Performance Problems:
- Page Density Degradation: Random inserts leave pages partly empty after splits (theory ~69% average fill) vs. near-full for sequential
- Cache Inefficiency: Buffer cache thrashing through many pages instead of hot pages
- Write IOPS Explosion: Every insert requires multiple page reads/writes for splits
- Index Bloat: Primary indexes grow noticeably larger than optimal (measure with pgstatindex)
Kịch bản minh hoạ, không phải sự cố có nguồn (số liệu bên dưới là ví dụ; đo bằng pgstatindex và pg_stat_io trên hệ thống của bạn):
sql
-- PostgreSQL 18 (minh hoạ, không chạy độc lập: giả định bảng orders đã có ~100M hàng)
-- Table: 100M rows (~100GB)
-- Workload: 10,000 sustained writes/second for 1 hour
-- With UUIDv4 Primary Key:
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- Random!
customer_id INT,
amount DECIMAL(10,2),
created_at TIMESTAMP
);
-- Số minh hoạ cho kịch bản (không phải số đo thật, không có nguồn; chỉ cho thấy thứ tự độ lớn):
-- Write IOPS: 3,200 (maxed out gp3 baseline)
-- Write Latency P99: 380ms
-- Index size after 1 week: 78GB
-- Page density: 58% (42% wasted space!)
-- Buffer cache hit ratio: 65% (thrashing)
-- Problem diagnosis:
SELECT * FROM pg_stat_user_tables WHERE relname = 'orders';
-- seq_scan: 0
-- idx_scan: 12M
-- n_tup_ins: 100M (minh hoạ: khớp với bảng 100M dòng; 604M trong một tuần mâu thuẫn mức ghi 10 000 dòng/giây)
-- n_tup_upd: 0
-- n_tup_del: 0
-- Result: Pure insert workload, yet horrible write performance
-- Check index fragmentation (pgstatindex đo index; pgstattuple() đo heap):
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT index_size, avg_leaf_density, leaf_fragmentation FROM pgstatindex('orders_pkey');
-- Kết quả minh hoạ: avg_leaf_density thấp (ví dụ ~58) = trang lá còn nhiều chỗ trống do page splitThe Solution: ULIDs (or UUIDv7)
What are ULIDs?
ULIDs combine timestamp-based ordering with randomness:
- First 48 bits: Unix timestamp in milliseconds (sortable!)
- Remaining 80 bits: Random values (uniqueness)
- Result: Time-sortable unique identifiers that behave like sequential keys
Standard Alternative: UUIDv7 (official IETF standard, RFC 9562)
- Same concept as ULID
- Standard UUID format (8-4-4-4-12 hex)
- Slightly different timestamp encoding
python
# Python (minh hoạ, không chạy độc lập: cần gói python-ulid)
from ulid import ULID
id1 = ULID() # ví dụ: 01ARZ3NDEKTSV4RRFFQ69G5FAV
id2 = ULID()
# So sánh chuỗi chỉ đảm bảo thứ tự theo mili-giây; trong cùng một mili-giây
# thứ tự chỉ được đảm bảo nếu dùng bộ sinh monotonic.sql
-- PostgreSQL 18
SELECT uuidv7(); -- ví dụ: 018e3f3c-9f1a-7xxx-xxxx-xxxxxxxxxxxx
-- ^^^^^^^^ phần thời gian (sắp xếp được)B-Tree Behavior with ULID:
text
ULID (Time-Sortable):
├─ Insert 1 (t=1000): 01ARZ3ND... → Appends to rightmost page ✅
├─ Insert 2 (t=1001): 01ARZ3NE... → Appends to rightmost page ✅
├─ Insert 3 (t=1002): 01ARZ3NF... → Appends to rightmost page ✅
└─ Result: Sequential inserts, no page splits, optimal densityPerformance Benchmarks: UUIDv4 vs ULID
Kịch bản minh hoạ, không phải benchmark có nguồn: các số IOPS, độ trễ, kích thước index bên dưới đến từ một bài blog, chưa được kiểm chứng độc lập; hãy đo lại trên workload của bạn.
Test Setup:
- Database: PostgreSQL 14 on AWS r6g.2xlarge RDS
- Storage: gp3 (3000 IOPS baseline, 125 MB/s throughput)
- Workload: 10,000 sustained writes/second for 1 hour
- Table size: 100M rows (~100GB)
Results:
| Metric | UUIDv4 | ULID | Improvement |
|---|---|---|---|
| Write IOPS | 3,200 | 1,100 | 66% reduction ✅ |
| Write Latency P99 | 380ms | 45ms | 8.4x faster ✅ |
| Index Size (1 week) | 78GB | 43GB | 35GB savings (45%) ✅ |
| Page Density | 58% | 94% | 62% better space utilization ✅ |
| Buffer Cache Hit Ratio | 65% | 89% | 37% better cache efficiency ✅ |
Cơ chế đằng sau chênh lệch (minh hoạ, không phải số đo):
text
UUIDv4: mỗi lần chèn đi vào một lá ngẫu nhiên
1. Tìm lá trong B-Tree: lá thường không nằm trong cache -> đọc từ đĩa
2. Lá đầy -> tách trang: ghi trang cũ và trang mới
3. Cập nhật trang cha (có thể tách tiếp lên trên)
ULID / UUIDv7: mỗi lần chèn đi vào lá ngoài cùng bên phải
1. Lá đó đã nằm trong cache
2. Chưa đầy thì chỉ thêm bản ghi; hiếm khi phải tách trangSố trang đọc/ghi mỗi lần chèn phụ thuộc kích thước index so với cache: đo bằng pg_stat_io (PostgreSQL 16+) hoặc Innodb_pages_written / Innodb_buffer_pool_reads (MySQL).
Migration Strategy: UUIDv4 → ULID
Production-Safe Migration (gần như không downtime):
Cách làm dual-write trong bài blog tham chiếu kéo dài khoảng 7 tháng (Day 0 → Day 210):
sql
-- PostgreSQL 18 (minh hoạ, không chạy độc lập: giả định bảng orders có khoá chính UUID id)
-- Phase 1: Add ULID column (Day 0)
ALTER TABLE orders ADD COLUMN id_ulid TEXT;
-- Phase 2: Build index concurrently (Day 1-7)
CREATE UNIQUE INDEX CONCURRENTLY idx_orders_ulid ON orders(id_ulid);
-- CONCURRENTLY: không chặn ghi trong lúc dựng index (thời gian: đo trên bản sao)
-- Phase 3: Dual-write in application (Day 7 - Day 90)
-- ULID do ứng dụng sinh, truyền qua tham số $1:
INSERT INTO orders (id, id_ulid, customer_id, amount)
VALUES (gen_random_uuid(), $1, 12345, 99.99);
-- Phase 4: Backfill historical records (Day 90 - Day 180)
-- Ứng dụng đọc từng lô khoá chính chưa có ULID, sinh ULID rồi UPDATE theo khoá chính:
SELECT id FROM orders WHERE id_ulid IS NULL LIMIT 10000;
UPDATE orders SET id_ulid = $2 WHERE id = $1;
-- Chạy theo lô nhỏ, ngoài giờ cao điểm
-- Phase 5: Promote ULID to primary key (Day 180)
-- Cần id_ulid NOT NULL (thêm CHECK ... NOT VALID rồi VALIDATE trước để tránh quét bảng dưới khoá), drop/re-point FK tham chiếu.
-- Một ALTER duy nhất lấy khoá ACCESS EXCLUSIVE một lần (hai ALTER rời nhả khoá ở giữa, bảng có lúc không có khoá chính): đặt lock_timeout để thất bại nhanh thay vì xếp hàng chặn mọi truy vấn.
-- Đã chạy trên PostgreSQL 18, bảng 1 triệu dòng: có CHECK (id_ulid IS NOT NULL) đã VALIDATE trước thì ADD PRIMARY KEY USING INDEX mất 2,4 ms; không có CHECK thì Postgres quét bảng để đặt NOT NULL dưới khoá (khoảng 97 ms ở lần đo này và 41 ms ở lần kiểm độc lập (có CHECK đã VALIDATE: 2,4 ms và 5,4 ms): số đổi theo máy, tỉ lệ cỡ 8 đến 40 lần).
SET lock_timeout = '5s';
ALTER TABLE orders DROP CONSTRAINT orders_pkey, ADD CONSTRAINT orders_pkey PRIMARY KEY USING INDEX idx_orders_ulid;
-- Phase 6: Drop old UUID column (Day 210)
-- Chờ 30 ngày để chắc chắn không cần quay lại:
ALTER TABLE orders DROP COLUMN id;
-- Tổng thời gian: khoảng 7 tháng (kèm khoảng đệm an toàn)
-- Downtime: chỉ khoảng ngắn khi giữ khoá ở Phase 5-6Key Migration Insights:
- Use CONCURRENTLY:
CREATE INDEXthường chặn ghi vào bảng trong lúc dựng index;CONCURRENTLYthì không - Dual-write period: Allows rollback if issues detected
- Backfill in batches: Prevents long-running transactions
- Wait before dropping old column: Safety net for bugs
- Monitor throughout: Index size, write latency, IOPS
When to Use Each Approach
Use Auto-Increment INT/BIGINT When:
- ✅ Building new systems (simplest, fastest)
- ✅ Single-database deployments (no distributed ID generation)
- ✅ Maximum performance required
- ✅ Integer IDs acceptable in URLs (
/orders/12345) - ✅ No global uniqueness needed across databases
Use ULIDs/UUIDv7 When:
- ✅ Distributed systems (multiple databases, services)
- ✅ Need globally unique IDs without coordination
- ✅ Offline ID generation (mobile apps, edge devices)
- ✅ Data migrations/merges across databases
- ✅ Privacy: hide sequential ID enumeration
❌ Tránh UUIDv4 ngẫu nhiên làm khoá có thứ tự (clustered/B-Tree) khi:
- ❌ Ghi nhiều (đo: số lần tách trang index, IOPS ghi, WAL)
- ❌ Index lớn hơn bộ nhớ đệm
- ❌ Hiệu năng ghi quan trọng (UUID ngẫu nhiên làm tăng write amplification; mức tăng đo bằng workload của bạn)
- ✅ Thay thế: UUIDv7/ULID cho lợi ích tương tự mà không rải chèn khắp cây
Database-Specific Considerations
PostgreSQL:
sql
-- Hai lựa chọn dùng tên bảng khác nhau nên chạy cả khối được (Option 1 cần extension, sẽ lỗi nếu chưa cài; bỏ qua nó nếu không dùng).
-- Option 1 (extension bên thứ ba `pgx_ulid`, không có sẵn trong PostgreSQL; đã build từ source Rust/pgrx 0.17 với `--features pg18` và chạy trên PostgreSQL 18)
-- Tên extension là pgx_ulid: `CREATE EXTENSION ulid;` báo `extension "ulid" is not available`.
CREATE EXTENSION pgx_ulid;
CREATE TABLE orders_ulid_pg (
id ULID PRIMARY KEY DEFAULT gen_ulid()
-- , các cột khác ...
);
-- Option 2 (preferred): UUIDv7 built-in (PostgreSQL 18+)
CREATE TABLE orders_v7 (
id UUID PRIMARY KEY DEFAULT uuidv7() -- UUIDv7
-- , các cột khác ...
);
-- Monitor index health (pgstatindex đọc cả index: chạy ngoài giờ cao điểm):
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('orders_v7_pkey');
-- Ngưỡng 'khoẻ' phụ thuộc workload: so với baseline của chính index này, không dùng một ngưỡng cố định.MySQL InnoDB:
sql
-- MySQL 8.4
-- Option 1: ULID do ứng dụng sinh (CHAR(26) = 26 byte trong PK và trong mọi secondary index)
CREATE TABLE orders_ulid (
id CHAR(26) PRIMARY KEY, -- ULID: 26 ký tự base32
customer_id INT
);
INSERT INTO orders_ulid VALUES ('01ARZ3NDEKTSV4RRFFQ69G5FAV', 1); -- giá trị do ứng dụng sinh
-- Option 2: UUID 16 byte có thứ tự thời gian
-- MySQL 8.4 không có hàm UUIDv7 dựng sẵn (UUID() trả về UUIDv1).
-- UUID_TO_BIN(UUID(), 1) đổi chỗ phần thời gian nên giá trị tăng dần theo thời gian.
CREATE TABLE orders_v1 (
id BINARY(16) PRIMARY KEY,
customer_id INT
);
INSERT INTO orders_v1 VALUES (UUID_TO_BIN(UUID(), 1), 1), (UUID_TO_BIN(UUID(), 1), 2);
-- UUIDv7 sinh ở ứng dụng thì lưu thẳng vào BINARY(16).High-Concurrency Edge Case (ghi rất cao trên một index, ví dụ vài chục nghìn ghi/giây):
Ngay cả khoá tăng dần cũng dồn mọi lần chèn vào cùng một lá ngoài cùng bên phải, gây tranh chấp. Chia theo khoảng thời gian không giải quyết được (ghi hiện tại vẫn dồn vào lá cuối của partition hiện tại); chia theo hash trải các lần chèn lên nhiều cây:
sql
-- PostgreSQL 18
CREATE TABLE orders_h (
id UUID DEFAULT uuidv7(),
PRIMARY KEY (id) -- khoá chính của bảng partition phải gồm cột partition
) PARTITION BY HASH (id);
CREATE TABLE orders_h0 PARTITION OF orders_h FOR VALUES WITH (MODULUS 4, REMAINDER 0);
CREATE TABLE orders_h1 PARTITION OF orders_h FOR VALUES WITH (MODULUS 4, REMAINDER 1);
CREATE TABLE orders_h2 PARTITION OF orders_h FOR VALUES WITH (MODULUS 4, REMAINDER 2);
CREATE TABLE orders_h3 PARTITION OF orders_h FOR VALUES WITH (MODULUS 4, REMAINDER 3);
-- Đánh đổi: mất cắt partition theo thời gian; mỗi partition có lá cuối riêngAnti-Pattern: "But UUIDs are Standard!"
❌ Bad Reasoning:
"We use UUIDv4 because it's an industry standard and every language has UUID libraries."
Why It's Wrong:
- UUID v4 ngẫu nhiên làm tăng write amplification (mức tăng phụ thuộc kích thước index so với cache; đo bằng workload của bạn)
- "Standard" doesn't mean "performant"
- UUIDv7 is also standard (RFC 9562, 2024) and performant
✅ Good Reasoning:
"We use UUIDv7 (or ULID) because:
- Standard format (UUID libraries support v7)
- Time-sortable (no B-Tree fragmentation)
- Globally unique (distributed systems)
- Performance: chèn tuần tự vào lá cuối thay vì rải ngẫu nhiên (đo mức cải thiện trên workload của bạn)"
Quick Reference: ID Type Decision Matrix
| ID Type | Size | Sequential | Global Unique | Use Case |
|---|---|---|---|---|
| INT AUTO_INCREMENT | 4 bytes | ✅ | ❌ | Single DB, max performance |
| BIGINT AUTO_INCREMENT | 8 bytes | ✅ | ❌ | Single DB, >2B rows |
| UUIDv4 (Random) | 16 bytes | ❌ | ✅ | ❌ tránh làm khoá chính của bảng ghi nhiều (phân mảnh B-Tree, đo bằng pgstatindex) |
| UUIDv7 / ULID | 16 bytes | ✅ | ✅ | Distributed systems, best of both ✅ |
| Snowflake ID | 8 bytes | ✅ | ✅ | Twitter-style distributed ID |
| KSUID | 20 bytes | ✅ | ✅ | Similar to ULID, larger random portion |
Default Recommendation (2026):
- New projects: ULID hoặc UUIDv7 khi cần ID sinh phía client/phân tán
- Single database: INT/BIGINT AUTO_INCREMENT (đơn giản nhất)
- Existing UUIDv4: cân nhắc chuyển sang UUIDv7/ULID khi đo thấy index lớn hơn bộ nhớ đệm và độ trễ ghi tăng (không có ngưỡng ghi/giây cố định)
Measuring Fragmentation in Production
PostgreSQL:
sql
-- PostgreSQL 18
CREATE EXTENSION IF NOT EXISTS pgstattuple;
-- Mật độ lá của index khoá chính
SELECT leaf_fragmentation, avg_leaf_density FROM pgstatindex('orders_pkey');
-- Ước lượng cho bảng, dùng visibility map, không quét toàn bảng
SELECT approx_tuple_percent, dead_tuple_percent FROM pgstattuple_approx('orders');
-- Cách đọc: index B-Tree mặc định fillfactor 90, mật độ lá ~90 là index mới dựng;
-- chèn ngẫu nhiên kéo mật độ xuống quanh 70 (lý thuyết ln 2 ≈ 69%).
-- Tốt nhất so với chính index của bạn sau REINDEX CONCURRENTLY.
-- Lưu ý: pgstatindex đọc toàn bộ index; trên index lớn hãy chạy ngoài giờ cao điểm.MySQL InnoDB:
sql
-- MySQL 8.4
-- information_schema.tables dùng số liệu đệm (information_schema_stats_expiry, mặc định 24 giờ): ANALYZE trước
ANALYZE TABLE orders_int;
SELECT table_name,
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
ROUND(index_length / 1024 / 1024, 2) AS index_mb,
ROUND(data_free / 1024 / 1024, 2) AS free_mb
FROM information_schema.tables
WHERE table_schema = DATABASE() AND table_name = 'orders_int';
-- Lưu ý: data_free là chỗ trống chưa cấp cho trang nào, KHÔNG phản ánh trang B-Tree đầy dở sau khi tách trang.
-- Đo thật: bảng PK ngẫu nhiên 500 000 hàng có data_length 113.8 MB (data_free 5%) và còn 80.6 MB sau OPTIMIZE TABLE;
-- bảng chèn tuần tự 70.6 MB. So sánh data_length trước/sau rebuild trên bản sao thay vì dựa vào data_free.
-- Sửa phân mảnh (dựng lại cả bảng; cần chỗ đĩa tạm cỡ bảng, tạo tải I/O và độ trễ replica):
-- OPTIMIZE TABLE orders_int;
-- InnoDB làm OPTIMIZE TABLE bằng recreate + analyze, vẫn cho DML đồng thời (trừ bảng có FULLTEXT).
-- Thử trên bản sao trước; dùng pt-online-schema-change hoặc gh-ost nếu cần kiểm soát tốc độ.Real-World Case Study: E-Commerce Platform
Kịch bản minh hoạ, không phải sự cố có nguồn: các số trong mục này lấy từ một bài blog, chưa kiểm chứng độc lập.
Background:
- 100M orders, $500M GMV/year
- Peak: 10,000 orders/second (Black Friday)
- Database: PostgreSQL 14, AWS RDS r6g.2xlarge
- Problem: Write IOPS maxed out (3200), P99 latency 380ms
Root Cause Analysis:
sql
-- Step 1: Identify write-heavy tables
SELECT
schemaname,
relname,
n_tup_ins AS inserts,
n_tup_upd AS updates,
pg_size_pretty(pg_total_relation_size(relid)) AS size
FROM pg_stat_user_tables
ORDER BY n_tup_ins DESC
LIMIT 5;
-- Result: orders table = 100M inserts (số minh hoạ)
-- Size: 78GB (expected: ~45GB for 100M rows)
-- Step 2: Check index fragmentation
SELECT * FROM pgstattuple('orders_pkey');
-- tuple_percent: 58.3%
-- free_percent: 41.7%
-- Diagnosis: UUIDv4 primary key causing massive fragmentation!Solution Implemented:
sql
-- Migration to UUIDv7 (7-month timeline)
-- Phase 1-6: See migration strategy above
-- Results after migration:
-- Write IOPS: 3200 → 1100 (66% reduction)
-- Write latency P99: 380ms → 45ms (8.4x improvement)
-- Index size: 78GB → 43GB (45% savings)
-- AWS RDS cost: $850/mo → $450/mo (47% savings from IOPS reduction)
-- Black Friday performance:
-- Before: System crashed at 8,000 orders/sec (IOPS limit)
-- After: Handled 12,000 orders/sec with headroomKey Learnings:
- UUIDv4 fragmentation not obvious until high scale (>10M rows)
- Migration took 7 months but paid for itself in 2 months (cost savings)
- Monitoring index health early prevents costly migrations later
- UUIDv7/ULID should be default choice for new distributed systems
Phải nhớ:
- PRIMARY KEY của InnoDB là chính bảng và có mặt trong mọi secondary index: chọn PK hẹp, tăng dần (
BIGINT AUTO_INCREMENT, hoặcBINARY(16)có thứ tự thời gian nhưUUID_TO_BIN(UUID(), 1), UUIDv7, ULID). - UUID ngẫu nhiên làm PK rải chèn khắp cây, trang đầy dở và index phình ra; đo bằng
mysql.innodb_index_stats(MySQL) hoặcpgstatindex(PostgreSQL), không đoán. - Kiểm tra bằng số thật:
EXPLAIN(Using index= covering),ANALYZE TABLErồi sodata_lengthtrước/sau rebuild;data_freekhông cho biết trang đầy dở.
Further Reading:
- ULID Spec - Official ULID specification
- RFC 9562: UUIDv7 - IETF standard for UUIDv7
- PostgreSQL pgstattuple - Index health monitoring
- Bài gốc là một bài blog trên Medium (tác giả beyond-localhost); số liệu trong các kịch bản ở trên chưa kiểm chứng độc lập.