Part 04 · PostgreSQL & Redis · 4.1.01

Process, memory, storage và WAL

PostgreSQL là một hệ thống nhiều processes với shared cache, page-oriented storage và write-ahead log. Query latency và durability phụ thuộc cách các lớp này phối hợp với OS và disk.


Process model

Postmaster lắng nghe connections, tạo backend process cho từng client và quản lý auxiliary processes như checkpointer, background writer, WAL writer, autovacuum và archiver. Mỗi connection có process riêng nên connection count tiêu thụ memory và scheduling; pool phải bounded theo database capacity, không theo số application requests tối đa.

Memory model

Khu vựcVai tròCaveat
Shared buffersCache pages dùng chung giữa backends.OS page cache vẫn tham gia; cache hit cao không chứng minh query tối ưu.
WAL buffersĐệm WAL records trước khi flush.Commit latency phụ thuộc durability setting và storage.
Backend private memorySession state, plan/execution memory.work_mem áp cho từng sort/hash node, không phải mỗi connection một lần.
Maintenance memoryVACUUM, CREATE INDEX và maintenance operations.Nhiều workers/jobs có thể nhân tổng memory.
Memory multiplication: nhiều query nodes × parallel workers × active connections có thể làm tổng memory vượt xa một giá trị work_mem. Tuning phải dựa concurrency và execution plans thực.

Storage layout

Database cluster chứa databases và tablespaces. Mỗi relation chia thành segments và fixed-size pages; page có header, item identifiers, tuples và free space. TOAST compress hoặc lưu values lớn ngoài main row. Free Space Map theo dõi chỗ trống; Visibility Map hỗ trợ VACUUM và index-only scan.

Buffer manager

Backend tìm page trong shared buffers, pin/lock buffer, đọc disk khi miss và đánh dirty khi sửa. Background writer và checkpoint phân bổ writes, nhưng backend vẫn có thể phải tự write khi thiếu reusable buffers. Phân tích cần kết hợp cache hits, read/write latency và plan, không chỉ nhìn hit ratio.

Write-Ahead Logging

WAL records mô tả thay đổi đủ để redo. Quy tắc write-ahead yêu cầu WAL durable trước data page tương ứng. Commit thường flush WAL tới durable storage theo synchronous_commit. Full-page images bảo vệ torn pages sau checkpoint. WAL còn phục vụ crash recovery, archive/PITR và replication.

Checkpoint và crash recovery

Checkpoint ghi dirty buffers và tạo recovery point. Checkpoint quá thường tạo I/O/WAL spikes; quá thưa kéo dài recovery và WAL retention. Sau crash, startup process replay WAL từ checkpoint để khôi phục consistency. Unlogged tables không có cùng crash-safety và replication guarantees như normal tables.

Quan sát và tuning

Reasoning model: query → backend process → plan nodes và per-node memory → shared/OS cache → page I/O → WAL/commit path. Mỗi tuning change phải nêu bottleneck và metric xác nhận.
Nguồn tham khảo