
Logging, distributed tracing, metrics, alertingLogging, distributed tracing, metrics, alerting
Mười hai service, một checkoutTwelve services, one checkout.Một request checkout đi qua 12 service trước khi khách thấy chữ "Đặt hàng thành công". SLO hứa 99,9% thành công, tức chỉ 43 phút lỗi mỗi tháng.A checkout request crosses 12 services before the shopper sees "Order placed". The SLO promises 99.9% success, which means only 43 minutes of errors a month.
Hãy đặt mình vào vị trí on-call lúc 14:02, khi checkout bỗng chậm gần 2 giây mà chưa ai biết vì sao. Service gửi trace, metric và log qua OTLP tới OpenTelemetry Collector, collector chia vào Prometheus, Tempo và Loki, còn Grafana nối cả ba bằng trace_id để đi từ biểu đồ tới đúng dòng log trong vài cú nhấp. Chạy luồng điều tra trước, rồi thử “Burn rate vượt ngưỡng”, “Nhãn user_id” và “Collector sập” để thấy cảnh báo theo SLO, cái giá của cardinality và vì sao hệ quan sát hỏng không được kéo request hỏng theo.Put yourself on call at 14:02, when checkout suddenly takes almost 2 seconds and nobody knows why. Services send traces, metrics and logs over OTLP to the OpenTelemetry Collector, which splits them into Prometheus, Tempo and Loki, and Grafana joins all three by trace_id so you go from a chart to the exact log line in a few clicks. Play the investigation first, then try “Burn-rate alert”, “user_id label” and “Collector down” to see SLO alerting, the cost of cardinality, and why broken telemetry must never break requests.
1Từ 14:02, một phần request checkout mất gần 2 giây. CheckoutController.checkout (Go: checkout bọc trong instrument) gọi order service qua OrderClient (Go: client có otelhttp.NewTransport), header traceparent đi kèm nên cả hai span thuộc cùng một trace.From 14:02, some checkout requests take almost 2 seconds. CheckoutController.checkout (Go: checkout wrapped by instrument) calls the order service through OrderClient (Go: a client with otelhttp.NewTransport), which adds a traceparent header, so both spans belong to one trace.
Log dạng chuỗi tự do, không có định danh request, buộc người điều tra grep theo thời gian và đoán. Ghi log JSON một dòng (Logback + logstash-encoder, Go log/slog JSONHandler), luôn có trace_id, span_id, request_id, service, level. Micrometer Tracing đưa traceId vào MDC tự động.Free-form log strings with no request identifier force investigators to grep by timestamp and guess. Write one-line JSON logs (Logback with logstash-encoder, Go log/slog JSONHandler) that always include trace_id, span_id, request_id, service and level. Micrometer Tracing puts traceId into the MDC automatically.
Mỗi service tự tạo trace mới vì không đọc header từ upstream. Dùng W3C traceparent làm propagator chung, instrument cả HTTP client và server (otelhttp, Spring RestClient tự cấu hình), và truyền context qua Kafka bằng header của message.Each service starts a new trace because it never reads the upstream header. Use W3C traceparent as the shared propagator, instrument both HTTP client and server (otelhttp, an auto-configured Spring RestClient), and carry the context through Kafka in message headers.
Mỗi tổ hợp nhãn là một time series trong bộ nhớ Prometheus. user_id, order_id, URL thô hay email làm số series bùng nổ. Nhãn chỉ dùng tập giá trị nhỏ và cố định (route template, method, code); giá trị cao để vào span hoặc log. Đặt sample_limit và theo dõi prometheus_tsdb_head_series.Every label combination is a time series in Prometheus memory. user_id, order_id, raw URLs or emails make the series count explode. Labels take only small, fixed value sets (route template, method, code); high-cardinality values go into spans or logs. Set sample_limit and watch prometheus_tsdb_head_series.
Trung bình 120 ms có thể che 2% request mất 3 giây. Dùng histogram với bucket bám theo ngưỡng SLO (0,1 · 0,3 · 0,8 · 2 s) và tính p99 bằng histogram_quantile trên toàn cụm. Summary tính phân vị tại từng instance nên không cộng gộp được.A 120 ms average can hide 2% of requests taking 3 seconds. Use histograms with buckets aligned to the SLO thresholds (0.1, 0.3, 0.8, 2 s) and compute p99 with histogram_quantile across the cluster. Summaries compute quantiles per instance and cannot be aggregated.
CPU 85% hay một pod restart chưa chắc làm người dùng đau, nhưng vẫn gọi người dậy lúc 3 giờ sáng. Chỉ page khi ngân sách lỗi bị đốt nhanh (multi-window burn rate 14,4x trong 1 giờ, 6x trong 6 giờ); nguyên nhân để trên dashboard hoặc thành ticket.85% CPU or one pod restart may not hurt users, yet it wakes someone at 3 a.m. Page only when the error budget burns fast (multi-window burn rate of 14.4x over 1 hour, 6x over 6 hours); causes belong on dashboards or in tickets.
Giữ 100% trace ở 12k rps rất tốn. Head sampling (ví dụ 10%) quyết định ngay ở đầu nên rẻ nhưng có thể bỏ sót trace lỗi. Tail sampling ở collector chờ trace hoàn tất rồi giữ mọi trace lỗi hoặc chậm hơn 1 s, cộng 5% số còn lại.Keeping 100% of traces at 12k rps is expensive. Head sampling (say 10%) decides at the start, which is cheap but may drop error traces. Tail sampling in the collector waits for the trace to complete and keeps every error or trace slower than 1 s, plus 5% of the rest.
Gửi span đồng bộ hay ghi log chặn có thể làm request chậm khi collector có sự cố. SDK dùng BatchSpanProcessor với hàng đợi giới hạn, đầy thì bỏ span chứ không chặn; collector chạy dạng agent cạnh service với memory_limiter.Exporting spans synchronously or blocking on log writes can slow requests when the collector has trouble. The SDK uses a BatchSpanProcessor with a bounded queue that drops spans instead of blocking when full; the collector runs as an agent next to the service with a memory_limiter.
| BảngTable | Cột chínhKey columns | Ghi chúNotes |
|---|---|---|
log line (Loki) | ts, level, service, env, trace_id, span_id, request_id, msg, fields… | Nhãn Loki chỉ là service, env, level; trace_id là trường JSON, tra bằng | json, không làm nhãnLoki labels are only service, env and level; trace_id is a JSON field queried with | json, never a label |
http_server_request_duration_seconds | histogram · labels: service, route, method, code · buckets 0.05 0.1 0.3 0.8 2 5 | Nguồn của RED: rate từ _count, errors từ code=~"5..", duration từ histogram_quantileThe source of RED: rate from _count, errors from code=~"5..", duration from histogram_quantile |
span (Tempo) | trace_id, span_id, parent_span_id, name, service, start, duration, status, attributes | Thuộc tính giá trị cao như user.id, order.id đặt ở đây, không ở metricHigh-cardinality attributes such as user.id and order.id live here, not in metrics |
slo | service, sli, objective, window, fast_burn, slow_burn, runbook_url | Ví dụ checkout · success ratio · 99.9% · 30d · 14.4x/1h · 6x/6h; sinh ra recording rule và alertE.g. checkout · success ratio · 99.9% · 30d · 14.4x/1h · 6x/6h; generates recording rules and alerts |
CheckoutController và MetricsConfig (Java), instrument và checkout (Go) chạy trong hộp Checkout Service ở sơ đồ: observation gắn nhãn ít giá trị cho metric, nhãn nhiều giá trị chỉ cho span, log mang trace_id, tất cả gửi qua hộp OTel Collector. slo-rules.yml là rule của hộp Prometheus, cảnh báo theo burn rate tới hộp Alertmanager.CheckoutController and MetricsConfig (Java), instrument and checkout (Go) run in the Checkout Service box in the diagram: the observation puts low-cardinality tags on metrics and high-cardinality ones on the span only, logs carry the trace_id, and everything goes through the OTel Collector box. slo-rules.yml holds the Prometheus box's rules, alerting on burn rate to the Alertmanager box.
package com.example.checkout;
import io.micrometer.observation.Observation;
import io.micrometer.observation.ObservationRegistry;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequiredArgsConstructor
public class CheckoutController {
private final ObservationRegistry registry;
private final OrderClient orders; // RestClient from the builder: traceparent added for you
@PostMapping("/checkout")
public CheckoutResult checkout(@RequestBody CheckoutRequest req) {
return Observation.createNotStarted("checkout", registry)
.lowCardinalityKeyValue("payment.method", req.paymentMethod()) // metric tag + span
.highCardinalityKeyValue("cart.id", req.cartId()) // span only
.observe(() -> {
log.info("checkout started items={}", req.items().size()); // MDC has traceId, spanId
return orders.place(req);
});
}
}package main
import (
"context"
"log/slog"
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/trace"
)
var reqDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_server_request_duration_seconds",
Help: "HTTP request latency.",
Buckets: []float64{.05, .1, .3, .8, 2, 5},
}, []string{"route", "method", "code"}) // never user_id
var client = &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport), Timeout: 2 * time.Second}
func logger(ctx context.Context) *slog.Logger {
sc := trace.SpanContextFromContext(ctx)
return slog.Default().With("trace_id", sc.TraceID().String(), "span_id", sc.SpanID().String())
}
func instrument(route string, h http.HandlerFunc) http.Handler {
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, code: http.StatusOK}
h(rec, r)
traceID := trace.SpanContextFromContext(r.Context()).TraceID().String()
obs := reqDuration.WithLabelValues(route, r.Method, strconv.Itoa(rec.code))
obs.(prometheus.ExemplarObserver).ObserveWithExemplar(
time.Since(start).Seconds(), prometheus.Labels{"trace_id": traceID})
})
return otelhttp.NewHandler(inner, route) // reads traceparent, starts the server span
}| Head samplingHead sampling | Tail samplingTail sampling | |
|---|---|---|
| Quyết định khiDecides | Ngay ở span đầu tiên, truyền qua cờ sampled trong traceparentAt the first span, carried by the sampled flag in traceparent | Sau khi trace hoàn tất, tại collectorAfter the trace completes, in the collector |
| Giữ trace lỗiKeeps error traces | Không đảm bảo, lỗi hiếm có thể bị bỏNot guaranteed; rare errors may be dropped | Có, theo luật: mọi lỗi, mọi trace chậm hơn 1 sYes, by policy: every error, every trace slower than 1 s |
| Chi phíCost | Rẻ, không cần bộ nhớ đệmCheap, no buffering | Collector phải giữ span trong bộ nhớ vài giây, cần định tuyến theo trace_idThe collector buffers spans for seconds and needs routing by trace_id |
| Chọn khiPick it when | Lưu lượng vừa phải, cần đơn giảnTraffic is moderate and simplicity matters | Lưu lượng lớn và cần mọi trace lỗi để điều traTraffic is high and every error trace is needed for investigations |
Cảnh báo CPU trên 80%, heap trên 70% kêu hàng trăm lần mỗi tuần mà phần lớn không ảnh hưởng ai, nên on-call quen bấm tắt và bỏ lỡ sự cố thật. Chỉ gọi người khi burn rate vượt 14,4x ở cả cửa sổ 1 giờ và 5 phút, hoặc 6x ở 6 giờ và 30 phút; các tín hiệu nguyên nhân chuyển thành ticket hoặc dashboard.Alerts on CPU above 80% or heap above 70% fire hundreds of times a week, mostly harmlessly, so on-call learns to silence them and misses the real incident. Page only when burn rate exceeds 14.4x on both 1-hour and 5-minute windows, or 6x on 6-hour and 30-minute windows; cause signals become tickets or dashboards.
Một nhãn user_id, order_id hay full URL nhân số series theo số người dùng và có thể đưa Prometheus từ 40 nghìn lên hàng triệu series trong một ngày. Chuẩn hoá route thành mẫu (/orders/{id}), đặt sample_limit cho mỗi target, cảnh báo khi prometheus_tsdb_head_series tăng 50% so với hôm qua.A user_id, order_id or raw URL label multiplies series by user count and can push Prometheus from 40 thousand to millions of series in a day. Normalize routes to templates (/orders/{id}), set a per-target sample_limit, and alert when prometheus_tsdb_head_series grows 50% over yesterday.
Head sampling 1% quyết định ngay từ đầu, nên 99% request lỗi hoặc chậm cũng bị bỏ và lúc cần điều tra thì không có trace nào. Dùng tail sampling ở collector: giữ 100% trace lỗi và trace vượt 800 ms, chỉ lấy mẫu 1-5% trace bình thường, và đảm bảo mọi span của một trace tới cùng một collector.1% head sampling decides up front, so 99% of failing or slow requests are dropped too, and no trace exists when you need one. Use tail sampling in the collector: keep 100% of error traces and traces above 800 ms, sample only 1-5% of normal ones, and route all spans of a trace to the same collector.
Auto-instrumentation có thể ghi cả header Authorization, query string chứa token hay body có số thẻ, rồi giữ 14 ngày trong Loki mà nhiều người đọc được. Bật danh sách header được phép, thêm processor redaction ở collector để xoá các khoá như password, card_number, authorization, và quét log định kỳ tìm mẫu số thẻ.Auto-instrumentation can capture Authorization headers, query strings with tokens or bodies with card numbers, then keep them for 14 days in Loki where many people can read them. Allow-list headers, add a redaction processor in the collector that strips keys like password, card_number and authorization, and scan logs regularly for card-number patterns.
Mỗi pattern mở bài học tương ứng trong menu Pattern.Each one opens its lesson in the Patterns menu.
Metric là con số tổng hợp, rẻ, giữ lâu, dùng để cảnh báo và vẽ xu hướng. Trace cho thấy một request đi qua những đâu và tốn bao lâu ở mỗi chặng. Log ghi chi tiết của một sự kiện. Luồng điều tra thường là metric báo động, trace khoanh vùng, log giải thích; trace_id nối ba thứ lại.Metrics are cheap aggregated numbers kept for a long time, used for alerts and trends. Traces show where one request went and how long each hop took. Logs record the details of one event. An investigation usually goes metric to raise the alarm, trace to narrow it down, log to explain it; trace_id ties them together.
Burn rate gắn cảnh báo với ngân sách lỗi: 14,4x trong 1 giờ nghĩa là mất 2% ngân sách tháng, đáng gọi người. Ngưỡng cố định như 1% trong 5 phút vừa ồn khi có đợt lỗi ngắn vừa bỏ sót lỗi âm ỉ. Dùng hai cửa sổ để vừa nhạy vừa tắt nhanh.Burn rate ties the alert to the error budget: 14.4x over 1 hour means 2% of the monthly budget is gone, which is worth a page. A fixed threshold like 1% over 5 minutes is both noisy on short blips and blind to slow leaks. Two windows make it both sensitive and quick to clear.
Producer ghi traceparent vào header của message, consumer đọc ra và tạo span mới liên kết (span link hoặc con của span producer). Instrumentation của OpenTelemetry cho Spring Kafka và franz-go/sarama làm việc này; với code tự viết thì dùng propagator Inject và Extract trên header.The producer writes traceparent into the message headers and the consumer extracts it to start a linked span (a span link or a child of the producer span). OpenTelemetry instrumentation for Spring Kafka and franz-go/sarama does this; hand-written code calls the propagator's Inject and Extract on the headers.
Cardinality. Xem prometheus_tsdb_head_series, trang TSDB Status để tìm metric và nhãn có nhiều series nhất, thường là nhãn chứa ID, URL thô hay pod name thay đổi liên tục. Bỏ nhãn bằng metric_relabel_configs hoặc ở collector, sửa code, đặt sample_limit.Cardinality. Check prometheus_tsdb_head_series and the TSDB Status page for the metrics and labels with the most series, usually labels holding IDs, raw URLs or constantly changing pod names. Drop the label with metric_relabel_configs or in the collector, fix the code, and set sample_limit.
Phím 1–4 để chọn đáp án, Enter để kiểm tra.Press 1–4 to choose an answer, Enter to check.
Ôn tập ngắt quãng (spaced repetition): thẻ được lặp lại sau 1 → 3 → 7 → 14 → 30 ngày để củng cố trí nhớ dài hạn.Spaced repetition: cards are repeated after 1 → 3 → 7 → 14 → 30 days to build long-term memory.