9 lab PostgreSQL và Redis
Mỗi lab phải tạo được failure có kiểm soát, thu evidence trước/sau và kết luận bằng invariant hoặc SLO. Screenshot “chạy được” không đủ; lưu command, config, dataset size, timeline và số đo để người khác tái hiện.
EXPLAIN ANALYZE trên DML production nếu chưa bọc transaction/rollback và hiểu side effect.Schema và business invariants
Mục tiêu: thiết kế order/payment schema có primary key, foreign key, UNIQUE, CHECK, idempotency key và money type an toàn.
Thực hiện
- Viết ít nhất bốn invariants trước khi viết DDL: amount dương, currency hợp lệ, một idempotency key chỉ tạo một payment, state transition không nhận giá trị ngoài domain.
- Tạo tables bằng
numerichoặc integer minor units; đặt constraints trong database và application validation riêng. - Viết migration expand và rollback/forward-fix plan. Nếu down migration làm mất dữ liệu, ghi rõ vì sao không thể rollback tự động.
- Insert dữ liệu hợp lệ rồi cố tình vi phạm từng constraint từ hai writers khác nhau.
- Chạy concurrent duplicate insert để chứng minh
SELECT-then-INSERTkhông thay unique constraint.
Isolation, locking và retry
Mục tiêu: quan sát anomalies và lock waits bằng hai connections thay vì chỉ mô tả lý thuyết.
Thực hiện
- Dùng hai
psqlsessions tái hiện hai SELECT thấy kết quả khác ở Read Committed và snapshot ổn định ở Repeatable Read. - Tạo lost update bằng application read-modify-write, sau đó sửa lần lượt bằng atomic conditional update, version column và
SELECT ... FOR UPDATE. - Tạo deadlock bằng khóa hai accounts theo thứ tự ngược; lưu error/deadlock log rồi sửa bằng sorted lock order.
- Đặt
lock_timeoutvàstatement_timeoutkhác nhau để thấy failure semantics. - Implement bounded retry toàn transaction với fresh state, jitter và idempotent external effects.
pg_stat_activity/pg_locks, deadlock graph, affected-row counts và retry histogram.Index và EXPLAIN
Mục tiêu: cải thiện một query bằng evidence và lượng hóa write/storage cost của index.
Thực hiện
- Seed ít nhất một triệu rows với skew gần production, không dùng distribution đồng đều giả tạo.
- Chọn query có equality, range và ordering; lưu baseline bằng
EXPLAIN (ANALYZE, BUFFERS). - Thử composite index, partial index và
INCLUDEkhi phù hợp; giải thích column order. - Làm statistics cũ hoặc giảm statistics target để quan sát estimate sai, sau đó chạy
ANALYZEvà so plan. - Đặt
work_memthấp trong session để tạo sort/hash spill rồi ghi temp I/O. - Đo insert/update throughput, index size và cache impact; xóa index không còn justify.
Offset và keyset pagination
Mục tiêu: chứng minh latency và consistency behavior của hai pagination strategies.
Thực hiện
- Dùng dataset Lab 03 và stable ordering
ORDER BY created_at DESC, id DESC. - Benchmark page đầu, giữa và rất sâu bằng OFFSET; ghi rows scanned và buffers.
- Implement cursor chứa cả
created_atlẫn unique tie-breakerid; encode cursor opaque và direction-aware. - Insert/delete rows giữa hai page requests. Ghi rõ semantics mong muốn rồi kiểm tra duplicate/missing của mỗi strategy.
- Test nhiều rows cùng timestamp, reverse pagination và invalid/tampered cursor.
Cache-aside và stale-data race
Mục tiêu: xây cache có ownership, freshness và failure behavior đo được.
Thực hiện
- Cache endpoint GET order với key gồm namespace/version/tenant, TTL và jitter.
- Đo hit, miss, origin latency và cache latency theo endpoint/key class.
- Update DB rồi invalidate; dùng barriers/delays để tái hiện reader set lại value cũ sau invalidation.
- Sửa race bằng versioned value hoặc event/outbox invalidation; xác định stale window còn lại.
- Thêm negative caching TTL ngắn và test object được tạo sau một negative hit.
- Tắt/làm chậm Redis; fallback DB phải có timeout, concurrency cap và không vượt request deadline.
Stampede protection và Redis failover
Mục tiêu: giới hạn origin amplification và quan sát data-loss/client-recovery semantics.
Thực hiện
- Cho 100 requests đồng thời miss một hot key; đếm DB calls, peak concurrency và p99.
- Thêm per-process single-flight, sau đó chạy nhiều application instances để thấy giới hạn.
- Thử distributed lease hoặc stale-while-revalidate; kill holder và kiểm tra waiter deadline/fallback.
- Dựng primary/replicas với Sentinel hoặc một Redis Cluster local; tạo sustained writes rồi fail primary.
- Đo detection, promotion, client reconnect, replication lag và acknowledged writes bị mất/duplicate retry.
- Thử cache warmup có rate limit sau recovery thay vì nạp toàn bộ cùng lúc.
MVCC và autovacuum forensic
Mục tiêu: nối long transaction với dead tuples, vacuum progress và table growth.
Thực hiện
- Tạo table đủ lớn, mở transaction giữ snapshot và chạy workload update/delete ở session khác.
- Quan sát transaction age/xmin trong
pg_stat_activity, live/dead tuples trong statistics và relation size. - Chạy VACUUM/đợi autovacuum; dùng progress views/logs để giải thích vì sao tuples chưa reclaim được.
- Commit/rollback long transaction, chạy VACUUM và quan sát visibility/dead tuple thay đổi.
- Chứng minh regular VACUUM làm space reusable nhưng thường không trả file ngay cho OS; so với rewrite operation trong lab cô lập.
- Thử HOT-eligible và indexed-column update để so heap/index amplification.
PostgreSQL replication và PITR
Mục tiêu: đo RPO/RTO thực tế của physical standby và archived recovery.
Thực hiện
- Dựng primary/standby, tạo slot có retention guard và theo dõi sent/write/flush/replay LSN.
- Test read-after-write trên replica ở các mức lag khác nhau; implement route/wait timeout.
- Fail primary, fence node cũ, promote standby và redirect client; ghi timeline/timeline ID.
- Archive WAL, tạo base backup và restore point; thực hiện một lệnh DELETE có marker timestamp.
- Restore vào cluster cô lập tới thời điểm trước DELETE, validate data và application query.
- Làm hỏng một credential hoặc bỏ một WAL segment để chứng minh alert/runbook phát hiện restore gap.
Redis durability và cluster incident
Mục tiêu: phân biệt process recovery, persistence durability, replica failover và cluster reshard behavior.
Thực hiện
- Chạy cùng write workload với RDB-only và AOF
everysec; kill process/host simulation rồi đếm acknowledged records còn lại. - Trigger snapshot/AOF rewrite dưới write load; đo fork duration, COW memory, latency và disk behavior.
- Tạo slow/disconnected replica, quan sát backlog/output buffer rồi buộc full resync.
- Với Sentinel, ghi SDOWN/ODOWN/election/promotion và client rediscovery; với Cluster, migrate slots và capture
ASK/MOVED. - Tạo hot slot/key để chứng minh thêm node không tự chia một key; rebalance và đo giới hạn còn lại.
- Restore persistence artifact vào instance cô lập, validate key count, sampled values và TTL.
Definition of Done cho mỗi lab
- Repository hoặc scripts có README ghi prerequisites, versions và exact commands.
- Failure được tái hiện trước khi fix; evidence có timestamp và workload/dataset context.
- Expected result được viết trước, actual result và sai lệch được giải thích.
- Không để credentials, dumps chứa PII hoặc destructive automation không có guard.
- Kết luận nêu invariant/SLO được bảo vệ, trade-off và known limitation.
- Cleanup được chạy và môi trường lab trở về trạng thái xác định.