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ực | Vai trò | Caveat |
|---|---|---|
| Shared buffers | Cache 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 memory | Session 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 memory | VACUUM, CREATE INDEX và maintenance operations. | Nhiều workers/jobs có thể nhân tổng memory. |
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
pg_stat_activitycho sessions, waits và current work.- Checkpointer/background-writer statistics cho checkpoint và buffer writes.
pg_stat_walvà archive metrics cho WAL rate/retention.- Database và OS I/O latency, fsync behavior, CPU, memory pressure.
- Connection active/idle/waiting và pool acquisition latency.