Prometheus: từ instrumentation đến PromQL
Prometheus thu thập và lưu time series; Grafana thường query Prometheus để hiển thị. Metrics hiệu quả vì aggregate bounded dimensions; unbounded labels biến monitoring thành memory/cost incident.
1. Kiến trúc và data flow
Java/Spring Actuator /metrics
↓ HTTP scrape
Prometheus + service discovery
↓ TSDB + PromQL + rules
Grafana dashboard Alertmanager notificationsPrometheus chủ động pull metrics từ targets theo scrape interval. Service discovery tìm targets; relabeling chỉnh target labels trước khi ingest. Pushgateway chỉ phù hợp một số batch job ngắn hạn, không phải cách mặc định biến Prometheus thành push system.
2. Time-series data model
Một series được xác định bởi metric name và toàn bộ label set. Thay một label value là tạo series khác.
- Counter: chỉ tăng hoặc reset khi process restart; query bằng
rate/increase. - Gauge: tăng giảm tự do như queue depth, memory usage hoặc active connections.
- Histogram: sinh bucket, sum và count; aggregate được giữa instances rồi ước lượng quantile.
- Summary: client-side quantile không aggregate đúng giữa instances.
Dùng base units như seconds/bytes. Không lấy rate() trên gauge; không alert trực tiếp từ raw counter tích lũy.
3. RED, USE và business signals
RED: Rate, Errors, Duration cho request services. USE: Utilization, Saturation, Errors cho resources. Thêm JVM GC/allocation/threads, DB/HTTP pool active/wait/timeout, queue age/lag, cache hit/eviction và business outcomes—nhưng chỉ với dimensions bounded.
4. PromQL mental model
Luôn xác định metric, time window, labels cần group và denominator có cùng scope không.
# Request rate theo service
sum by (service) (rate(http_server_requests_seconds_count[5m]))
# Error ratio
sum(rate(http_server_requests_seconds_count{status=~"5.."}[5m]))
/
sum(rate(http_server_requests_seconds_count[5m]))
# P95 từ histogram
histogram_quantile(
0.95,
sum by (le, service) (rate(http_server_requests_seconds_bucket[5m]))
)- Dùng
ratetrước rồi mới aggregate counters để xử lý reset theo từng series. - Vector matching dùng
on/ignoring; many-to-many match thường báo query sai. absent()tìm missing series, nhưng “không data” có thể là scrape lỗi, đổi label hoặc traffic bằng 0.
5. Histogram và SLO
Nếu SLO là 95% requests dưới 300 ms, cần bucket le="0.3":
sum(rate(http_server_requests_seconds_bucket{le="0.3"}[5m]))
/
sum(rate(http_server_requests_seconds_count[5m]))histogram_quantile nội suy nên là estimate. Average che tail. Native histograms đã stable từ Prometheus v3.8; vẫn cần kiểm tra compatibility, storage/query behavior và bật scrape/remote-write settings phù hợp với phiên bản triển khai.
6. Cardinality budget
Số series xấp xỉ tích các label combinations. Không dùng user/order/trace ID, raw URL, email, exception message hay timestamp làm label. Chuẩn hóa route/error code; chi tiết sang logs/traces hoặc exemplars.
7. Rules và Alertmanager
Recording rule precompute PromQL đắt hoặc dùng lặp lại. Alert rule đánh giá condition, dùng for tránh transient noise và gắn labels/annotations. Alertmanager group, route, silence và inhibit notifications; nó không tự tạo condition từ raw metrics.
groups:
- name: service-sli
rules:
- record: service:http_requests:error_ratio_rate5m
expr: |
sum by (service) (rate(http_server_requests_seconds_count{status=~"5.."}[5m]))
/
sum by (service) (rate(http_server_requests_seconds_count[5m]))Alert production nên dựa user impact/SLO burn rate, có owner, runbook, severity và test.
8. Remote write và HA
- Local retention phù hợp fast query và rule evaluation.
- Remote write đưa samples sang long-term backend; theo dõi queue, retries và dropped samples.
- Hai HA replicas scrape cùng targets; global query cần deduplication.
- Federation lấy tập metrics chọn lọc, không thay mọi long-term architecture.
- Backup config/rules; TSDB không phải nguồn dữ liệu nghiệp vụ.
9. Debug checklist
- Target có trong discovery và scrape status là gì?
- Endpoint metrics trả đúng content, timeout và sample volume không?
- Labels có bị relabel/drop hoặc đổi sau deploy không?
- PromQL selector có match series và đúng time range không?
- Rule evaluation có error/query timeout/missing data không?
- Alert firing nhưng routing/silence/inhibition chặn ở đâu?