Observability: Logs, Metrics, Traces and the Stack
"Observability lets you understand a system from the outside by letting you ask questions about that system without knowing its inner workings. Furthermore, it allows you to easily troubleshoot and handle novel problems, that is, “unknown unknowns”." — OpenTelemetry documentation, Observability primer
Summary: Observability is the property that lets you answer a new question about a running system from the telemetry it already emits: metrics tell you something is wrong and how much, traces tell you where in the request path the time or the error went, logs tell you exactly what happened in one step, and profiles tell you which code burned the CPU or memory. The stack is the pipeline that produces, ships, stores and joins those signals. Focus: Monitoring vs observability, unknown unknowns and high cardinality; structured JSON logging with levels, trace ids, sampling and redaction; log pipelines (Fluent Bit, Vector, OpenTelemetry Collector) into Loki, Elasticsearch/OpenSearch or ClickHouse; counters, gauges, histograms and summaries; labels and cardinality explosions; Prometheus (pull model, exposition format, scrape interval, recording rules, PromQL rate and histogram_quantile), Pushgateway, StatsD, OpenMetrics and long-term storage (Thanos, Mimir, Cortex, VictoriaMetrics); RED, USE and the four golden signals; spans, context propagation with W3C traceparent and baggage, head and tail sampling; OpenTelemetry SDK, Collector and OTLP; exporters to Jaeger, Tempo, Zipkin, Honeycomb; semantic conventions; exemplars; pprof and continuous profiling (Pyroscope, Parca); Grafana and dashboards as code; LGTM vs ELK vs SaaS; instrumenting Go and Laravel 13; cost, retention and compliance. Learning goal: Instrument a Go service and a Laravel application so that one alert leads, in three clicks, from a metric to the slow trace to the log lines of the failing span; size the metric labels and the log volume before shipping them; choose head or tail sampling and a backend stack with numbers; and keep personal data out of every signal.
This chapter opens the Observability & Operations group. It builds on Latency Budgets & Tail Latency (why p99 and not the average) and is followed by Alerting That Actually Works, which owns paging rules, burn-rate alerts and on-call hygiene; this page stops at "the SLI exists and is queryable". SLO and error-budget definitions are in SLAs, SLOs, SLIs & Error Budgets. Trace propagation across brokers, consumer lag and DLQ metrics are in Messaging Observability & Tracing, and database-side telemetry (slow query logs, pg_stat_statements) is in Database Observability. Mesh-generated telemetry is in Service Mesh & the Sidecar Pattern. This page owns the signals, the pipeline, the products, the numbers and the instrumentation code.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why dashboards alone stop working | Why it exists |
| Kalman, Dapper, Prometheus, OpenTelemetry | Where it comes from |
| Monitoring vs observability, unknown unknowns | Observability vs monitoring |
| JSON logs, levels, trace ids, log sampling, redaction | Structured logging |
| Fluent Bit, Vector, Loki, Elasticsearch, ClickHouse | Log pipelines and storage |
| Counter, gauge, histogram, summary | Metric types |
| Labels and cardinality explosions | Cardinality |
| Pull model, exposition format, Pushgateway, StatsD | Prometheus |
rate, histogram_quantile, recording rules | PromQL |
| RED, USE, four golden signals, SLIs | Methods |
| Thanos, Mimir, Cortex, VictoriaMetrics | Long-term storage |
| Spans, parents, kinds, attributes, events, links | Traces and spans |
traceparent, tracestate, baggage | Context propagation |
| Head vs tail sampling | Sampling |
| API, SDK, Collector, OTLP | OpenTelemetry |
http.route, service.name, naming rules | Semantic conventions |
| Metric to trace to log | Exemplars and correlation |
| pprof, Pyroscope, Parca | Profiling |
| Grafana, provisioning, dashboards in git | Dashboards |
| LGTM, ELK/OpenSearch, ClickStack, Datadog, New Relic, Honeycomb | Stack choices |
Liveness, readiness, /up | Health endpoints |
| Jobs, queues, cron | Async work |
| Money, retention, GDPR | Cost, retention and compliance |
| Exact formats, knobs and messages | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Which stack, which sampling, which signal | Choosing |
| Monolith to distributed system | In architecture |
| Numbers from a real run | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The four signals.
| Signal | Unit | Cheap at | Expensive at | Answers | Typical store |
|---|---|---|---|---|---|
| Metrics | A number per time series per scrape | Volume (aggregated before storage) | Cardinality (every label combination is a series) | Is something wrong, how much, since when? | Prometheus, Mimir, Thanos, VictoriaMetrics |
| Traces | A tree of spans per request | Context (every attribute rides along) | Volume (one span per hop per request), so sampled | Where did the time or the error go? | Tempo, Jaeger, Zipkin, Honeycomb |
| Logs | A timestamped event, ideally JSON | Detail (any field) | Volume and indexing, plus personal data | What exactly happened in this step? | Loki, Elasticsearch/OpenSearch, ClickHouse |
| Profiles | Sampled stack traces over time | Code-level resolution | Storage per process, still maturing in OpenTelemetry (Alpha) | Which function burned the CPU or memory? | Pyroscope, Parca, pprof files |
Three methods, one question each.
| Method | Apply it to | Measure | Source |
|---|---|---|---|
| RED | Every request-driven service | Rate, Errors, Duration | Tom Wilkie, Grafana Labs |
| USE | Every resource (CPU, disk, pool, queue) | Utilization, Saturation, Errors | Brendan Gregg |
| Four golden signals | A user-facing system | Latency, traffic, errors, saturation | Google SRE Book, chapter 6 |
Defaults and numbers you will meet.
| Number | Meaning |
|---|---|
scrape_interval 1m, scrape_timeout 10s, evaluation_interval 1m | Prometheus global defaults; most teams set 15s or 30s |
| 15d | Prometheus local retention when neither --storage.tsdb.retention.time nor .size is set |
| 1-2 bytes per sample | Prometheus storage after compression: disk = retention seconds x samples per second x bytes per sample |
| "below 10" | Prometheus advice for the cardinality of most metrics; over 100 means "investigate alternate solutions" |
| 0.005 ... 10 s, 14 buckets | OpenTelemetry advisory buckets for http.server.request.duration |
| 4317 / 4318 | OTLP over gRPC / over HTTP default ports |
| 55 characters | traceparent value length: 2 + 32 + 16 + 2 hex digits plus three dashes |
| 32 / 64 / 8192 | Max tracestate list members / max baggage members / max baggage bytes |
| 128 code points | OpenMetrics limit on the combined exemplar label names and values |
| 30s, 50000 | Collector tail_sampling defaults for decision_wait and num_traces |
| 1000 ms | Default threshold of the Laravel Pulse slow requests, slow jobs, slow queries cards |
The stacks, side by side.
| Stack | Metrics | Logs | Traces | Profiles | UI | Operated by |
|---|---|---|---|---|---|---|
| LGTM (Grafana) | Prometheus + Mimir | Loki | Tempo | Pyroscope | Grafana | You or Grafana Cloud |
| ELK / OpenSearch | Elasticsearch / OpenSearch (or Prometheus beside it) | Elasticsearch / OpenSearch | Elastic APM / OpenSearch trace analytics | Elastic Universal Profiling | Kibana / OpenSearch Dashboards | You or Elastic Cloud / AWS |
| ClickHouse (ClickStack) | ClickHouse | ClickHouse | ClickHouse | - | HyperDX / Grafana | You or ClickHouse Cloud |
| Jaeger + Prometheus | Prometheus | Any | Jaeger | - | Jaeger UI + Grafana | You |
| SaaS | Datadog, New Relic, Honeycomb, Grafana Cloud | Same vendor | Same vendor | Some vendors | Vendor UI | Vendor, priced per GB, host, series or event |
| Neutral layer under any of them | OpenTelemetry SDK + Collector + OTLP | Swappable backend |
The picture is the whole chapter: four signals, each strong where the others are weak, joined by one identifier. A page fires on a metric, an exemplar on the slow histogram bucket points to a trace, the slow span's trace_id finds its log lines, and a profile linked to the span shows the function. Everything below is how to make every arrow in that picture real.
Why it exists
A single process on one machine can be understood with a debugger and a log file. Once a request crosses a load balancer, three services, a queue and two databases, no single place sees the whole request, the failure that matters happens to one customer in ten thousand, and it never reproduces on a laptop. Dashboards built in advance answer the questions somebody thought of in advance. The Google SRE Book frames the goal in two questions: "Your monitoring system should address two questions: what’s broken, and why?" Monitoring answers the first for failures you predicted; observability is the ability to answer the second for failures you did not.
| Monitoring alone | Observability |
|---|---|
| Predefined metrics and thresholds | Telemetry rich enough to ask new questions |
| Known unknowns: disk full, CPU high, error rate up | Unknown unknowns: only Android 14 users in one region on the new pricing flag |
| Low-cardinality aggregates | High-cardinality, high-dimensional events (user id, build id, tenant) on spans and logs |
| Dashboards per component | Queries that follow one request across components |
| "Is it up?" | "Why is it slow for these users?" |
| Reactive alert, then guesswork | Alert, then a path: exemplar to trace to logs to profile |
Honeycomb's own description: monitoring "is the collection of predefined metrics" and "excels at providing early warnings for well-defined problems", while useful observability data "must be rich in context and must contain high-cardinality data". You need both: monitoring is the smoke alarm; observability is being able to find which room is burning without opening every door.
The analogy we reuse on this page: a hospital. The bedside monitor shows heart rate and blood pressure every second: that is metrics, cheap, continuous, and great for alarms, but it never says why. The patient's chart, where each nurse writes what they did and saw with a time stamp, is the logs: detailed, written by many hands, and only useful if everyone writes the patient's id on every page. The patient's path through admission, X-ray, surgery and recovery with the time spent in each department is the trace: it shows that the six-hour stay was five hours of waiting for X-ray. The MRI scan is the profile: expensive, but it shows exactly which organ is the problem. The wristband with the patient number is the trace id: without it, the chart, the path and the scan cannot be put together.
Three common misunderstandings, up front
- "Observability is logs, metrics and traces: buy the three tools and you have it." The three signals are the raw material. Honeycomb itself calls the "three pillars" framing a rant topic. You have observability only when the signals share identifiers (trace id, service name, route), carry enough context, and can be queried for a question nobody planned. Three disconnected tools are three haystacks.
- "More data is more observability." Unbounded labels crash Prometheus, unsampled debug logs double the bill, and logged emails create a GDPR incident. Good instrumentation is selective: high cardinality on spans and logs, low cardinality on metrics, sampling on everything voluminous, redaction at the source.
- "OpenTelemetry is an observability backend." The OpenTelemetry documentation says the opposite: "OpenTelemetry is not an observability backend itself." It is the API, SDKs, Collector and the OTLP protocol that produce and move telemetry; storage and UI are Prometheus, Tempo, Loki, Jaeger, Elasticsearch or a vendor.
Where it comes from
Control theory, 1960. In control theory, observability "is a measure of how well internal states of a system can be inferred from knowledge of its external outputs"; the concept "was introduced by the Hungarian-American engineer Rudolf E. Kálmán for linear dynamic systems" (Wikipedia, a secondary source, citing Kalman 1960). Charity Majors (Honeycomb) describes the software use as "a borrowed term from mechanical engineering/control theory", paraphrased as: can you understand any internal state the system may get into "simply by asking questions from the outside?"
Dapper, 2010. Google's paper Dapper, a Large-Scale Distributed Systems Tracing Infrastructure describes production tracing with the design goals of "low overhead, application-level transparency, and ubiquitous deployment", and credits "the use of sampling and restricting the instrumentation to a rather small number of common libraries" for its success. Zipkin (Twitter) and later Jaeger (released by Uber in 2016, then donated to the CNCF) follow its span model.
Prometheus, 2012. Prometheus was "originally built at SoundCloud" in 2012 and joined the CNCF "in 2016 as the second hosted project, after Kubernetes". It brought the pull model, labels and PromQL to the mainstream; its text exposition format became the base of the OpenMetrics specification.
Methods: USE, the golden signals, RED. Brendan Gregg's USE method ("For every resource, check utilization, saturation, and errors"); the Google SRE Book's "four golden signals of monitoring are latency, traffic, errors, and saturation" (2016); and Tom Wilkie's RED method for services (Rate, Errors, Duration), written up by Grafana Labs in 2018.
OpenTracing + OpenCensus = OpenTelemetry. OpenTelemetry "is the result of a merger between two prior projects, OpenTracing and OpenCensus", both created to fix "the lack of a standard for how to instrument code and send telemetry data". W3C Trace Context became a W3C Recommendation on 23 November 2021; W3C Baggage is a Candidate Recommendation (snapshot of 30 May 2024). OpenTelemetry now lists profiles as a fourth signal, with status Alpha.
Year Idea What changed in practice
1 1960 Kalman: observability of linear systems The word: infer internal state from outputs (secondary source)
2 2010 Google Dapper paper Spans, trace ids, sampling, instrument common libraries
3 2012 Prometheus at SoundCloud; Zipkin Pull model, labels, PromQL; open-source tracing
4 2016 SRE Book; Prometheus joins CNCF; Jaeger Four golden signals; cloud-native metrics; Uber tracing
5 2018 RED method write-up Rate, Errors, Duration per service
6 2019+ OpenTelemetry (OpenTracing + OpenCensus) One API/SDK/Collector/OTLP for all signals
7 2021 W3C Trace Context Recommendation traceparent works across vendors
8 2024+ W3C Baggage CR; OTel profiles (Alpha) Context beyond ids; the fourth signalThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products provide it, and the fix.
Observability vs monitoring: unknown unknowns and high cardinality Must-know
In plain words: monitoring checks the things you knew to check; observability lets you ask about the thing you never thought of, using data you already collected.
Common misunderstanding: "Observability replaces monitoring." It does not. You still need cheap metrics and alerts on symptoms (the SRE Book: "it’s better to spend much more effort on catching symptoms than causes"). Observability is what you use after the alert, to find the cause without shipping new code.
Definition: a system is observable to the degree that you can explain any state it gets into from its outputs. In software that means: every unit of work emits context-rich telemetry (a wide event or span with dozens of attributes such as service.version, http.route, user.id, tenant, feature_flag), the telemetry is joined by ids, and the store supports arbitrary group-by and filter on high-cardinality fields. Cardinality is the number of distinct values of a field; a field like user.id has millions, http.request.method about nine.
t Event Monitoring sees Observability lets you ask
1 09:00 deploy v1.4.2 to 10% of pods nothing -
2 09:05 p99 checkout 380 ms -> 2.1 s, error rate unchanged latency alert fires which requests are slow?
3 09:07 group slow spans by service.version - only v1.4.2
4 09:08 group by payment.provider within v1.4.2 - only provider=B
5 09:09 open one exemplar trace, slow span = new retry loop - the cause, no new code shippedReal scenarios: a single tenant generating 40% of errors (group by tenant.id on spans); a slow-down only for one mobile app build; a bug behind one feature flag; one Kubernetes node with a noisy neighbour; one PostgreSQL replica lagging so only reads routed to it are stale.
| Tool family | Strong for | Weak for |
|---|---|---|
| Prometheus + Grafana | Known metrics, alerting, long trends | Per-user or per-request questions (labels must be bounded) |
| Honeycomb (wide events) | Arbitrary group-by on high-cardinality fields | Cheap long-term infrastructure metrics |
| Tempo / Jaeger | One request's path | Aggregates across millions of requests (unless span metrics or TraceQL metrics) |
| Loki / Elasticsearch / ClickHouse | Detail and text search | Joining requests across services without trace ids |
Fix / how to use it: put high-cardinality context on spans and structured logs, keep metric labels bounded, propagate one trace id everywhere, and make sure the backend can group by any span attribute. The Go and Laravel code below does exactly this.
Structured logging: JSON, levels, trace ids, sampling, redaction Must-know
In plain words: write each log line as a small JSON object with fixed field names, so machines can filter on it, and put the request's trace id in every line so you can pull all lines of one request together.
Common misunderstanding: "A request id (correlation id) is the same as a trace id." A correlation id generated by one service groups that service's lines. A W3C trace id is created once at the edge and propagated through every hop, queue and job, and is also the key of the trace in Tempo or Jaeger. Use the trace id as your correlation id and you get both.
Definition: a structured log record has a timestamp, a severity level, a message (a constant string, not a template filled with values), and typed attributes. Levels follow RFC 5424 in Monolog/Laravel ("emergency, alert, critical, error, warning, notice, info, and debug") and DEBUG/INFO/WARN/ERROR in Go's log/slog. Correlation fields: trace_id and span_id (OpenTelemetry log data model calls them TraceId and SpanId). Log sampling drops a share of low-value lines (for example successful requests whose trace was not sampled) while keeping every warning and error. Redaction removes or hashes personal and secret data before the line leaves the process.
Service Line written (JSON, one per line)
1 gateway {"level":"INFO","msg":"http request","http.route":"/checkout","trace_id":"0af7...319c","span_id":"b7ad...3331"}
2 orders {"level":"INFO","msg":"order created","order_id":981,"trace_id":"0af7...319c","span_id":"00f0...02b7"}
3 payments {"level":"ERROR","msg":"charge declined","provider":"B","trace_id":"0af7...319c","span_id":"b9c7...18e1"}
4 job worker {"level":"INFO","msg":"order charged","order_id":981,"trace_id":"0af7...319c"}
query: {trace_id="0af7651916cd43dd8448eb211c80319c"} returns all four lines, from four processesReal scenarios: a support ticket quotes a Trace-Id response header and the engineer finds every line in one query; a log line "user %s failed login" with the email inside it becomes a data-protection incident; debug logging left on after an incident doubles the Loki bill; an exception message containing a SQL statement with a customer's address is shipped to a SaaS vendor.
| Concern | Go log/slog | Laravel / Monolog | Collector side |
|---|---|---|---|
| JSON output | slog.NewJSONHandler | 'formatter' => Monolog\Formatter\JsonFormatter::class | filelog receiver with a JSON parser |
| Levels | slog.LevelDebug/Info/Warn/Error, HandlerOptions.Level | Eight RFC 5424 levels, channel level option | filter processor on severity_number |
| Request context | logger.With(...), context-aware handler | Log::withContext, Log::shareContext, Context::add | resource/attributes processors |
| Trace id | Custom slog.Handler reading trace.SpanContextFromContext | Context::add('trace_id', ...) from the active span | OTLP log records carry TraceId/SpanId natively |
| Redaction | HandlerOptions.ReplaceAttr | Monolog processor added by a channel tap | redaction, attributes (delete, hash) processors |
| Sampling | Middleware decides before logging | Pulse recorder sample_rate; your own middleware | probabilistic_sampler, filter |
Fix / how to use it: constant messages, typed attributes, the trace id injected by a handler or middleware rather than by every call site, redaction in the logger configuration (not a code-review promise), and "always log errors, sample successes". Go: obs/logging.go; Laravel: RequestContext and RedactSensitiveData.
Log pipelines and storage: Fluent Bit, Vector, Loki, Elasticsearch, ClickHouse Important
In plain words: the application writes lines to stdout; an agent on the node picks them up, parses, enriches and filters them, and ships them to a store that is either cheap (index only a few labels) or searchable (index everything).
Common misunderstanding: "Loki is a cheaper Elasticsearch." It is a different design. Loki "does not index the contents of the logs, but only indexes metadata about your logs as a set of labels for each log stream", and stores compressed chunks in object storage. Queries filter by labels first and then scan text; a full-text search over a month without a narrow label selector is slow by design. Elasticsearch/OpenSearch builds an inverted index on the content: fast search, much larger storage and memory.
Definition: a log pipeline has collection (tail files or read container stdout, receive syslog or OTLP), processing (parse JSON, add Kubernetes metadata, drop or sample, redact, route) and storage/query. Agents: Fluent Bit ("a fast and lightweight telemetry agent for logs, metrics, and traces", a CNCF graduated sub-project of Fluentd), Vector ("a lightweight and ultra-fast tool for building observability pipelines", from Datadog), and the OpenTelemetry Collector with the filelog receiver. Stores: Loki (label index + object storage), Elasticsearch/OpenSearch (inverted index), ClickHouse (columnar SQL, compression, TTL).
Step Component Action Cost lever
1 app writes JSON to stderr one line per event what you log at all
2 agent Fluent Bit / Vector / filelog tail /var/log/containers, parse JSON, add pod drop debug, sample 2xx
3 agent processors redact, hash user.email, drop health checks PII never leaves the node
4 ship to Loki / Elastic / ClickHouse batch, compress, retry with a buffer bytes over the network
5 store index labels / full text / columns retention per stream or table TTL GB-months stored
6 query LogQL / KQL / SQL filter by labels, service, trace_id query scan costReal scenarios: a Kubernetes cluster ships container logs with Fluent Bit to Loki with labels namespace, app, env (Loki: "Static labels are good"); a security team keeps an audit index in Elasticsearch for 1 year with full-text search; an analytics-heavy team stores logs in ClickHouse and joins them with business tables in SQL; a team puts trace_id as a Loki label and creates millions of streams (Loki: "never use a label which can have unbounded or infinite values").
| Store | Index | Query | Storage | Good at | Watch out for |
|---|---|---|---|---|---|
| Grafana Loki | Labels only (keep them "limited to tens of values") | LogQL | Object storage (S3, GCS, Azure Blob) | Cheap volume, Kubernetes | High-cardinality labels; unselective queries |
| Elasticsearch / OpenSearch | Inverted index on fields and text | Query DSL, KQL, Lucene, PPL | Local SSD, tiers (hot/warm/cold), snapshots | Full-text search, security analytics | Heap, shard counts, storage multiple of raw |
| ClickHouse | Sparse primary key, skip indexes, columns | SQL | Columnar, compressed, TTL per row | Aggregations, joins, long retention | Schema design and ORDER BY choice |
| Vendor SaaS | Vendor-specific | Vendor UI | Vendor | No operations | Per-GB ingest and retention price |
Fix / how to use it: ship JSON over stdout, keep Loki labels static and bounded (move trace_id, user_id into the line or structured metadata), drop or sample noise at the agent, and set retention per stream or table. The ClickHouse schema with tiered TTL is in Solving the classic problems.
Metric types: counter, gauge, histogram, summary Must-know
In plain words: a counter only goes up (requests served); a gauge goes up and down (requests in flight); a histogram counts observations into buckets so you can compute percentiles later; a summary computes percentiles inside the process and can never be combined across processes.
Common misunderstanding: "I will expose the p99 as a gauge from each pod and average them on the dashboard." The average of percentiles is not a percentile. The Prometheus docs say of summaries: "you cannot aggregate quantiles (e.g. to calculate the total 90th percentile latency for a service backed by multiple replicated workers)". A histogram's buckets can be summed across pods first, then the quantile is computed once.
Definition (Prometheus): "A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart"; name ends in _total. "A gauge is a metric that represents a single numerical value that can arbitrarily go up and down." A classic histogram exposes <basename>_bucket{le="<upper inclusive bound>"} (cumulative), <basename>_sum and <basename>_count (identical to the +Inf bucket). A summary exposes {quantile="0.99"} series plus _sum and _count. Native histograms store sparse exponential buckets as one composite sample per scrape; the Prometheus advice is "If you can, use native histograms and prefer them over both classic histograms and summaries." OpenTelemetry instruments: Counter, UpDownCounter, Gauge, Histogram, and asynchronous (observable) variants read at collection time.
Request duration buckets le=0.05 / 0.1 / 0.25 / 0.5 / +Inf after the request
1 r1 0.040 s 1 / 1 / 1 / 1 / 1 _sum=0.040 _count=1
2 r2 0.180 s 1 / 1 / 2 / 2 / 2 _sum=0.220 _count=2
3 r3 0.090 s 1 / 2 / 3 / 3 / 3 _sum=0.310 _count=3 (cumulative: each bucket counts all <= le)
4 r4 0.700 s 1 / 2 / 3 / 3 / 4 _sum=1.010 _count=4
5 p75 = 3rd of 4 observations -> it lies in the (0.1, 0.25] bucket; histogram_quantile interpolates inside itReal scenarios: http_server_requests_total (counter) for rate and errors; http_server_active_requests, queue_depth, db_pool_in_use (gauges); http_server_request_duration_seconds (histogram) for the SLI "share under 250 ms" and p99; a legacy Java service exposing a summary that cannot be aggregated across 20 pods; a batch job exposing last_success_timestamp_seconds (gauge) through the Pushgateway.
| Need | Prometheus type | OpenTelemetry instrument | PromPHP (Laravel) | client_golang (Go) |
|---|---|---|---|---|
| Events so far | Counter _total | Counter | getOrRegisterCounter()->inc() | prometheus.NewCounterVec |
| Current level | Gauge | Gauge / UpDownCounter / async gauge | getOrRegisterGauge()->set() | prometheus.NewGauge |
| Distribution, aggregatable | Histogram (classic or native) | Histogram | getOrRegisterHistogram(..., $buckets) | prometheus.NewHistogramVec with Buckets or NativeHistogramBucketFactor |
| Exact client-side quantile, one process | Summary | (none; histograms only) | getOrRegisterSummary | prometheus.NewSummaryVec |
Fix / how to use it: counters for things that happen, gauges for levels, histograms for every latency and size, buckets chosen around your SLO threshold (a 250 ms objective needs a le="0.25" boundary). The Go code uses the OpenTelemetry HTTP bucket list; the SRE Book suggests boundaries "approximately exponentially (in this case by factors of roughly 3)".
Labels and the cardinality explosion Must-know
In plain words: every distinct combination of label values is a separate time series that Prometheus keeps in memory; one label with a million possible values turns one metric into a million series and takes the server down.
Common misunderstanding: "Labels are free tags, like attributes on a span." On spans and logs, extra distinct values cost a few bytes. On metrics, the Prometheus docs warn: "every unique combination of key-value label pairs represents a new time series, which can dramatically increase the amount of data stored. Do not use labels to store dimensions with high cardinality (many different label values), such as user IDs, email addresses, or other unbounded sets of values."
Definition: series count = product of the distinct values of every label (times instances, times buckets + 3 for a classic histogram). The Prometheus instrumentation guide: "try to keep the cardinality of your metrics below 10, and for metrics that exceed that, aim to limit them to a handful across your whole system. The vast majority of your metrics should have no labels." Typical offenders: raw URL path (/orders/981), user or tenant id, email, trace id, error message text, pod name on a metric aggregated anyway, full user agent.
t Event Active series Prometheus
1 10:00 v1 exposes requests{route="/orders/{id}"} 72 k fine
2 10:30 v2 changes label to path=r.URL.Path 72 k -> 900 k memory climbs
3 10:45 bot scans /wp-login.php, /.env, /admin/... +300 k head block grows
4 11:00 Prometheus OOM-killed, restarts, replays WAL 0 all dashboards and alerts blind
5 11:20 rollback; sample_limit would have failed only that target's scrapeReal scenarios: a path label on a REST API; status_message with the exception text; customer_id on a billing metric; le buckets times code times route on a histogram (the third bar in the picture); Kubernetes pod names on a high-churn deployment creating new series on every rollout.
| Defence | Where | Effect |
|---|---|---|
| Route template, not path | Instrumentation (Go r.Pattern, Laravel $request->route()->uri()) | /orders/{id} is one value |
| Normalise unknown values | Instrumentation (_OTHER for unknown HTTP methods, unmatched for 404s) | Scanners cannot create series |
sample_limit, label_limit | Prometheus scrape_config | Over the limit, "the entire scrape will be treated as failed" for that target only |
metric_relabel_configs with labeldrop | Prometheus | Drop a bad label before ingestion |
| Per-tenant limits | Mimir, Cortex, VictoriaMetrics | Max series per tenant |
| High-cardinality fields on spans/logs | Design | Questions per user go to traces, not metrics |
Fix / how to use it: compute the series count before you add a label (cmd/cardinality in the Lab does it), use route templates, set sample_limit, and put ids on spans. The Go test TestRouteLabelKeepsCardinalityBounded proves that five different paths and a bogus method produce three series.
Prometheus: pull model, exposition format, scrape interval, Pushgateway, StatsD, OpenMetrics Must-know
In plain words: your service publishes its current counters as text on /metrics; Prometheus fetches that page every 15 seconds from every instance it discovered, stores the numbers with a timestamp, and evaluates rules over them.
Common misunderstanding: "Pull cannot work for short jobs or behind NAT, so we should push everything to a Pushgateway." The Prometheus docs say "Usually, the only valid use case for the Pushgateway is for capturing the outcome of a service-level batch job", and list the pitfalls: a single point of failure, losing "automatic instance health monitoring via the up metric", and the fact that "The Pushgateway never forgets series pushed to it".
Definition: in the pull model the server discovers targets (static, Kubernetes, Consul, EC2 service discovery), scrapes them every scrape_interval (default 1m) with a scrape_timeout (default 10s), attaches job and instance labels, and records a synthetic up series (1 if the scrape succeeded). The text exposition format is line-oriented: # HELP, # TYPE, then name{labels} value [timestamp]. OpenMetrics (application/openmetrics-text; version=1.0.0) standardises it, adds exemplars, _created series and a mandatory # EOF terminator. Push alternatives: the Pushgateway for batch jobs, StatsD (UDP, aggregated by a daemon into counters/timers/gauges, then flushed to a backend; a statsd_exporter bridges to Prometheus), and OTLP push to an OpenTelemetry Collector which exposes or remote-writes to Prometheus.
t Prometheus orders-1:8080/metrics
1 0 s GET /metrics (Accept: openmetrics, text) renders counters, histograms
2 0.02 s stores 1 500 samples, up{instance="orders-1"}=1
3 15 s GET /metrics again
4 25 s timeout after scrape_timeout=10s process stuck in GC
5 25 s up=0 for this instance; alert "TargetDown" can fire after a for: duration
6 30 s rate() over [1m] still works: counters are cumulative, a missed scrape loses resolution, not countsReal scenarios: Kubernetes pods annotated for discovery; a nightly billing job pushing billing_last_success_timestamp_seconds to a Pushgateway with no instance label; a PHP-FPM fleet scraped via hipages/php-fpm_exporter reading pm.status_path; a legacy Node.js app sending StatsD over UDP to a statsd_exporter; a SaaS agent scraping the same /metrics endpoint.
| Ingestion path | Model | Health signal | Best for | Pitfall |
|---|---|---|---|---|
| Prometheus scrape | Pull | up, scrape_duration_seconds | Long-running services | Needs discovery and network reachability |
| Pushgateway | Push, cached | None per instance | Service-level batch jobs | Never forgets series; single point of failure |
StatsD + statsd_exporter | Push over UDP | None | Legacy, very short-lived processes | Lossy UDP, aggregation in the daemon |
| OTLP to Collector | Push | Collector's own metrics | Multi-signal, vendor-neutral | Another component to run and size |
| Prometheus remote write | Push from Prometheus | Remote-write queue metrics | Long-term store (Mimir, Thanos Receive, VictoriaMetrics) | Backpressure when the receiver is slow |
| Prometheus Agent mode | Scrape then forward | up | Edge clusters without local query | No local rules or queries |
Fix / how to use it: expose /metrics with promhttp.HandlerFor(reg, promhttp.HandlerOpts{EnableOpenMetrics: true}) in Go or a MetricsController with PromPHP in Laravel, keep it off the public internet, scrape every 15-30 s, and reserve the Pushgateway for batch jobs. Config: Mechanics.
PromQL basics and recording rules Must-know
In plain words: PromQL turns raw counters into per-second rates and raw buckets into percentiles; recording rules precompute the expensive queries every evaluation interval so dashboards and alerts stay fast.
Common misunderstanding: "sum(rate(x[5m])) and rate(sum(x)[5m]) are the same." They are not: the docs say "always take a rate() first, then aggregate. Otherwise rate() cannot detect counter resets when your target restarts." A pod restart resets its counter to zero; summed first, the reset looks like a huge negative drop.
Definition: rate(v[5m]) "calculates the per-second average rate of increase of the time series in the range vector", adjusting for counter resets and extrapolating to the range edges; "rate should only be used with counters". increase() is rate times the range; irate() uses the last two samples (spiky, for graphs only). histogram_quantile(φ, b) "calculates the φ-quantile (0 ≤ φ ≤ 1)" from bucket rates; for classic histograms the le label must survive the aggregation: histogram_quantile(0.9, sum by (job, le) (rate(http_request_duration_seconds_bucket[10m]))). The quantile is interpolated inside a bucket, so its accuracy is the bucket width. Recording rules "should be of the general form level:metric:operations", for example job_route:http_server_requests:rate5m.
Query Meaning
1 rate(http_server_requests_total[5m]) requests/s per series
2 sum by (route) (rate(http_server_requests_total{code=~"5.."}[5m])) errors/s per route
3 -> divided by sum by (route) (rate(http_server_requests_total[5m])) error ratio per route (RED: Errors)
4 histogram_quantile(0.99, sum by (le, route) (rate(..._bucket[5m]))) p99 per route (RED: Duration)
5 sum(rate(..._bucket{le="0.25"}[5m])) / sum(rate(..._count[5m])) SLI: share under 250 ms
6 record: job_route:http_server_errors:ratio_rate5m precomputed every evaluation_intervalReal scenarios: an SLO dashboard over 30 days that times out until a recording rule precomputes 5-minute ratios; a p99 that never moves because the only buckets are 1 s and 10 s; an alert that fires on every deploy because someone wrote rate(sum(...)); rate(x[1m]) with a 30 s scrape interval returning gaps (the range should cover at least four scrapes, our rule of thumb).
| Function | Input | Use | Trap |
|---|---|---|---|
rate | Counter range | Alerts, dashboards | Aggregate after, never before |
irate | Counter range | Zoomed-in graphs | Too spiky for alerts |
increase | Counter range | "How many in the last hour" | Extrapolated, may be fractional |
histogram_quantile | Bucket rates with le | p50/p90/p99 | Accuracy bounded by bucket width; keep le in by |
sum by / without | Instant vector | Collapse labels | Removing le breaks quantiles |
absent | Instant vector | Alert when a metric disappears | Needs exact label matchers |
Fix / how to use it: the four recording rules in rules-red.yml (Mechanics) give rate, error ratio, p99 and the fast-request SLI per route; dashboards and the alerting chapter read those.
RED, USE and the four golden signals, and SLIs from metrics Must-know
In plain words: for every service measure how many requests, how many fail, and how long they take (RED); for every resource measure how busy it is, how much work is waiting, and how many errors (USE); for the user-facing system watch latency, traffic, errors and saturation (golden signals).
Common misunderstanding: "Saturation is the same as utilization." Gregg defines utilization as "the average time that the resource was busy servicing work" and saturation as "the degree to which the resource has extra work which it can't service, often queued", and warns that "A burst of high utilization can cause saturation and performance issues, even though utilization is low when averaged over a long interval."
Definition: RED (Wilkie): "Rate (the number of requests per second)", "Errors (the number of those requests that are failing)", "Duration (the amount of time those requests take)". USE (Gregg): "For every resource, check utilization, saturation, and errors." Golden signals (SRE Book): "latency, traffic, errors, and saturation. If you can only measure four metrics of your user-facing system, focus on these four." An SLI is "a measurement of a service’s behavior" that "measures your service from the perspective of your users" (OpenTelemetry primer); from metrics it is usually a ratio of good events to all events over a window. SLO targets and error budgets are defined in SLAs, SLOs, SLIs & Error Budgets.
Layer Method Metrics in this chapter's code
1 orders HTTP API RED rate(http_server_requests_total), 5xx ratio, histogram p99
2 PHP-FPM pool USE phpfpm_active_processes / total (U), phpfpm_listen_queue (S), phpfpm_max_children_reached (E)
3 Laravel queue RED + USE queue_job_duration_seconds, Horizon wait time (S), failed jobs (E)
4 whole checkout golden latency p99, traffic rps, error ratio, saturation (CPU, pool, queue depth)
5 SLI ratio share of checkout requests < 250 ms and not 5xx, over 28 daysReal scenarios: an API whose CPU is 40% but whose database connection pool queue is 30 deep (USE on the pool finds it, CPU does not); a worker fleet with zero errors and a growing Horizon wait time (saturation, not errors); a checkout whose average latency is flat while p99 tripled (the SRE Book: collect "request counts bucketed by latencies").
| Method | Unit of analysis | Error definition | Saturation signal | Good starting dashboard |
|---|---|---|---|---|
| RED | Service / route | 5xx, timeouts (not 4xx) | (not part of RED) | Rate, error ratio, p50/p99 per route |
| USE | Resource | Device or operation errors | Queue length, wait time | One row per resource |
| Golden signals | User-facing system | Explicit, implicit (wrong content) and policy (too slow) failures | "How full" the most constrained resource is | Four panels per service |
Fix / how to use it: the Go middleware and the Laravel RecordRequestMetrics produce RED; phpfpm_* and Horizon produce USE for the workers; the recording rule job:http_server_requests_fast:ratio_rate5m is an SLI ready for Alerting That Actually Works.
Long-term metric storage: Thanos, Mimir, Cortex, VictoriaMetrics Important
In plain words: one Prometheus keeps two weeks of data on its own disk and knows only its own targets; to see all clusters together and keep a year, you add a system that stores Prometheus data in object storage and queries it as one.
Common misunderstanding: "Set --storage.tsdb.retention.time=1y and we are done." Local storage is single-node; the docs warn that "NFS filesystems (including AWS's EFS) are not supported", a disk loss loses history, and two HA replicas hold two diverging copies. Long-term, highly available, global storage is a different component.
Definition: Thanos ("Open source, highly available Prometheus setup with long term storage capabilities", with sidecars uploading blocks to object storage and a querier that deduplicates HA pairs); Grafana Mimir ("an open source, horizontally scalable, highly available, multi-tenant TSDB for long-term storage for Prometheus", ingesting via remote write); Cortex (the CNCF project Mimir was forked from, with blocks storage, ruler and query frontend); VictoriaMetrics (a time series database usable "as a drop-in replacement for Prometheus in Grafana" and as remote storage). Prometheus capacity rule: needed_disk_space = retention_time_seconds * ingested_samples_per_second * bytes_per_sample.
Step Component Data
1 0 s Prometheus scrapes, writes WAL head block in memory, 2 h
2 2 h block cut and compacted local block on disk
3 2 h Thanos sidecar uploads block S3 / GCS bucket
3' 1 s or remote_write to Mimir distributor -> ingesters -> object storage
4 query Thanos Querier / Mimir querier merges recent (ingesters) + old (store gateway), dedups HA pairs
5 days compactor downsamples (Thanos) 5 m and 1 h resolutions for year-long graphsReal scenarios: 12 clusters each with an HA pair of Prometheus servers and one global Grafana; a regulator asking for 13 months of availability evidence; a SaaS platform giving each customer tenant limits in Mimir; a cost-driven team replacing a Prometheus fleet with VictoriaMetrics single-node.
| Product | Ingest | Storage | Multi-tenant | HA dedup | Notes |
|---|---|---|---|---|---|
| Prometheus alone | Scrape | Local TSDB, 15d default | No | No (run two, pick one) | Simplest; vertical scaling only |
| Thanos | Sidecar upload or Receive (remote write) | Object storage | Optional | Querier dedup by replica label | Downsampling, works with existing Prometheus |
| Grafana Mimir | Remote write, OTLP | Object storage | Yes | Distributor HA tracker | Tested "to 1 billion active series" (vendor claim) |
| Cortex | Remote write | Object storage (blocks) | Yes | Yes | CNCF; Mimir's ancestor |
| VictoriaMetrics | Remote write, scrape (vmagent), many protocols | Own format, local or cluster | Cluster version | Yes | PromQL-compatible MetricsQL |
Fix / how to use it: keep Prometheus local retention short (2-15 days), add external_labels identifying cluster and replica, remote_write to Mimir or VictoriaMetrics or run Thanos sidecars, and downsample old data. The prometheus.yml snippet shows the wiring.
Traces and spans: parent, child, kind, attributes, events, links, status Must-know
In plain words: a trace is the story of one request; each step (an HTTP handler, a database query, a call to another service, a job) is a span with a start, an end, a name and some facts; spans point to their parent, so the story becomes a tree with timings.
Common misunderstanding: "One span per service is enough." A server span that lasts 395 ms tells you the service was slow, not why. The value comes from child spans for each outbound call (database, cache, HTTP, broker) so the waterfall shows where the time went; one span per function, on the other hand, is noise and cost.
Definition: "A span represents a single unit of work or operation" with a name, start and end time, attributes, events (timestamped annotations such as an exception), links (references to spans in other traces, for batches and fan-in), a status (Unset, Ok, Error) and a span kind: SERVER, CLIENT, PRODUCER, CONSUMER or INTERNAL. All spans of a trace share a 16-byte trace id; each span has an 8-byte span id and its parent's span id (the root span has none). Status rules from the HTTP conventions: a server span is Error for 5xx, left Unset for 4xx (the client's mistake).
t (ms) Span (kind) parent Fact
1 0 gateway POST /checkout (SERVER) none (root) trace_id 0af7...319c created
2 8 orders POST /checkout (SERVER) gateway span traceparent header carried it
3 12 SELECT orders (CLIENT) orders span 18 ms, db.system.name=postgresql
4 40 POST /v1/charges (CLIENT) orders span 350 ms
5 50 payments SERVER charges span status ERROR on first try, retry inside
6 412 gateway span ends total 412 ms; 340 of it in payments
7 +2 s orders process (CONSUMER) orders span queued job, same trace idReal scenarios: a p99 regression traced to a new N+1 query (twenty sibling SELECT spans); a timeout in one of five parallel fan-out calls (the longest child defines the parent); a batch consumer linking one span to the hundred producer spans whose messages it processed; a retry that only shows as two CLIENT spans under one parent.
| Backend | Storage | Query | Strength | Note |
|---|---|---|---|---|
| Grafana Tempo | Object storage only ("only requires an object storage to operate") | TraceQL, trace id lookup | Cheap at scale, metrics-generator | Search by attributes is via TraceQL |
| Jaeger | Cassandra, Elasticsearch/OpenSearch, Badger, memory | Service/operation/tags, trace id | CNCF graduated, Uber origin | Jaeger v2 is built on the OpenTelemetry Collector |
| Zipkin | Memory, Cassandra, Elasticsearch | Service, tags, duration; dependency diagram | Simple, mature | Reports over HTTP or Kafka |
| Honeycomb | Vendor columnar store | Group by any field, BubbleUp | High-cardinality analysis, wide events | Priced "by event volume" |
| Elastic APM / OpenSearch trace analytics | Elasticsearch / OpenSearch | Kibana / Dashboards | Same store as logs | Index sizing applies |
Fix / how to use it: auto-instrument the server and the clients (HTTP, database, Redis, broker), add manual spans only around meaningful work (a payment, a job), put business ids on spans as attributes, set status on errors and record exceptions. Go: obs/middleware.go and loadOrder; Laravel: ChargeOrder.
Context propagation: W3C traceparent, tracestate, baggage Must-know
In plain words: when one service calls another it adds a header with the trace id and its own span id; the receiver reads it and makes its span a child, so both halves end up in the same trace.
Common misunderstanding: "The tracing library does this automatically everywhere." It does it for the instrumented HTTP and gRPC clients and servers. It does not do it for a hand-written queue payload, a cron job, a WebSocket message, a proxy that strips unknown headers, or a thread pool that loses the context object. Each such hop needs explicit inject/extract, otherwise the trace breaks into two.
Definition: W3C Trace Context (Recommendation, 2021) defines traceparent: version-traceid-parentid-flags, for example 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01; trace-id is 32HEXDIGLC (16 bytes, all zeroes forbidden), parent-id is 16HEXDIGLC, trace-flags has one used bit, sampled. "Every tracing tool MUST properly set traceparent even when it only relies on vendor-specific information in tracestate"; tracestate holds up to 32 vendor list-members. W3C Baggage carries application key-values (tenant=acme) with limits of 64 list-members and 8192 bytes. Older formats: Zipkin B3 headers, Jaeger uber-trace-id. OpenTelemetry propagators: tracecontext, baggage, b3; OTEL_PROPAGATORS=baggage,tracecontext.
Hop Action Header / carrier
1 browser -> gateway no traceparent: gateway starts a root -
2 gateway -> orders inject traceparent: 00-0af7...319c-b7ad...3331-01
3 orders extract, start SERVER span as child parent-id becomes orders' span id on the next hop
4 orders -> Laravel queue inject into job context (hidden Context) traceparent stored with the job payload
5 worker extract, start CONSUMER span same trace id 2 s later
6 orders -> Kafka inject into record headers see /messaging/messaging-observabilityReal scenarios: an NGINX or Envoy ingress that must pass (or start) traceparent; a Laravel job whose span appears as a separate root trace until the context is carried; an AWS SQS message attribute carrying traceparent; baggage used to carry tenant to every service so logs and spans can be filtered by tenant (and the risk that baggage leaks to third-party APIs, since it is sent on every outbound call).
| Carrier | Go | Laravel / PHP | Note |
|---|---|---|---|
| HTTP server | propagation.HeaderCarrier(r.Header) + Extract, or otelhttp.NewHandler | Auto-instrumentation, or TraceContextPropagator::getInstance()->extract($request->getHeaders()) | Done once in middleware |
| HTTP client | otelhttp.NewTransport or Inject | PSR-18 / Laravel HTTP client instrumentation, or inject($carrier) | Every outbound call |
| Queue job | Inject into message headers | Context::addHidden('traceparent', ...); Context is captured at dispatch | Laravel Context travels with jobs |
| Broker record | Headers in Kafka/RabbitMQ/Redis Streams | Same | Messaging conventions: Messaging Observability |
| Logs | trace_id field from the span context | Context::add('trace_id', ...) | Joins logs to traces |
Fix / how to use it: register the W3C propagators globally (otel.SetTextMapPropagator(obs.Propagator())), extract in the server middleware, inject in every client and every async hand-off, and test it: the Go test TestContinuesIncomingTrace sends a known traceparent and asserts the trace id and parent span id.
Sampling: head and tail Must-know
In plain words: keeping every trace is too expensive, so you keep some. Head sampling decides at the start of the request by flipping a (deterministic) coin; tail sampling waits until the trace is complete and keeps the interesting ones: errors, slow ones and a small share of the rest.
Common misunderstanding: "10% head sampling keeps 10% of the errors, which is enough." It keeps 10% of all traces, so 90% of error traces are gone, including the one in the support ticket. OpenTelemetry: "you cannot ensure that all traces with an error within them are sampled with head sampling alone. For this situation and many others, you need tail sampling."
Definition: head sampling: "a sampling decision is made based on the trace ID and the desired percentage of traces to sample" (consistent probability sampling), propagated in the sampled flag; the SDK sampler ParentBased(TraceIDRatioBased(0.1)) follows the parent's decision and samples 10% of roots. Tail sampling: "the decision to sample a trace takes place by considering all or most of the spans within the trace"; downsides: harder to implement, "must be stateful systems that can accept and store a large amount of data", and often vendor-specific. The Collector tail_sampling processor requires that "All spans for a given trace MUST be received by the same collector instance", hence the load_balancing exporter with routing_key: traceID in front of it. Policies: status_code, latency, probabilistic, rate_limiting, string_attribute, ottl_condition, composite, and, drop.
t Event Head (10%) Tail (errors + >1.5 s + 5%)
1 0 s root span starts, coin flip on trace id decided: dropped -
2 0.4 s payments returns 500 spans not recorded buffered in sampler memory
3 1.0 s root span ends - waiting decision_wait
4 11 s decision_wait (10 s) elapsed - status_code policy: KEEP
5 later engineer opens the trace from an exemplar not found foundReal scenarios: a high-traffic API at 20 000 rps keeping 1% at the head plus tail rules in the Collector; a low-traffic admin service keeping 100%; span-derived RED metrics computed from 100% of spans before tail sampling so rates stay exact; a sampler tier that runs out of memory during a traffic spike and must be monitored (OpenTelemetry: "it is critical to monitor tail-sampling components").
| Approach | Where | Keeps all errors | Cost | Complexity |
|---|---|---|---|---|
| Always on | SDK | Yes | Highest | None |
Head ratio (TraceIDRatioBased) | SDK, at the root | No | Proportional to ratio | Low |
| Parent-based | SDK, every hop | Follows root | - | Low; keeps traces whole |
Tail (tail_sampling) | Collector tier | Yes | Buffer memory, extra tier | High: sticky routing by trace id |
| Vendor dynamic sampling | Vendor (e.g. Honeycomb Refinery) | Configurable | Vendor | Medium |
| Logs follow traces | Your middleware | Errors always logged | Lower log volume | Low |
Fix / how to use it: in the SDK use ParentBased(TraceIDRatioBased(r)) (Go obs/tracing.go), with r = 1.0 when you also tail-sample so the Collector sees everything, and r < 1 when volume forces you to drop at the source. The sampler Collector config is in Mechanics.
OpenTelemetry: API, SDK, Collector, OTLP, exporters Must-know
In plain words: OpenTelemetry is one set of libraries for every language to create traces, metrics and logs, one protocol (OTLP) to send them, and one agent/gateway (the Collector) to receive, process and forward them to whichever backend you choose.
Common misunderstanding: "Using the OpenTelemetry Collector means we must store data in an OpenTelemetry database." There is none. The Collector is a pipeline: receivers in, processors in the middle, exporters out to Prometheus, Tempo, Jaeger, Loki, Elasticsearch, ClickHouse, Datadog, New Relic or Honeycomb. That is why it is the neutral layer: changing vendor changes exporters, not code.
Definition: the API is what libraries call (tracer.Start, meter.Int64Counter), a no-op unless an SDK is installed; the SDK implements sampling, processors (batch span processor), resource (service.name, service.version) and exporters. Zero-code or auto-instrumentation installs hooks into common libraries (Go eBPF or otelhttp wrappers; the PHP opentelemetry extension plus packages such as open-telemetry/opentelemetry-auto-laravel). OTLP carries all signals over gRPC (port 4317) or HTTP/protobuf (port 4318). The Collector configuration has receivers, processors, exporters, connectors (an exporter of one pipeline and receiver of another, like spanmetrics and forward) and extensions (health_check, pprof, zpages), enabled per pipeline under service.pipelines. "Configuring a processor does not enable it."
Step Component Action
1 app SDK span ends -> batch span processor queues it
2 app OTLP exporter POST /v1/traces to 127.0.0.1:4318 every few seconds
3 agent otlp receiver accepts gRPC 4317 / HTTP 4318
4 agent memory_limiter refuses data before the process runs out of memory
5 agent redaction, attributes masks tokens, deletes db.query.text, hashes user.email
6 agent load_balancing exporter routes by trace id to one sampler instance
7 tier2 spanmetrics -> forward -> tail_sampling -> otlp_grpc/tempo; logs -> Loki; metrics -> MimirReal scenarios: a company migrating from Jaeger to Tempo by changing one Collector exporter; a Laravel application with PHP auto-instrumentation sending to a local Collector over HTTP; a vendor evaluation with dual export to two SaaS backends for a month; an agent DaemonSet that drops health-check spans and redacts before data leaves the node.
| Layer | Go | PHP / Laravel | Notes |
|---|---|---|---|
| API | go.opentelemetry.io/otel, otel/trace, otel/metric | open-telemetry/api (Globals::tracerProvider()) | Safe no-op without SDK |
| SDK | go.opentelemetry.io/otel/sdk/trace, sdk/metric | open-telemetry/sdk | Sampler, processors, resource |
| Auto-instrumentation | otelhttp, otelgrpc, otelsql; eBPF agent | pecl install opentelemetry + OTEL_PHP_AUTOLOAD_ENABLED=true + auto packages | PHP: Composer + PECL, or the OS-package PHP Distro on Linux |
| Exporter | otlptracehttp, otlptracegrpc, stdout | open-telemetry/exporter-otlp | OTEL_EXPORTER_OTLP_ENDPOINT |
| Collector | otelcol / otelcol-contrib binary | Same | Agent and gateway roles |
| Backends | Jaeger, Tempo, Zipkin, Honeycomb, Datadog, New Relic (native OTLP ingest), Elastic | Same | Chosen by exporter |
Fix / how to use it: SDK in-process with a batch processor and OTLP to a Collector on localhost; the Collector does redaction, routing, sampling and fan-out. Exact config in Mechanics; Go in Go; PHP setup in Laravel.
Semantic conventions Important
In plain words: agreed names for attributes and metrics (http.request.method, http.route, service.name, db.system.name) so dashboards, queries and vendor features work for every service without translation.
Common misunderstanding: "Names are a matter of taste." When half the services write status, a quarter http_status and the rest http.status_code, no query covers all of them, and backends cannot build their service maps. Also, names change between convention versions (http.method became http.request.method): pin and migrate deliberately.
Definition: OpenTelemetry semantic conventions define resource attributes (service.name, service.version, deployment.environment.name, k8s.pod.name), span names and attributes per domain (HTTP, database, messaging, RPC), metric names and units (http.server.request.duration in seconds, a Histogram with advisory buckets [ 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10 ]), and requirement levels. HTTP span names "SHOULD be {method} {target} if there is a (low-cardinality) target available", where the target is http.route; unknown methods become _OTHER. Prometheus has its own naming practice: base units (seconds, bytes), _total for counters, _seconds, _bytes suffixes.
Field Bad (seen in the wild) Convention
1 span name GET /orders/981 GET /orders/{id} (low cardinality)
2 method verb=get http.request.method=GET
3 route path=/orders/981 http.route=/orders/{id}, url.path=/orders/981
4 status status="500 Internal" http.response.status_code=500
5 latency metric latency_ms (gauge) http.server.request.duration (histogram, s)
6 service app=orders-prod-2 service.name=orders, deployment.environment.name=prodReal scenarios: Grafana Tempo's service graph working only for services that set service.name; a migration where a dashboard silently breaks after a library upgrade renamed attributes; a span name containing the order id that explodes span-metrics series.
| Domain | Key attributes | Span kind |
|---|---|---|
| HTTP server | http.request.method, http.route, http.response.status_code, url.path | SERVER |
| HTTP client | http.request.method, server.address, url.full | CLIENT |
| Database | db.system.name, db.operation.name, db.collection.name, db.query.text (often redacted) | CLIENT |
| Messaging | messaging.system, messaging.operation.type, messaging.destination.name | PRODUCER / CONSUMER |
| Resource | service.name, service.version, deployment.environment.name, host.name, k8s.* | - |
Fix / how to use it: use the convention names in your own spans and logs (the Go middleware logs http.route and http.response.status_code, the same keys as the span), and set service.name and service.version on the resource.
Exemplars and correlation: metric to trace to log Important
In plain words: an exemplar is one real example attached to a metric point: "this bucket of slow requests includes, for instance, trace 0af7...". In Grafana you click the dot on the latency graph and land on that trace; from the trace you jump to its logs by trace id.
Common misunderstanding: "To connect metrics to traces we must add trace_id as a label." That is the cardinality explosion again. Exemplars sit beside the sample, are not part of the series identity, and "Ingestors MAY discard exemplars".
Definition: OpenMetrics: "Exemplars are references to data outside of the MetricSet. A common use case are IDs of program traces." Text form: sample # {trace_id="..."} value timestamp; "The combined length of the label names and values of an Exemplar's LabelSet MUST NOT exceed 128 UTF-8 character code points"; histogram buckets and counter totals may carry one. Prometheus stores them only with --enable-feature=exemplar-storage and scrapes them only in the OpenMetrics format. Correlation in the other directions: log lines carry trace_id/span_id; Grafana data source settings link Loki lines to Tempo ("derived fields") and Tempo spans to Loki queries; profiles can carry span ids.
Click From To
1 1 Grafana panel p99 /orders/{id} = 2.1 s exemplar dot on bucket le="2.5", trace_id=0af7...
2 2 Tempo trace 0af7... slowest span: payments SERVER 340 ms, Error
3 3 "Logs for this span" (trace_id, span_id) Loki: {app="payments"} | json | trace_id="0af7..."
4 4 "Profiles for this span" Pyroscope flame graph for that time and serviceReal scenarios: a p99 spike investigated in under a minute without guessing; a support ticket with a Trace-Id header value searched directly in Tempo; Laravel log lines from Monolog with Context trace_id linked to the PHP auto-instrumented trace.
| Link | Producer side | Backend side |
|---|---|---|
| Metric -> trace | client_golang ObserveWithExemplar, OTel SDK exemplars | Prometheus exemplar-storage, Mimir; Grafana "Exemplars" toggle |
| Trace -> logs | trace_id in every log line | Grafana Tempo data source "Trace to logs"; Loki derived fields |
| Log -> trace | Same field | Loki derived field regex to Tempo; Kibana APM links |
| Trace -> metrics | service.name, http.route attributes | spanmetrics connector, Tempo metrics-generator |
| Trace -> profile | Span id labels in profiles | Pyroscope span profiles (Go) |
Fix / how to use it: the Go middleware calls ObserveWithExemplar(elapsed, prometheus.Labels{"trace_id": ...}) only for sampled traces (an exemplar to a dropped trace is a dead link); /metrics is served with EnableOpenMetrics: true; the Lab shows the exemplar on the wire.
Profiling: pprof and continuous profiling (Pyroscope, Parca) Important
In plain words: a profiler samples the stack many times per second and tells you which functions use the CPU, allocate memory, hold locks or block goroutines; continuous profiling does that all the time in production, at low overhead, so you can compare yesterday with today.
Common misunderstanding: "A trace already shows the slow function." A trace shows the slow span, which may contain thousands of function calls and spend its time in JSON encoding, regex compilation or GC. Only a profile shows code-level cost, and only a profile shows the CPU spent outside any request (background goroutines, GC).
Definition: OpenTelemetry: "A profile is a collection of samples and associated metadata that shows where applications consume resources during execution", "emerging as the fourth essential signal" (status Alpha). Go's net/http/pprof serves profiles under /debug/pprof/: profile?seconds=30 (CPU), heap, allocs, goroutine, block (after runtime.SetBlockProfileRate), mutex (after runtime.SetMutexProfileFraction), trace?seconds=5 (execution trace); import _ "net/http/pprof" registers them on DefaultServeMux, which is why it must never be the public mux. Continuous profilers: Grafana Pyroscope (push from SDKs or pull via Grafana Alloy), Parca (eBPF-based, whole-node, no code change). PHP: Xdebug and SPX for development, phpspy or eBPF profilers in production, Blackfire and Tideways commercially.
t Event Signal that sees it
1 10:00 CPU of orders pods 35% -> 70% after deploy metric (USE: utilization)
2 10:02 p99 up 20%, no error metric, traces show all spans uniformly slower
3 10:05 go tool pprof .../profile?seconds=30 40% in regexp.Compile inside a handler
4 10:06 flame graph diff v1.4.1 vs v1.4.2 in Pyroscope new regexp.MustCompile per request
5 10:20 hotfix: compile once at package level CPU back to 35%Real scenarios: memory growth found as a slice cache never evicted (heap profile); lock contention on a global map (mutex profile); goroutine leak from un-cancelled contexts (goroutine profile count climbing); a Laravel endpoint spending 60% in Eloquent hydration found with SPX locally.
| Tool | Languages | Mode | Overhead model | Production use |
|---|---|---|---|---|
Go net/http/pprof | Go | On demand over HTTP | Sampling; only while a profile is taken (CPU) | Yes, on a private port |
| Grafana Pyroscope | Go, Java, Python, Ruby, .NET, PHP (via eBPF/agents) | Continuous | Sampling, low | Yes |
| Parca | Any (eBPF) | Continuous, node-wide | Sampling, low | Yes, Linux |
| Xdebug / SPX | PHP | On demand | High (Xdebug), moderate (SPX) | Development / staging |
| OTel profiles | Many (Alpha) | Continuous via OTLP | Sampling | Experimental |
Fix / how to use it: in Go, register pprof handlers on a loopback-only admin server (cmd/server does 127.0.0.1:6060), never on the public mux; run a continuous profiler for always-on history; in the Lab we take a heap profile from the running server.
Dashboards and dashboards as code: Grafana Good to know
In plain words: dashboards are the shared screens for the questions you ask every day; keep them in git as files so they are reviewed, versioned and identical in every environment.
Common misunderstanding: "More panels help during an incident." A wall of 60 panels hides the one that matters. Start every service with one RED row and one USE row, link to Explore for the rest, and delete panels nobody looked at in 90 days.
Definition: Grafana is the common UI for Prometheus, Loki, Tempo, Pyroscope, Elasticsearch, ClickHouse and many vendors. "Grafana has an active provisioning system that uses configuration files. You can define data sources and dashboards using files that can be version controlled, making GitOps more natural." Dashboards are JSON models; dashboards as code generate that JSON (Grafonnet/Jsonnet, the Grafana Terraform provider, Grafana Foundation SDK, or plain JSON reviewed in pull requests) and provision it.
Step Action Artefact
1 PR change a panel query in dashboards/orders.json reviewed diff
2 CI validate JSON, render with Grafonnet if used artefact
3 deploy provisioning file points Grafana at the folder /etc/grafana/provisioning/dashboards/*.yaml
4 run Grafana loads it read-only same dashboard in staging and prodReal scenarios: a service template that ships with its RED dashboard; a dashboard edited by hand in production that diverges from staging; a team-wide variable $route driven by label_values(http_server_requests_total, route).
| Approach | Format | Review in git | Notes |
|---|---|---|---|
| UI-only | Stored in Grafana DB | No | Fast to start, drifts |
| JSON provisioning | Dashboard JSON + provider YAML | Yes | Native, verbose diffs |
| Jsonnet / Grafonnet | Code generating JSON | Yes | Reuse via libraries |
| Terraform provider | HCL | Yes | Same tool as infrastructure |
Fix / how to use it: one RED row per route (job_route:* recording rules), one USE row for pools and queues, exemplars enabled on the latency panel, links to Tempo and Loki with the trace_id field.
The stack choices: LGTM, ELK/OpenSearch, ClickHouse, SaaS, OpenTelemetry as the neutral layer Important
In plain words: you can run Grafana's open-source set (Loki, Grafana, Tempo, Mimir, plus Pyroscope), Elastic's or OpenSearch's search-centric set, a ClickHouse-based set, or pay a vendor; whichever you pick, instrument with OpenTelemetry so you can change your mind.
Common misunderstanding: "SaaS is always more expensive" or "self-hosting is free". SaaS bills per host, GB, series or event and grows with usage; self-hosting bills in engineers, object storage, compute and on-call for the observability system itself (which must stay up when everything else is down).
Definition: LGTM is Loki (logs), Grafana (UI), Tempo (traces), Mimir (metrics), all with object storage as the main store. ELK is Elasticsearch, Logstash and Kibana (Beats/Elastic Agent for shipping); OpenSearch is the Apache-licensed fork with OpenSearch Dashboards and Data Prepper. ClickStack is ClickHouse "unifying logs, traces, metrics and session in a single high-performance scalable solution". SaaS: Datadog, New Relic ("supports native OTLP ingest and recommends it as the preferred method"), Honeycomb, Grafana Cloud, Elastic Cloud. OpenTelemetry "is not an observability backend itself"; it keeps "no vendor lock-in" at the instrumentation layer.
Year 1 Year 3
1 10 services, one team 80 services, 12 teams
2 Prometheus + Grafana + Loki, self-run ingest 2 TB logs/day, 5 M series
3 SDK: OpenTelemetry, OTLP to Collector SaaS trial: add a second exporter in the Collector
4 - migration = exporter change, not 80 code changesReal scenarios: a start-up on Grafana Cloud free tier then self-hosted LGTM at scale; a bank keeping logs in OpenSearch on-premises for data residency; a gaming company with ClickHouse for 30 days of high-cardinality events; an enterprise on Datadog whose bill is dominated by custom metrics and indexed logs.
| Criterion | LGTM | ELK / OpenSearch | ClickHouse / ClickStack | SaaS (Datadog, New Relic, Honeycomb) |
|---|---|---|---|---|
| Log search | Label-first, grep-like | Full-text, best | SQL, fast aggregations | Vendor |
| Storage cost | Low (object storage) | High (indexes, SSD) | Low-medium (columnar compression) | Per GB ingested/indexed |
| High-cardinality analysis | Tempo TraceQL, limited on metrics | Aggregations on fields | Strong | Honeycomb strongest |
| Operations burden | Medium (several components) | High (cluster, shards, heap) | Medium | None |
| Lock-in risk | Low (open source, OTLP) | Low-medium | Low | High unless instrumented with OpenTelemetry |
Fix / how to use it: decide by question type and budget using the decision table; in every case instrument with OpenTelemetry and keep a Collector in the path.
Health endpoints: liveness and readiness Good to know
In plain words: a tiny URL the load balancer or Kubernetes calls every few seconds: "are you alive?" (restart me if not) and "can you take traffic now?" (stop sending if not).
Common misunderstanding: "The health check should test the database, Redis and every dependency." A liveness probe that fails when the database is down makes Kubernetes restart every pod at once, which does not fix the database and adds a restart storm. Liveness checks the process; readiness may check what this instance needs to serve; dependency outages belong in metrics and alerts.
Definition: Laravel: "the health check route is served at /up and will return a 200 HTTP response if the application has booted without exceptions. Otherwise, a 500 HTTP response will be returned", configured with health: '/up' in bootstrap/app.php (it also dispatches a DiagnosingHealth event you can hook). In Go, /healthz and /readyz are conventions; the server in this chapter returns 503 on /readyz once shutdown starts so the load balancer drains it first. Keep health checks out of traces, logs and RED metrics: at one probe every 5 s per pod they otherwise dominate the data.
t Probe Result Action
1 0 s GET /healthz 200 alive
2 0 s GET /readyz 200 in rotation
3 30 s SIGTERM - ctx cancelled
4 30 s GET /readyz 503 removed from rotation
5 40 s server.Shutdown - in-flight requests finish, spans flushedReal scenarios: Kubernetes liveness on /up with readiness on a route that checks the cache warm-up; AWS ALB target group checks; uptime monitors (black-box) on the public URL complementing white-box metrics (the SRE Book: "black-box monitoring is symptom-oriented").
| Probe | Checks | Failure means | Example |
|---|---|---|---|
| Liveness | Process responds | Restart | Laravel /up, Go /healthz |
| Readiness | Can serve now (warm, not draining) | Remove from load balancer | Go /readyz |
| Startup | Finished booting | Wait before liveness | Kubernetes startupProbe |
| Synthetic / black-box | User journey from outside | Alert | Uptime monitor on /checkout |
Fix / how to use it: health routes mounted outside the instrumentation middleware (Go), excluded from metrics (Laravel middleware skips up and metrics).
Observability for async work: queues, jobs, cron Important
In plain words: a job runs seconds or hours after the request that caused it, in another process; unless you carry the trace context with the job and measure wait time, the job is invisible and its failures look unrelated.
Common misunderstanding: "Job duration is the metric." The user waits for queue wait time plus run time. A queue with fast jobs and a 20-minute backlog is broken even though every job takes 50 ms.
Definition: for each queue measure depth (gauge), wait time (enqueue to start), run time (histogram), throughput and failures (counters), and retries; propagate traceparent in the message or job payload; give the consumer span kind CONSUMER and link or parent it to the producer span. Laravel: Context "is captured and shared with the job" at dispatch and "hydrated back into the current context while the job is executing"; Horizon "provides information regarding your job and queue wait times and throughput" after horizon:snapshot runs every five minutes; Pulse cards show queues and slow jobs. Broker-specific telemetry (consumer lag, DLQ depth, OTel messaging conventions) is owned by Messaging Observability & Tracing.
t Process Event Signal
1 0 s web dispatch ChargeOrder Context: trace_id, hidden traceparent
2 0-90 s Redis job waits in queue Horizon wait time, queue depth gauge
3 90 s worker handle(): extract traceparent CONSUMER span, same trace id
4 90.4 s worker POST /v1/charges CLIENT child span
5 90.5 s worker success queue_job_duration_seconds, Pulse order_chargedReal scenarios: an email job with a 2-hour backlog found by Horizon's wait-time notification; a cron job that silently stopped (push last_success_timestamp_seconds and alert on its age); a fan-out job whose child jobs link to the parent trace.
| Need | Laravel | Go |
|---|---|---|
| Context into job | Context::add, Context::addHidden (automatic capture) | Inject into message headers |
| Job span | Manual span, SpanKind::KIND_CONSUMER (ChargeOrder) | tracer.Start(ctx, "... process", WithSpanKind(Consumer)) |
| Wait time and throughput | Horizon metrics, horizon:snapshot | Histogram of now - enqueued_at |
| Failures | failed_jobs, Pulse exceptions, Horizon failed | Counter by outcome |
| Batch / cron | Pushgateway or a "last success" gauge | Same |
Fix / how to use it: RequestContext stores the traceparent in hidden Context; ChargeOrder extracts it, opens a CONSUMER span, records the outcome histogram and a Pulse aggregate.
Cost, retention and compliance Must-know
In plain words: telemetry is data you pay to move, index and keep, and some of it is personal data you are legally responsible for; decide what to keep, for how long, and who may see it, before it exists.
Common misunderstanding: "Storage is cheap, keep everything forever." Ingest, indexing and query compute cost more than the disk, and personal data in logs falls under data-protection law (GDPR's storage limitation and erasure rights) whether or not you meant to log it. Immutable, replicated log stores make erasure hard; the cheapest PII to delete is PII never logged.
Definition: cost drivers per signal: metrics, active series and samples per second; logs, GB ingested, indexed and retained; traces, spans per second times retention; profiles, profiles per process. Levers: drop at the source (log levels, health checks), sample (head, tail, log sampling tied to trace sampling), aggregate (recording rules, span metrics, log-derived metrics), downsample (Thanos), tier (hot/warm/cold, object storage), and retention per stream or table (Loki retention, Elasticsearch ILM, ClickHouse TTL timestamp + INTERVAL ..., Prometheus --storage.tsdb.retention.time). Compliance: redaction at the SDK and Collector (the redaction processor is "intended as one line of defence rather than the only compliance measure"), access control per tenant/team, audit logs kept separately with their own retention.
Decision Before After
1 drop DEBUG in prod, sample 2xx access logs 1.2 TB/day 300 GB/day
2 errors kept 30 d, info 7 d (tiered TTL) 30 d for all 30 d for 5% of rows
3 traces: head 100% -> tail errors+slow+5% 100% stored about 7% stored
4 metrics: drop path label 900 k series 72 k series
5 redact email, token, card number at agent PII in 3 stores none leaves the nodeReal scenarios: a log bill that tripled after a dependency started logging every retry; a deletion request for a customer whose email is in 18 months of logs; a team paying for 400 k custom metrics series from one customer_id label; a security audit log required for 1 year kept in a separate cold index.
| Signal | Typical hot retention | Long-term form | Main cost lever |
|---|---|---|---|
| Metrics | 15 d local (Prometheus default) | 13 months in Mimir/Thanos, downsampled | Series count |
| Logs | 7-30 d | Archive to object storage; errors longer | Volume, indexing |
| Traces | 7-30 d | Span metrics kept as metrics | Sampling |
| Profiles | 7-30 d | Aggregated flame graphs | Sample rate |
| Audit logs | Per regulation (often 1 year+) | WORM / cold storage | Separate pipeline |
Fix / how to use it: the ClickHouse table in Solving the classic problems keeps errors 30 days and the rest 7 days; the Collector agent config redacts and hashes; the Go and Laravel loggers redact at the source.
Mechanics
The exposition format on the wire
What the Go server in this chapter returned in the Lab (OpenMetrics, trimmed; the +Inf, _sum, _count and # EOF lines are added for completeness and their values are illustrative). Note the # {trace_id=...} exemplar after the bucket value and the # EOF that ends an OpenMetrics response.
# HELP http_server_requests_total HTTP requests served, by method, route template and status code.
# TYPE http_server_requests_total counter
http_server_requests_total{code="200",method="GET",route="/orders/{id}"} 21.0
# TYPE http_server_request_duration_seconds histogram
http_server_request_duration_seconds_bucket{method="GET",route="/orders/{id}",le="0.005"} 21 # {trace_id="0af7651916cd43dd8448eb211c80319c"} 0.003799125 1.795654204542141e+09
http_server_request_duration_seconds_bucket{method="GET",route="/orders/{id}",le="+Inf"} 21
http_server_request_duration_seconds_sum{method="GET",route="/orders/{id}"} 0.0798
http_server_request_duration_seconds_count{method="GET",route="/orders/{id}"} 21
http_server_active_requests 0.0
# EOF| Element | Rule | Source |
|---|---|---|
# HELP, # TYPE | One per metric family, before its samples | Prometheus exposition formats |
| Counter name | Ends in _total (OpenMetrics: the family name has no suffix, samples have _total) | Prometheus naming, OpenMetrics |
| Histogram buckets | Cumulative, le inclusive upper bound, +Inf equals _count | Prometheus metric types |
| Exemplar | # {labels} value [timestamp], at most one per bucket, labels within 128 code points | OpenMetrics |
| Content type | application/openmetrics-text; version=1.0.0; charset=utf-8 | OpenMetrics |
| End | # EOF required in OpenMetrics | OpenMetrics |
traceparent, field by field
traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
1 00 version, 1 byte; ff is invalid
2 0af7651916cd43dd8448eb211c80319c trace-id, 16 bytes, lowercase hex, all zeroes forbidden
3 b7ad6b7169203331 parent-id, 8 bytes: the caller's span id
4 01 trace-flags: bit 0 = sampled
tracestate: congo=t61rcWkgMzE up to 32 vendor list-members, opaque to others
baggage: tenant=acme,plan=pro up to 64 members, 8192 bytes, sent on every outbound call| Field | Invalid input | Receiver behaviour |
|---|---|---|
version ff | Invalid | Ignore header, start a new trace |
| trace-id all zero | Forbidden | Ignore header (the Laravel middleware generates a fresh id; tested) |
| parent-id with uppercase hex | Invalid | "Vendors MUST ignore the traceparent when the parent-id is invalid" |
flags 00 | Valid: not sampled | Parent-based sampler does not record; the Go middleware still logs errors |
| Missing header | - | Root span |
The Collector pipelines
The agent tier (per node) receives OTLP on loopback, protects itself with memory_limiter, scrubs with redaction and attributes, and routes by trace id. Component names follow the current Collector documentation (otlp_grpc, otlp_http, load_balancing); older releases spell them otlp, otlphttp and loadbalancing, so check the names your Collector version accepts.
# Tier 1: one Collector per node (DaemonSet) or sidecar. Receives OTLP from
# local apps, protects itself, scrubs data, and routes every span of a trace
# to the same tier-2 instance so tail sampling sees whole traces.
receivers:
otlp:
protocols:
grpc:
endpoint: 127.0.0.1:4317
http:
endpoint: 127.0.0.1:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 400
spike_limit_mib: 100
redaction:
allow_all_keys: true
blocked_key_patterns:
- ".*token.*"
- ".*password.*"
blocked_values:
- "4[0-9]{12}(?:[0-9]{3})?" # Visa card number
summary: silent
attributes/scrub:
actions:
- key: db.query.text
action: delete
- key: user.email
action: hash
exporters:
load_balancing:
routing_key: traceID
protocol:
otlp:
timeout: 2s
resolver:
dns:
hostname: otelcol-sampler-headless.observability.svc.cluster.local
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, redaction, attributes/scrub]
exporters: [load_balancing]The sampler tier computes RED span metrics from every span, then forwards to tail sampling (errors, slower than 1.5 s, 5% baseline) and exports to Tempo, Loki and Mimir.
# Tier 2: stateful sampler and router. Keeps every error and every slow
# trace, 5% of the rest, derives RED metrics from all spans before sampling,
# and exports traces to Tempo, logs to Loki and metrics to Prometheus/Mimir.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
processors:
memory_limiter:
check_interval: 1s
limit_mib: 3000
spike_limit_mib: 600
tail_sampling:
decision_wait: 10s
num_traces: 200000
expected_new_traces_per_sec: 2000
policies:
[
{ name: errors, type: status_code, status_code: { status_codes: [ERROR] } },
{ name: slow, type: latency, latency: { threshold_ms: 1500 } },
{ name: baseline, type: probabilistic, probabilistic: { sampling_percentage: 5 } },
]
connectors:
# forward hands the unsampled stream from one pipeline to the next.
forward:
# Span-derived RED metrics see 100% of spans, so rates stay exact even
# though only a sample of traces is stored.
spanmetrics:
histogram:
explicit:
buckets: [5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s]
exporters:
otlp_grpc/tempo:
endpoint: tempo-distributor.observability.svc:4317
sending_queue:
batch:
otlp_http/loki:
endpoint: http://loki-gateway.observability.svc:3100/otlp
prometheusremotewrite/mimir:
endpoint: http://mimir-distributor.observability.svc/api/v1/push
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
pipelines:
traces/in:
receivers: [otlp]
processors: [memory_limiter]
exporters: [spanmetrics, forward]
traces/sampled:
receivers: [forward]
processors: [tail_sampling]
exporters: [otlp_grpc/tempo]
metrics:
receivers: [otlp, spanmetrics]
processors: [memory_limiter]
exporters: [prometheusremotewrite/mimir]
logs:
receivers: [otlp]
processors: [memory_limiter]
exporters: [otlp_http/loki]| Knob | Default | What it does | Our value |
|---|---|---|---|
tail_sampling.decision_wait | 30s | Time a trace is buffered before the decision | 10s |
tail_sampling.num_traces | 50000 | Traces kept in memory; oldest evicted when full (unless block_on_overflow) | 200000 |
tail_sampling.expected_new_traces_per_sec | 0 | Sizing hint for data structures | 2000 |
memory_limiter.limit_mib / spike_limit_mib | - | Hard and spike memory bounds | 400/100 agent, 3000/600 sampler |
load_balancing.routing_key | traceID for traces | Sticky routing so all spans of a trace meet | traceID |
redaction.allow_all_keys | false (fail closed: no attributes kept) | Keep keys, mask values by pattern | true + blocked patterns |
| OTLP receiver endpoints | localhost | 4317 gRPC, 4318 HTTP | loopback on the agent |
Prometheus configuration and recording rules
# Prometheus pulls /metrics from every target; Grafana Mimir (or Thanos,
# Cortex, VictoriaMetrics) keeps the long-term copy.
global:
scrape_interval: 15s # default 1m
scrape_timeout: 10s # default 10s, must not exceed the interval
evaluation_interval: 15s # how often recording and alerting rules run
external_labels:
cluster: eu-1 # identifies this Prometheus in the global view
rule_files:
- rules/*.yml
scrape_configs:
- job_name: orders-api
metrics_path: /metrics
static_configs:
- targets: ["orders-1:8080", "orders-2:8080"]
# Guard rails against a cardinality explosion in one release.
sample_limit: 20000
label_limit: 30
- job_name: php-fpm
static_configs:
- targets: ["web-1:9253", "web-2:9253"] # hipages/php-fpm_exporter
remote_write:
- url: http://mimir-distributor.observability.svc/api/v1/push# Recording rules: level:metric:operations. Dashboards and alerts read these
# cheap pre-aggregated series instead of recomputing over raw buckets.
groups:
- name: orders-api-red
rules:
- record: job_route:http_server_requests:rate5m
expr: sum by (job, route) (rate(http_server_requests_total[5m]))
- record: job_route:http_server_errors:ratio_rate5m
expr: |
sum by (job, route) (rate(http_server_requests_total{code=~"5.."}[5m]))
/
sum by (job, route) (rate(http_server_requests_total[5m]))
- record: job_route:http_server_request_duration_seconds:p99_5m
expr: |
histogram_quantile(0.99,
sum by (job, route, le) (rate(http_server_request_duration_seconds_bucket[5m])))
# SLI: share of requests faster than 250 ms (a bucket boundary).
- record: job:http_server_requests_fast:ratio_rate5m
expr: |
sum by (job) (rate(http_server_request_duration_seconds_bucket{le="0.25"}[5m]))
/
sum by (job) (rate(http_server_request_duration_seconds_count[5m]))| Setting | Default | Effect |
|---|---|---|
global.scrape_interval | 1m | Resolution of every series; 15s is common |
global.scrape_timeout | 10s | A slower scrape fails, up becomes 0 |
global.evaluation_interval | 1m | How often rules run |
sample_limit | 0 (no limit) | Over the limit after relabelling, "the entire scrape will be treated as failed" |
label_limit | 0 (no limit) | Max labels per sample |
--storage.tsdb.retention.time | 15d (when no size is set) | Local history |
--storage.tsdb.retention.size | 0 (disabled) | Oldest blocks deleted above the size |
--enable-feature=exemplar-storage | off | Keep exemplars (OpenMetrics scrape) |
What you will see when something is wrong
| Symptom (verbatim where quoted) | Where | Meaning | Action |
|---|---|---|---|
traces export: Post "http://127.0.0.1:4318/v1/traces": dial tcp 127.0.0.1:4318: connect: connection refused | Go OTel SDK error handler (observed in our Lab run) | No Collector listening; spans are dropped after the batch queue fills | Run the agent Collector or point OTEL_EXPORTER_OTLP_ENDPOINT elsewhere |
up == 0 | Prometheus | Scrape failed (timeout, refused, sample limit) | Check scrape_duration_seconds, target logs |
Scrape failed after sample_limit | Prometheus target page | Cardinality grew past the guard rail | Find the new label, roll back |
phpfpm_max_children_reached increasing | php-fpm_exporter | "The number of times, the process limit has been reached" | Saturation: more workers or less work per request |
phpfpm_listen_queue > 0 | php-fpm_exporter | Requests waiting for a worker | Saturation (USE) |
| Traces with missing children | Tempo / Jaeger | Spans of one trace went to different tail samplers, or a hop dropped traceparent | Sticky routing; inject at every hop |
Pulse values prefixed with ~ | Pulse dashboard | Sampling enabled; "values will be scaled up" | Expected |
Go
Before
The first version "has observability": logs, Prometheus and a dashboard. None of it can be joined. The log line is free text with the user's email in it and no level or trace id; the metric uses the raw path and the user as labels (one series per order per user); latency is a gauge holding the last request, so a 15-second scrape sees one request in thousands and nothing can be aggregated; and the metrics endpoint shares the public port.
// Command before is the "we have logs and a dashboard" service: every signal
// exists, none of them can be joined, and one metric grows without bound.
package main
import (
"log"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
// One series per raw path and per user: /orders/1, /orders/2, ... times
// every user id. This is a cardinality explosion waiting for traffic.
requests = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "requests",
Help: "Requests by path and user.",
}, []string{"path", "user"})
// The last latency seen. A scrape every 15 s samples one request out of
// thousands; the slow ones are invisible and nothing can be aggregated.
lastLatency = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "last_latency_ms",
Help: "Latency of the most recent request.",
})
)
func main() {
prometheus.MustRegister(requests, lastLatency)
mux := http.NewServeMux()
mux.HandleFunc("/orders/", func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
user := r.Header.Get("X-User")
time.Sleep(20 * time.Millisecond) // pretend work
w.Write([]byte("ok"))
d := time.Since(start)
requests.WithLabelValues(r.URL.Path, user).Inc()
lastLatency.Set(float64(d.Milliseconds()))
// Free text: no level, no trace id, the user's email in clear.
log.Printf("handled %s for %s (%s) in %v", r.URL.Path, user, r.Header.Get("X-Email"), d)
})
// pprof, metrics and the API share one public port.
mux.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(":8080", mux))
}After
The obs package has three small parts. tracing.go builds the SDK tracer provider with parent-based ratio sampling, a batch span processor and the service resource, and the W3C propagators.
// Package obs wires the three signals of one HTTP service together: a trace
// per request, RED metrics with exemplars, and JSON logs carrying trace ids.
package obs
import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
)
// NewTracerProvider builds an OpenTelemetry SDK tracer provider.
//
// Sampling is decided at the head: a root span is kept with probability
// ratio, and a child always follows the decision of its parent (the sampled
// flag of an incoming traceparent). Ended spans are batched before export.
func NewTracerProvider(exp sdktrace.SpanExporter, service, version string, ratio float64) *sdktrace.TracerProvider {
res := resource.NewSchemaless(
attribute.String("service.name", service),
attribute.String("service.version", version),
)
return sdktrace.NewTracerProvider(
sdktrace.WithBatcher(exp),
sdktrace.WithResource(res),
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio))),
)
}
// Propagator reads and writes the W3C traceparent, tracestate and baggage
// headers.
func Propagator() propagation.TextMapPropagator {
return propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})
}logging.go wraps any slog.Handler so that a record logged with a context containing a span gains trace_id and span_id, and redacts sensitive keys with ReplaceAttr before the line is written.
package obs
import (
"context"
"io"
"log/slog"
"strings"
"go.opentelemetry.io/otel/trace"
)
// TraceHandler decorates any slog.Handler: when the context passed to the
// logger holds a span, the record gains trace_id and span_id, so a log line
// can be joined to its trace in Loki, Elasticsearch or ClickHouse.
type TraceHandler struct{ next slog.Handler }
// NewTraceHandler wraps next.
func NewTraceHandler(next slog.Handler) *TraceHandler { return &TraceHandler{next: next} }
// Enabled reports whether next handles the level.
func (h *TraceHandler) Enabled(ctx context.Context, l slog.Level) bool {
return h.next.Enabled(ctx, l)
}
// Handle adds the trace identifiers and forwards the record.
func (h *TraceHandler) Handle(ctx context.Context, r slog.Record) error {
if sc := trace.SpanContextFromContext(ctx); sc.IsValid() {
r.AddAttrs(
slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()),
)
}
return h.next.Handle(ctx, r)
}
// WithAttrs keeps the decoration on derived loggers.
func (h *TraceHandler) WithAttrs(as []slog.Attr) slog.Handler {
return &TraceHandler{next: h.next.WithAttrs(as)}
}
// WithGroup keeps the decoration on derived loggers.
func (h *TraceHandler) WithGroup(name string) slog.Handler {
return &TraceHandler{next: h.next.WithGroup(name)}
}
// sensitive lists attribute keys whose values never reach a log line.
var sensitive = map[string]bool{
"password": true, "authorization": true, "cookie": true, "set-cookie": true,
"token": true, "card_number": true, "email": true,
}
// Redact is a slog ReplaceAttr function: it replaces the value of sensitive
// keys at the source, before the line is written, shipped or indexed.
func Redact(_ []string, a slog.Attr) slog.Attr {
if sensitive[strings.ToLower(a.Key)] {
return slog.String(a.Key, "[REDACTED]")
}
return a
}
// NewJSONLogger returns a JSON logger with redaction and trace correlation.
func NewJSONLogger(w io.Writer, level slog.Leveler) *slog.Logger {
h := slog.NewJSONHandler(w, &slog.HandlerOptions{Level: level, ReplaceAttr: Redact})
return slog.New(NewTraceHandler(h))
}metrics.go defines the RED metrics with bounded labels and the OpenTelemetry HTTP bucket boundaries.
package obs
import "github.com/prometheus/client_golang/prometheus"
// DurationBuckets are the boundaries (seconds) that the OpenTelemetry HTTP
// semantic conventions advise for http.server.request.duration.
var DurationBuckets = []float64{0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10}
// HTTPMetrics holds the RED metrics of an HTTP server.
type HTTPMetrics struct {
Requests *prometheus.CounterVec // Rate and Errors
Duration *prometheus.HistogramVec // Duration
InFlight prometheus.Gauge // a saturation hint
}
// NewHTTPMetrics creates and registers the metrics. Every label is bounded:
// method is one of nine values or _OTHER, route is a mux pattern, code is an
// HTTP status code.
func NewHTTPMetrics(reg prometheus.Registerer) *HTTPMetrics {
m := &HTTPMetrics{
Requests: prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "http_server_requests_total",
Help: "HTTP requests served, by method, route template and status code.",
}, []string{"method", "route", "code"}),
Duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_server_request_duration_seconds",
Help: "Time to serve an HTTP request, by method and route template.",
Buckets: DurationBuckets,
}, []string{"method", "route"}),
InFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Name: "http_server_active_requests",
Help: "Requests currently being served.",
}),
}
reg.MustRegister(m.Requests, m.Duration, m.InFlight)
return m
}
var knownMethods = map[string]bool{
"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true,
"DELETE": true, "OPTIONS": true, "CONNECT": true, "TRACE": true,
}
// normalizeMethod maps unknown methods to _OTHER, as the OpenTelemetry HTTP
// conventions do, so a scanner sending random verbs cannot create series.
func normalizeMethod(m string) string {
if knownMethods[m] {
return m
}
return "_OTHER"
}middleware.go ties them together per request: extract traceparent, start a SERVER span, run the mux, read the matched pattern from the request the mux received (an unmatched path becomes unmatched), name the span GET /orders/{id}, mark 5xx as Error, count the request, observe the duration with a trace exemplar when the trace is sampled, and write one access line: always for 4xx/5xx, for successes only when the trace is sampled.
package obs
import (
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
// Middleware gives every request one server span, one RED measurement with a
// trace exemplar, and at most one structured access-log line.
type Middleware struct {
Tracer trace.Tracer
Propagator propagation.TextMapPropagator
Metrics *HTTPMetrics
Logger *slog.Logger
// LogSuccess decides whether a non-error request is logged. The default
// logs a 1xx-3xx request only when its trace was sampled, so every kept
// access line has a trace to jump to. Errors are always logged.
LogSuccess func(sc trace.SpanContext) bool
}
// Wrap instruments next. Put it outside the ServeMux so it sees every request
// and can read the matched pattern after routing.
func (m *Middleware) Wrap(next http.Handler) http.Handler {
logSuccess := m.LogSuccess
if logSuccess == nil {
logSuccess = func(sc trace.SpanContext) bool { return sc.IsSampled() }
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
method := normalizeMethod(r.Method)
ctx := m.Propagator.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := m.Tracer.Start(ctx, method,
trace.WithSpanKind(trace.SpanKindServer),
trace.WithAttributes(
attribute.String("http.request.method", method),
attribute.String("url.path", r.URL.Path),
))
defer span.End()
m.Metrics.InFlight.Inc()
defer m.Metrics.InFlight.Dec()
sc := span.SpanContext()
w.Header().Set("Trace-Id", sc.TraceID().String())
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
inner := r.WithContext(ctx)
next.ServeHTTP(rec, inner)
// ServeMux sets Pattern on the request it was given; unmatched paths
// share one label value instead of one series per scanned URL.
route := routeOf(inner.Pattern)
elapsed := time.Since(start).Seconds()
span.SetName(method + " " + route)
span.SetAttributes(
attribute.String("http.route", route),
attribute.Int("http.response.status_code", rec.status),
)
if rec.status >= 500 {
// Server spans: 5xx is an error, 4xx is the client's problem.
span.SetStatus(codes.Error, http.StatusText(rec.status))
}
m.Metrics.Requests.WithLabelValues(method, route, strconv.Itoa(rec.status)).Inc()
obs := m.Metrics.Duration.WithLabelValues(method, route)
if ex, ok := obs.(prometheus.ExemplarObserver); ok && sc.IsSampled() {
ex.ObserveWithExemplar(elapsed, prometheus.Labels{"trace_id": sc.TraceID().String()})
} else {
obs.Observe(elapsed)
}
level := slog.LevelInfo
switch {
case rec.status >= 500:
level = slog.LevelError
case rec.status >= 400:
level = slog.LevelWarn
case !logSuccess(sc):
return
}
m.Logger.LogAttrs(ctx, level, "http request",
slog.String("http.request.method", method),
slog.String("http.route", route),
slog.Int("http.response.status_code", rec.status),
slog.Int64("http.response.body.size", rec.bytes),
slog.Float64("duration_ms", elapsed*1000),
)
})
}
// routeOf turns a ServeMux pattern such as "GET /orders/{id}" into the
// http.route value "/orders/{id}".
func routeOf(pattern string) string {
if pattern == "" {
return "unmatched"
}
if i := strings.IndexByte(pattern, ' '); i >= 0 {
pattern = pattern[i+1:]
}
return pattern
}
type statusRecorder struct {
http.ResponseWriter
status int
bytes int64
wroteHeader bool
}
func (s *statusRecorder) WriteHeader(code int) {
if !s.wroteHeader {
s.status, s.wroteHeader = code, true
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Write(b []byte) (int, error) {
s.wroteHeader = true
n, err := s.ResponseWriter.Write(b)
s.bytes += int64(n)
return n, err
}
// Unwrap lets http.ResponseController reach Flush and deadlines.
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }The tests use an in-memory span recorder (tracetest.NewSpanRecorder) and a private registry. They prove that an incoming traceparent is continued (trace id, parent span id, span name and Trace-Id response header), that five different paths and a bogus method create three series, that an unsampled successful request writes no log line while a 500 does (with the trace id), that 5xx and 404 server spans get Error and Unset status, that the histogram has 14 buckets and one carries the exemplar, that emails and passwords are redacted, and that DEBUG is filtered at INFO.
package obs
import (
"bytes"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)
const incoming = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
type fixture struct {
handler http.Handler
spans *tracetest.SpanRecorder
reg *prometheus.Registry
metrics *HTTPMetrics
logs *bytes.Buffer
}
func newFixture(t *testing.T, sampler sdktrace.Sampler) *fixture {
t.Helper()
sr := tracetest.NewSpanRecorder()
tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr), sdktrace.WithSampler(sampler))
t.Cleanup(func() { _ = tp.Shutdown(t.Context()) })
reg := prometheus.NewRegistry()
logs := &bytes.Buffer{}
mw := &Middleware{
Tracer: tp.Tracer("test"),
Propagator: Propagator(),
Metrics: NewHTTPMetrics(reg),
Logger: NewJSONLogger(logs, slog.LevelInfo),
}
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
if r.PathValue("id") == "boom" {
http.Error(w, "database unavailable", http.StatusInternalServerError)
return
}
w.Write([]byte("order " + r.PathValue("id")))
})
return &fixture{handler: mw.Wrap(mux), spans: sr, reg: reg, metrics: mw.Metrics, logs: logs}
}
func (f *fixture) do(method, path, traceparent string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, nil)
if traceparent != "" {
req.Header.Set("traceparent", traceparent)
}
rec := httptest.NewRecorder()
f.handler.ServeHTTP(rec, req)
return rec
}
func (f *fixture) logLines(t *testing.T) []map[string]any {
t.Helper()
var out []map[string]any
for _, line := range strings.Split(strings.TrimSpace(f.logs.String()), "\n") {
if line == "" {
continue
}
var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
t.Fatalf("log line is not JSON: %q", line)
}
out = append(out, m)
}
return out
}
func attr(s sdktrace.ReadOnlySpan, key string) (attribute.Value, bool) {
for _, kv := range s.Attributes() {
if string(kv.Key) == key {
return kv.Value, true
}
}
return attribute.Value{}, false
}
func TestContinuesIncomingTrace(t *testing.T) {
f := newFixture(t, sdktrace.ParentBased(sdktrace.NeverSample()))
rec := f.do("GET", "/orders/42", incoming)
ended := f.spans.Ended()
if len(ended) != 1 {
t.Fatalf("want 1 span, got %d", len(ended))
}
s := ended[0]
if got := s.SpanContext().TraceID().String(); got != "0af7651916cd43dd8448eb211c80319c" {
t.Errorf("trace id = %s, want the incoming one", got)
}
if got := s.Parent().SpanID().String(); got != "b7ad6b7169203331" {
t.Errorf("parent span id = %s", got)
}
if s.Name() != "GET /orders/{id}" {
t.Errorf("span name = %q, want the low-cardinality route", s.Name())
}
if v, _ := attr(s, "http.route"); v.AsString() != "/orders/{id}" {
t.Errorf("http.route = %q", v.AsString())
}
if rec.Header().Get("Trace-Id") != "0af7651916cd43dd8448eb211c80319c" {
t.Errorf("response Trace-Id header = %q", rec.Header().Get("Trace-Id"))
}
}
func TestRouteLabelKeepsCardinalityBounded(t *testing.T) {
f := newFixture(t, sdktrace.AlwaysSample())
for _, p := range []string{"/orders/1", "/orders/2", "/orders/3", "/wp-login.php", "/.env"} {
f.do("GET", p, "")
}
f.do("BREW", "/orders/4", "")
// Three series: GET /orders/{id} 200, GET unmatched 404, _OTHER unmatched 405.
if n := testutil.CollectAndCount(f.metrics.Requests); n != 3 {
t.Fatalf("want 3 series, got %d", n)
}
if v := testutil.ToFloat64(f.metrics.Requests.WithLabelValues("GET", "/orders/{id}", "200")); v != 3 {
t.Errorf("orders counter = %v, want 3", v)
}
if v := testutil.ToFloat64(f.metrics.Requests.WithLabelValues("GET", "unmatched", "404")); v != 2 {
t.Errorf("unmatched counter = %v, want 2", v)
}
}
func TestServerErrorMarksSpanAndIsAlwaysLogged(t *testing.T) {
// The caller did not sample (flag 00), so only the error line is written.
f := newFixture(t, sdktrace.ParentBased(sdktrace.AlwaysSample()))
f.do("GET", "/orders/7", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-00")
f.do("GET", "/orders/boom", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-00")
lines := f.logLines(t)
if len(lines) != 1 {
t.Fatalf("want 1 log line (the error), got %d: %v", len(lines), lines)
}
l := lines[0]
if l["level"] != "ERROR" || l["http.response.status_code"] != float64(500) {
t.Errorf("unexpected line %v", l)
}
if l["trace_id"] != "0af7651916cd43dd8448eb211c80319c" {
t.Errorf("log line lacks the trace id: %v", l)
}
}
func TestErrorStatusOnSpan(t *testing.T) {
f := newFixture(t, sdktrace.AlwaysSample())
f.do("GET", "/orders/boom", "")
f.do("GET", "/nope", "")
ended := f.spans.Ended()
if ended[0].Status().Code != codes.Error {
t.Errorf("5xx span status = %v, want Error", ended[0].Status().Code)
}
if ended[1].Status().Code != codes.Unset {
t.Errorf("404 server span status = %v, want Unset", ended[1].Status().Code)
}
}
func TestHistogramCarriesTraceExemplar(t *testing.T) {
f := newFixture(t, sdktrace.AlwaysSample())
f.do("GET", "/orders/9", incoming)
mfs, err := f.reg.Gather()
if err != nil {
t.Fatal(err)
}
for _, mf := range mfs {
if mf.GetName() != "http_server_request_duration_seconds" {
continue
}
h := mf.GetMetric()[0].GetHistogram()
if len(h.GetBucket()) != len(DurationBuckets) {
t.Fatalf("buckets = %d, want %d", len(h.GetBucket()), len(DurationBuckets))
}
for _, b := range h.GetBucket() {
if ex := b.GetExemplar(); ex != nil {
if ex.GetLabel()[0].GetValue() != "0af7651916cd43dd8448eb211c80319c" {
t.Errorf("exemplar trace id = %s", ex.GetLabel()[0].GetValue())
}
return
}
}
t.Fatal("no bucket carries an exemplar")
}
t.Fatal("histogram not found")
}
func TestRedactsSensitiveKeys(t *testing.T) {
buf := &bytes.Buffer{}
NewJSONLogger(buf, slog.LevelInfo).Info("login failed",
"email", "user@example.com", "Password", "hunter2", "attempt", 3)
out := buf.String()
if strings.Contains(out, "user@example.com") || strings.Contains(out, "hunter2") {
t.Fatalf("secret leaked: %s", out)
}
if !strings.Contains(out, `"attempt":3`) || strings.Count(out, "[REDACTED]") != 2 {
t.Fatalf("unexpected line: %s", out)
}
}
func TestDebugIsFilteredByLevel(t *testing.T) {
buf := &bytes.Buffer{}
l := NewJSONLogger(buf, slog.LevelInfo)
l.Debug("cache miss", "key", "order:1")
if buf.Len() != 0 {
t.Fatalf("debug line written at info level: %s", buf.String())
}
}The server wires it all: OTLP over HTTP to a local Collector, 10% head sampling, Go and process collectors, /metrics with OpenMetrics (exemplars), /healthz and /readyz outside the middleware, pprof on 127.0.0.1:6060, a child CLIENT span for the database call, and a shutdown that flips readiness, drains HTTP and flushes spans.
// Command server is an orders API with traces, RED metrics, JSON logs,
// health endpoints and a private pprof listener.
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"academy/observability-logs-metrics-traces/obs"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
"go.opentelemetry.io/otel/trace"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
logger := obs.NewJSONLogger(os.Stdout, slog.LevelInfo)
slog.SetDefault(logger)
// OTLP over HTTP to a local OpenTelemetry Collector. The exporter honours
// OTEL_EXPORTER_OTLP_ENDPOINT; nothing is dialled until the first export.
exp, err := otlptracehttp.New(ctx)
if err != nil {
logger.Error("otlp exporter", "error", err)
os.Exit(1)
}
tp := obs.NewTracerProvider(exp, "orders-api", "1.4.2", 0.10)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(obs.Propagator())
tracer := tp.Tracer("academy/orders")
reg := prometheus.NewRegistry()
reg.MustRegister(collectors.NewGoCollector(), collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
mw := &obs.Middleware{Tracer: tracer, Propagator: obs.Propagator(), Metrics: obs.NewHTTPMetrics(reg), Logger: logger}
api := http.NewServeMux()
api.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
if err := loadOrder(r.Context(), tracer, r.PathValue("id")); err != nil {
logger.ErrorContext(r.Context(), "load order", "error", err)
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
w.Write([]byte(`{"status":"paid"}`))
})
public := http.NewServeMux()
public.Handle("/", mw.Wrap(api))
// Health and metrics stay outside the middleware: probes every few
// seconds would otherwise dominate traces, logs and the RED numbers.
public.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok")) })
public.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
if ctx.Err() != nil { // draining: tell the load balancer first
http.Error(w, "draining", http.StatusServiceUnavailable)
return
}
w.Write([]byte("ready"))
})
public.Handle("GET /metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{EnableOpenMetrics: true}))
// pprof on loopback only, never on the public port.
admin := http.NewServeMux()
admin.HandleFunc("/debug/pprof/", pprof.Index)
admin.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
admin.HandleFunc("/debug/pprof/profile", pprof.Profile)
admin.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
admin.HandleFunc("/debug/pprof/trace", pprof.Trace)
srv := &http.Server{Addr: ":8080", Handler: public, ReadHeaderTimeout: 5 * time.Second}
adm := &http.Server{Addr: "127.0.0.1:6060", Handler: admin, ReadHeaderTimeout: 5 * time.Second}
go serve(logger, adm)
go serve(logger, srv)
<-ctx.Done()
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = srv.Shutdown(shutdown)
_ = adm.Shutdown(shutdown)
_ = tp.Shutdown(shutdown) // flushes the batch span processor
}
func serve(l *slog.Logger, s *http.Server) {
if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
l.Error("listen", "addr", s.Addr, "error", err)
os.Exit(1)
}
}
// loadOrder stands in for a database call and gets its own child span.
func loadOrder(ctx context.Context, tracer trace.Tracer, id string) error {
ctx, span := tracer.Start(ctx, "SELECT orders", trace.WithSpanKind(trace.SpanKindClient),
trace.WithAttributes(
attribute.String("db.system.name", "postgresql"),
attribute.String("db.operation.name", "SELECT"),
attribute.String("db.collection.name", "orders"),
))
defer span.End()
select {
case <-time.After(3 * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
}The cardinality calculator prints series counts and Prometheus disk for four label designs (used in the Lab).
// Command cardinality prints how many time series one metric costs, and what
// a Prometheus server needs on disk to keep them, before anyone deploys it.
package main
import (
"fmt"
"os"
"text/tabwriter"
)
type design struct {
name string
labels []int // distinct values per label
histogram int // buckets, 0 for a counter
}
// series per label set: one for a counter; buckets + _bucket{le="+Inf"} +
// _sum + _count for a classic histogram.
func (d design) series(instances int) int {
n := instances
for _, v := range d.labels {
n *= v
}
if d.histogram > 0 {
return n * (d.histogram + 3)
}
return n
}
func main() {
const instances = 30
const scrape = 15.0 // seconds
const retention = 15.0 // days, the Prometheus default
const bytesPerSample = 2 // Prometheus docs: "only 1-2 bytes per sample"
designs := []design{
{"counter method x route x code", []int{5, 40, 12}, 0},
{"histogram method x route, 14 buckets", []int{5, 40}, 14},
{"histogram + code label", []int{5, 40, 12}, 14},
{"counter + user_id (100k users)", []int{5, 40, 12, 100_000}, 0},
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "design\tseries\tsamples/s\tdisk (15d)")
for _, d := range designs {
s := d.series(instances)
sps := float64(s) / scrape
disk := retention * 86400 * sps * bytesPerSample
fmt.Fprintf(w, "%s\t%d\t%.0f\t%s\n", d.name, s, sps, human(disk))
}
w.Flush()
}
func human(b float64) string {
units := []string{"B", "KB", "MB", "GB", "TB"}
i := 0
for b >= 1024 && i < len(units)-1 {
b /= 1024
i++
}
return fmt.Sprintf("%.1f %s", b, units[i])
}| Choice in the code | Alternative | Why this one |
|---|---|---|
| Hand-written middleware | otelhttp.NewHandler(handler, "orders") | Shows every step; in production otelhttp plus WithSpanNameFormatter is fine |
| Prometheus client for metrics | OTel metrics SDK + Prometheus exporter or OTLP | Exemplars and promhttp are mature; OTel metrics are equally valid |
r.Pattern from the inner request | URL path | Bounded label; works with Go 1.22+ ServeMux patterns |
| Exemplar only when sampled | Always | An exemplar to a dropped trace is a dead link |
| Logs follow trace sampling for 2xx | Log every request | Volume drops by the sampling ratio; every kept line has a trace |
| pprof on loopback | import _ "net/http/pprof" | The blank import registers on DefaultServeMux, easy to expose publicly |
The Go angle
Go's standard library gives most of the parts: log/slog (Go 1.21) with JSON output, levels, ReplaceAttr for redaction and context-aware Handle for trace ids; net/http with 1.22 patterns and the Request.Pattern field for bounded route labels; net/http/pprof and runtime/pprof for profiles; runtime/metrics behind collectors.NewGoCollector. The OpenTelemetry Go SDK (go.opentelemetry.io/otel, version 1.38 here, compatible with go 1.24) supplies spans, propagation and exporters; go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp wraps handlers and transports; github.com/prometheus/client_golang supplies counters, histograms (classic and native), exemplars and promhttp. Go-specific rules: always pass ctx to logger.InfoContext/LogAttrs or the trace id is lost; wrap the http.Client transport so outbound calls propagate; flush the tracer provider on shutdown; never block a request on telemetry export (the batch processor drops instead). Newer OpenTelemetry Go releases require a newer Go toolchain (the latest at the time of writing set go 1.26 in go.mod), which is why the module pins v1.38.
Laravel
Before
The typical first version logs interpolated strings to a daily file, counts nothing per route, and relies on Telescope in production:
// routes/web.php -- the "before" shape (not a snippet file)
Route::get('/orders/{order}', function (Order $order, Request $request) {
Log::info("User {$request->user()->email} viewed order {$order->id}"); // PII, free text, no trace id
ChargeOrder::dispatch($order->id, $order->total, $order->currency); // the job starts a new, unrelated trace
return $order;
});
// config/app.php providers: TelescopeServiceProvider in every environment, telescope_entries never prunedAfter
Install the pieces (commands from the Laravel 13, OpenTelemetry PHP and PromPHP documentation; expected, not run):
composer require laravel/pulse laravel/horizon promphp/prometheus_client_php
composer require laravel/telescope --dev
pecl install opentelemetry # then: extension=opentelemetry.so in php.ini
composer require open-telemetry/sdk open-telemetry/exporter-otlp open-telemetry/opentelemetry-auto-laravel
# .env / php-fpm pool env
OTEL_PHP_AUTOLOAD_ENABLED=true
OTEL_SERVICE_NAME=shop-web
OTEL_TRACES_EXPORTER=otlp
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318
OTEL_PROPAGATORS=baggage,tracecontextThe request middleware takes the trace id from the active span (auto-instrumentation), else from a valid incoming traceparent, else a fresh random id; puts it in Laravel Context (so it is appended to every log entry and captured into dispatched jobs); stores the full traceparent as hidden Context (travels to jobs, never logged); and returns it in a Trace-Id header.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\API\Trace\Span;
use Symfony\Component\HttpFoundation\Response;
/**
* Puts the trace id on every log line of the request and on every job it
* dispatches, and returns it to the caller for support tickets.
*/
class RequestContext
{
private const TRACEPARENT = '/^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/';
public function handle(Request $request, Closure $next): Response
{
// With OpenTelemetry auto-instrumentation the server span already
// exists; otherwise fall back to the caller's traceparent, then to a
// fresh random id so that logs can still be grouped.
$current = Span::getCurrent()->getContext();
$fromHeader = $this->traceIdFrom($request->header('traceparent'));
$traceId = $current->isValid()
? $current->getTraceId()
: ($fromHeader ?? bin2hex(random_bytes(16)));
// Context is appended to every log entry as metadata and is captured
// into queued jobs when they are dispatched.
Context::add('trace_id', $traceId);
if ($current->isValid()) {
Context::add('span_id', $current->getSpanId());
}
// The full traceparent travels to jobs but stays out of the logs.
$carrier = [];
TraceContextPropagator::getInstance()->inject($carrier);
$traceparent = $carrier['traceparent'] ?? ($fromHeader !== null ? $request->header('traceparent') : null);
if (is_string($traceparent)) {
Context::addHidden('traceparent', $traceparent);
}
$response = $next($request);
$response->headers->set('Trace-Id', $traceId);
return $response;
}
private function traceIdFrom(?string $header): ?string
{
if ($header === null || ! preg_match(self::TRACEPARENT, $header, $m)) {
return null;
}
return $m[1] === str_repeat('0', 32) ? null : $m[1];
}
}Logs go to stderr as JSON through Monolog's JsonFormatter, and a channel tap adds a processor that masks sensitive keys in context and extra.
<?php
// Excerpt of config/logging.php: one JSON object per line on stderr, which
// the container runtime collects and Fluent Bit, Vector or the OpenTelemetry
// Collector ship to Loki, Elasticsearch/OpenSearch or ClickHouse.
use App\Logging\RedactSensitiveData;
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\StreamHandler;
return [
'default' => env('LOG_CHANNEL', 'json'),
'channels' => [
'json' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'info'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => JsonFormatter::class,
'tap' => [RedactSensitiveData::class],
],
// Local development keeps the readable daily file.
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 7),
],
],
];<?php
namespace App\Logging;
use Illuminate\Log\Logger;
use Monolog\LogRecord;
/**
* Channel "tap": adds a Monolog processor that masks sensitive keys in the
* context and extra arrays before any handler formats or ships the record.
*/
class RedactSensitiveData
{
private const KEYS = ['password', 'password_confirmation', 'authorization', 'cookie', 'token', 'card_number', 'email'];
public function __invoke(Logger $logger): void
{
$logger->pushProcessor(function (LogRecord $record): LogRecord {
return $record->with(
context: $this->mask($record->context),
extra: $this->mask($record->extra),
);
});
}
private function mask(array $data): array
{
foreach ($data as $key => $value) {
if (is_array($value)) {
$data[$key] = $this->mask($value);
} elseif (in_array(strtolower((string) $key), self::KEYS, true)) {
$data[$key] = '[REDACTED]';
}
}
return $data;
}
}PHP-FPM processes share nothing, so a counter incremented in one worker is invisible to the next scrape unless it is aggregated somewhere shared. PromPHP "uses Redis or APCu to do the client side aggregation"; the service provider binds a Redis-backed registry, and Metrics records RED with the same bucket list as Go.
<?php
namespace App\Observability;
use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;
/**
* RED metrics for a PHP-FPM or Octane application. PHP-FPM workers share
* nothing, so the registry aggregates in Redis (or APCu on a single host).
*/
final class Metrics
{
/** OpenTelemetry HTTP semantic-convention boundaries, in seconds. */
public const BUCKETS = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10];
private const METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
public function __construct(private CollectorRegistry $registry) {}
public function observeRequest(string $method, string $route, int $status, float $seconds): void
{
$method = in_array($method, self::METHODS, true) ? $method : '_OTHER';
$this->registry
->getOrRegisterCounter('app', 'http_server_requests_total', 'HTTP requests by method, route template and status code.', ['method', 'route', 'code'])
->inc([$method, $route, (string) $status]);
$this->registry
->getOrRegisterHistogram('app', 'http_server_request_duration_seconds', 'HTTP request duration by method and route template.', ['method', 'route'], self::BUCKETS)
->observe($seconds, [$method, $route]);
}
public function jobProcessed(string $job, string $outcome, float $seconds): void
{
$this->registry
->getOrRegisterHistogram('app', 'queue_job_duration_seconds', 'Queued job run time by job class and outcome.', ['job', 'outcome'], [0.05, 0.1, 0.5, 1, 5, 10, 30, 60, 300])
->observe($seconds, [$job, $outcome]);
}
public function render(): string
{
return (new RenderTextFormat())->render($this->registry->getMetricFamilySamples());
}
}<?php
namespace App\Providers;
use App\Models\User;
use App\Observability\Metrics;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Prometheus\CollectorRegistry;
use Prometheus\Storage\Redis;
class ObservabilityServiceProvider extends ServiceProvider
{
public function register(): void
{
// One registry per process, backed by Redis so that every PHP-FPM
// worker adds to the same counters and the scrape sees their sum.
$this->app->singleton(CollectorRegistry::class, function () {
$redis = config('database.redis.metrics', config('database.redis.default'));
return new CollectorRegistry(new Redis([
'host' => $redis['host'] ?? '127.0.0.1',
'port' => (int) ($redis['port'] ?? 6379),
'password' => $redis['password'] ?? null,
'timeout' => 0.1,
'read_timeout' => '10',
'persistent_connections' => true,
]));
});
$this->app->singleton(Metrics::class);
}
public function boot(): void
{
// Pulse is only reachable in local by default; production needs a gate.
Gate::define('viewPulse', fn (User $user) => $user->is_admin);
}
}The metrics middleware reads the route template after routing (orders/{order}), skips /up and /metrics, and the controller renders the scrape output for an allow-list of scraper addresses.
<?php
namespace App\Http\Middleware;
use App\Observability\Metrics;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Records one RED measurement per request. The label is the route template
* ("orders/{order}"), never the raw path, so cardinality stays bounded.
*/
class RecordRequestMetrics
{
public function __construct(private Metrics $metrics) {}
public function handle(Request $request, Closure $next): Response
{
$start = hrtime(true);
$response = $next($request);
// Routing has run by now; unmatched URLs share one label value.
$route = $request->route()?->uri() ?? 'unmatched';
if ($route !== 'metrics' && $route !== 'up') {
$this->metrics->observeRequest(
$request->getMethod(),
$route,
$response->getStatusCode(),
(hrtime(true) - $start) / 1e9,
);
}
return $response;
}
}<?php
namespace App\Http\Controllers;
use App\Observability\Metrics;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Prometheus\RenderTextFormat;
/**
* The scrape target for Prometheus. Reachable from the monitoring network
* only: the route is limited to an allow-list of scraper addresses.
*/
class MetricsController
{
public function __invoke(Request $request, Metrics $metrics): Response
{
abort_unless(in_array($request->ip(), config('observability.scrapers', []), true), 404);
return response($metrics->render(), 200, ['Content-Type' => RenderTextFormat::MIME_TYPE]);
}
}<?php
use App\Http\Middleware\RecordRequestMetrics;
use App\Http\Middleware\RequestContext;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
// Liveness for the load balancer or Kubernetes: 200 if the app boots.
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Order matters: the context exists before anything logs.
$middleware->append(RequestContext::class);
$middleware->append(RecordRequestMetrics::class);
})
->withExceptions(function (Exceptions $exceptions): void {
// Unhandled exceptions are logged with the Context metadata attached.
})
->create();<?php
use App\Http\Controllers\MetricsController;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schedule;
// Loaded from routes/web.php. The Prometheus scrape target.
Route::get('/metrics', MetricsController::class);
// Horizon fills its metrics dashboard from snapshots; Telescope (local only)
// must be pruned or its table grows without bound.
Schedule::command('horizon:snapshot')->everyFiveMinutes();
Schedule::command('telescope:prune --hours=48')->daily();The job continues the HTTP request's trace: it extracts the hidden traceparent, opens a CONSUMER span with the order id as an attribute (fine on a span, never on a metric label), wraps the payment call in a CLIENT span, records exceptions and Error status, observes a job-duration histogram by outcome, and adds a Pulse aggregate for the business number.
<?php
namespace App\Jobs;
use App\Observability\Metrics;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Laravel\Pulse\Facades\Pulse;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use Throwable;
/**
* A queued job that continues the trace of the HTTP request that dispatched
* it: the traceparent arrives through hidden Context, the job opens a
* CONSUMER span under it, and the charge gets a CLIENT child span.
*/
class ChargeOrder implements ShouldQueue
{
use Queueable;
public function __construct(
public int $orderId,
public int $amountCents,
public string $currency,
) {}
public function handle(Metrics $metrics): void
{
$tracer = Globals::tracerProvider()->getTracer('app.jobs', '1.0.0');
$parent = TraceContextPropagator::getInstance()->extract([
'traceparent' => Context::getHidden('traceparent') ?? '',
]);
$span = $tracer->spanBuilder('orders process')
->setParent($parent)
->setSpanKind(SpanKind::KIND_CONSUMER)
->setAttribute('messaging.operation.type', 'process')
->setAttribute('messaging.destination.name', $this->queue ?? 'default')
// High-cardinality identifiers belong on spans and logs, not on metric labels.
->setAttribute('app.order_id', $this->orderId)
->startSpan();
$scope = $span->activate();
$start = hrtime(true);
$outcome = 'success';
try {
$charge = $tracer->spanBuilder('POST /v1/charges')
->setSpanKind(SpanKind::KIND_CLIENT)
->startSpan();
try {
Http::timeout(5)
->withHeaders(['Idempotency-Key' => "order-{$this->orderId}"])
->post(config('services.payments.url').'/v1/charges', [
'amount' => $this->amountCents,
'currency' => $this->currency,
])
->throw();
} finally {
$charge->end();
}
Pulse::record('order_charged', $this->currency, $this->amountCents)->sum()->count();
Log::info('order charged', ['order_id' => $this->orderId, 'amount_cents' => $this->amountCents]);
} catch (Throwable $e) {
$outcome = 'failure';
$span->recordException($e);
$span->setStatus(StatusCode::STATUS_ERROR, 'charge failed');
Log::error('order charge failed', ['order_id' => $this->orderId, 'exception' => $e::class]);
throw $e;
} finally {
$metrics->jobProcessed(self::class, $outcome, (hrtime(true) - $start) / 1e9);
$span->end();
$scope->detach();
}
}
}The feature test checks the trace id path from header to response to Context, that the traceparent is hidden context (not log metadata), that an all-zero trace id is replaced, and that /up answers.
<?php
namespace Tests\Feature;
use App\Jobs\ChargeOrder;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class ObservabilityTest extends TestCase
{
private const TRACEPARENT = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01';
protected function setUp(): void
{
parent::setUp();
Route::get('/orders/{order}', function (int $order) {
ChargeOrder::dispatch($order, 1999, 'EUR');
return ['trace_id' => Context::get('trace_id')];
});
}
public function test_the_callers_trace_id_reaches_logs_and_response(): void
{
Queue::fake();
$this->get('/orders/42', ['traceparent' => self::TRACEPARENT])
->assertOk()
->assertHeader('Trace-Id', '0af7651916cd43dd8448eb211c80319c')
->assertJson(['trace_id' => '0af7651916cd43dd8448eb211c80319c']);
// The hidden traceparent is available to the job, not to log lines.
$this->assertSame(self::TRACEPARENT, Context::getHidden('traceparent'));
$this->assertArrayNotHasKey('traceparent', Context::all());
Queue::assertPushed(ChargeOrder::class);
}
public function test_an_invalid_traceparent_gets_a_fresh_trace_id(): void
{
Queue::fake();
$response = $this->get('/orders/7', ['traceparent' => '00-'.str_repeat('0', 32).'-b7ad6b7169203331-01']);
$id = $response->headers->get('Trace-Id');
$this->assertMatchesRegularExpression('/^[0-9a-f]{32}$/', $id);
$this->assertNotSame(str_repeat('0', 32), $id);
}
public function test_health_route_answers(): void
{
$this->get('/up')->assertOk();
}
}| Laravel tool | What it is | Use in production | Limits |
|---|---|---|---|
| Pulse | First-party dashboard at /pulse: servers, usage, exceptions, queues, slow requests/jobs/queries/outgoing requests, cache | Yes, behind the viewPulse gate; Redis ingest with pulse:work for volume; pulse:check for the servers card | Aggregates in your database, not a tracing or log system; sampling shows ~ values |
| Telescope | Request/query/job/mail inspector | No: "local development"; install with --dev, register only when environment('local') | Grows fast: schedule telescope:prune |
| Horizon | Redis queue dashboard and supervisor | Yes | Metrics need horizon:snapshot every five minutes; retention by metrics.trim_snapshots |
| Log + Context | Monolog channels, Log::withContext, Log::shareContext, Context::add | Yes | Context metadata on every line: keep it small |
| OpenTelemetry PHP | Extension + SDK + auto packages, manual spans | Yes | Extension required for auto-instrumentation; export cost per request in PHP-FPM |
| PromPHP + php-fpm_exporter | /metrics for app and pool | Yes | Redis round trip per observation; aggregate in APCu on single hosts |
The Laravel angle
Laravel 13 gives four first-party pieces: Context (log metadata that crosses into jobs, with hidden values for things like a traceparent), Monolog channels (formatter, tap, stderr), the /up health route and Pulse/Horizon for application-level dashboards. Everything that is distributed tracing or Prometheus comes from outside the framework: the OpenTelemetry PHP extension and open-telemetry/opentelemetry-auto-laravel (spans for requests, queries, cache, HTTP client and queue, configurable with OTEL_PHP_DISABLED_INSTRUMENTATIONS=laravel to turn it off), and PromPHP or the Collector for metrics. The PHP-FPM model drives three rules: aggregation must be shared (Redis/APCu, or emit OTLP and let the Collector aggregate), export must not block the response (use a local Collector on loopback; OpenTelemetry's PHP Distro adds "background export" as a production default), and pool saturation is measured outside PHP with php-fpm_exporter reading the FPM status page (phpfpm_active_processes, phpfpm_listen_queue, phpfpm_max_children_reached). Under Octane the process is long-lived, so in-memory registries become possible but per-request state must be reset; Context is request-scoped either way.
Solving the classic problems
The dashboard is green, users say it is slow
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Histograms, not averages | http_server_request_duration_seconds with buckets around the SLO | p99 and "share under 250 ms" become visible | More series (buckets + 3 per label set) |
| Per-route RED | route label from the template | The slow route stands out from the fast majority | Routes must be bounded |
| Exemplars | ObserveWithExemplar + OpenMetrics + exemplar-storage | One click from the slow bucket to a real trace | Only sampled traces are reachable |
| Black-box probe | Synthetic check from outside | Sees DNS, TLS, CDN problems the app never sees | One more system |
| Golden-signal saturation | Pool queue, run queue, phpfpm_listen_queue | Finds waiting that latency inside the app does not show | Needs exporters per resource |
Cardinality explosion after a deploy
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Guard rails | sample_limit, label_limit per scrape job | One bad target fails, Prometheus survives | That target's metrics are lost until fixed |
| Drop at ingestion | metric_relabel_configs with action: labeldrop | Immediate relief without a deploy | Hides the bug if left forever |
Route templates and _OTHER | Instrumentation code (Go test proves it) | Fixed by design | Needs discipline in every service |
| Find the culprit | topk(10, count by (__name__) ({__name__=~".+"})), Prometheus TSDB status page, Mimir cardinality API | Data, not guesses | Expensive query on large servers |
| Move to spans | Per-user questions answered by traces/wide events | No metric cost | Needs tracing coverage |
The log bill doubled
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Level discipline | INFO in production, DEBUG via a flag for minutes | Biggest single lever | Need a way to turn DEBUG on safely |
| Log sampling tied to traces | Successful requests logged only when traced (Go middleware) | Volume drops by the sampling ratio | Unsampled successes have no access line |
| Drop at the agent | Fluent Bit / Vector / Collector filter on health checks, bots | No code change | Rules must be maintained |
| Tiered retention | ClickHouse TTL DELETE WHERE, Loki per-stream retention, Elasticsearch ILM | Errors kept long, noise short | Configuration per store |
| Log-derived metrics | Count in the pipeline, store the number | Keeps the trend, drops the lines | Lose the detail |
A ClickHouse log table in the shape of the OpenTelemetry exporter's schema (simplified), with tiered retention: everything for 7 days, errors and warnings for 30.
CREATE TABLE otel_logs
(
Timestamp DateTime64(9) CODEC(Delta, ZSTD(1)),
TraceId String CODEC(ZSTD(1)),
SpanId String CODEC(ZSTD(1)),
SeverityText LowCardinality(String),
SeverityNumber UInt8,
ServiceName LowCardinality(String),
Body String CODEC(ZSTD(1)),
LogAttributes Map(LowCardinality(String), String),
INDEX idx_trace_id TraceId TYPE bloom_filter(0.001) GRANULARITY 1
)
ENGINE = MergeTree
PARTITION BY toDate(Timestamp)
ORDER BY (ServiceName, SeverityText, toUnixTimestamp(Timestamp))
TTL toDateTime(Timestamp) + INTERVAL 7 DAY DELETE WHERE SeverityNumber < 13,
toDateTime(Timestamp) + INTERVAL 30 DAY DELETE;
-- All lines of one request, from every service (the trace-to-logs jump).
SELECT Timestamp, ServiceName, SeverityText, Body
FROM otel_logs
WHERE TraceId = '0af7651916cd43dd8448eb211c80319c'
ORDER BY Timestamp;
-- Which service produces the volume? (where to cut first)
SELECT ServiceName, SeverityText, count() AS lines, formatReadableSize(sum(length(Body))) AS body_bytes
FROM otel_logs
WHERE Timestamp >= now() - INTERVAL 1 DAY
GROUP BY ServiceName, SeverityText
ORDER BY lines DESC
LIMIT 10;SeverityNumber < 13 is below WARN in the OpenTelemetry log data model (WARN is 13 to 16), so INFO and DEBUG rows expire after 7 days; the TTL ... DELETE WHERE form is from the ClickHouse TTL guide (TTL time + INTERVAL 1 MONTH DELETE WHERE event != 'error').
The trace breaks at the queue (or the gateway)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Inject/extract at every async hop | Laravel hidden Context, message headers | One trace from request to job | Every producer and consumer must do it |
| Span links for fan-in | Consumer span links to many producer spans | Correct for batches | UI support varies |
| Edge proxy starts or forwards | NGINX/Envoy/ALB tracing config | Trace starts at the edge | Proxies that strip headers must be fixed |
| Test it | Go TestContinuesIncomingTrace; Laravel feature test | Regression-proof | Needs a span recorder |
"We cannot find the trace for that slow request"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Tail sampling | Collector tail_sampling errors + latency + baseline | Interesting traces kept | Stateful tier, sticky routing |
| Return the trace id | Trace-Id response header, shown on error pages | Support tickets carry the key | Must not be confused with a secret |
| Always sample critical routes | Custom sampler or string_attribute policy on http.route | Checkout always traced | Volume |
| Span metrics before sampling | spanmetrics connector on 100% | Exact RED even with 5% traces | Extra metrics series |
Personal data in logs and traces
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Redact at the source | slog ReplaceAttr, Monolog processor via tap | Never written | Key lists must be maintained |
| Redact in the Collector | redaction (fail-closed allow-list), attributes delete/hash | Central, catches libraries | "one line of defence", not the only one |
| Constant messages | "login failed" + typed fields | Redaction can work on keys | Code review |
| Drop query text | Delete db.query.text or keep parameterised statements only | No customer values in spans | Less debugging detail |
| Retention and access control | Short TTL, per-team access | Limits exposure | Configuration per store |
Alert noise and pages nobody acts on
Alerting is the next chapter: Alerting That Actually Works owns symptom-based paging, burn rates and for: durations. The hand-off from this page is the recording rules (error ratio, p99, fast-request SLI) and the rule that pages come from symptoms (RED, golden signals), while cause metrics (USE) go to dashboards.
Prometheus cannot keep a year of data
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Remote write to Mimir / VictoriaMetrics | remote_write | Horizontal, multi-tenant, object storage | Another distributed system |
| Thanos sidecar + store + compactor | Upload blocks, query globally | Keeps existing Prometheus, downsampling | Several components |
| Recording rules for long-term views | Keep only aggregates long | Small | Detail gone after short retention |
Choosing
Which signal answers which question
| Question | First signal | Then | Why |
|---|---|---|---|
| Is the service healthy right now? | Metrics (RED, golden signals) | Alert | Cheap, continuous |
| Which route, version or region is affected? | Metrics with bounded labels, span metrics | Traces grouped by attribute | Bounded dimensions on metrics, the rest on spans |
| Why is this one request slow? | Trace | Logs of the slow span | The waterfall shows the hop |
| What exactly failed in this step? | Logs | Exception event on the span | Detail and stack traces |
| Which code is using the CPU or memory? | Profile | Diff against last release | Code-level cost |
| Which customers are affected? | Spans / wide events with tenant.id | Logs | High cardinality belongs there |
| Did the nightly job run? | Pushed "last success" gauge | Job logs | Batch jobs cannot be scraped |
Which stack
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Small team, Kubernetes, cost-sensitive | Prometheus + Grafana + Loki + Tempo (LGTM), OTel Collector | Object storage for all three | Low storage cost, one UI |
| Heavy full-text log search, security analytics | Elasticsearch or OpenSearch for logs, Prometheus for metrics | ILM hot/warm/cold | Inverted index is the strength |
| High-cardinality analytics on events, SQL skills | ClickHouse (ClickStack) | Tiered TTL, LowCardinality columns | Columnar compression and SQL |
| No operations capacity | SaaS (Datadog, New Relic, Honeycomb, Grafana Cloud) | OTel SDK + Collector, budget alerts on ingest | Pay money instead of on-call |
| Debugging unknown unknowns across many services | Wide events/traces with rich attributes (Honeycomb, Tempo TraceQL, ClickHouse) | Tail sampling | Group by any field |
| Many clusters, 13 months retention | Mimir or Thanos or VictoriaMetrics | external_labels, downsampling | Global view and long history |
| Laravel monolith on a few servers | Pulse + Horizon + JSON logs + php-fpm_exporter, add OTel when services split | Redis ingest for Pulse | First-party, minimal setup |
Which sampling
| Traffic | Head ratio in SDK | Tail policy in Collector | Note |
|---|---|---|---|
| Under 50 rps per service | 1.0 | None | Keep everything |
| 50-2000 rps | 1.0 | Errors + latency + 5-10% | Tail tier sized for full volume |
| Above 2000 rps | 0.1-0.25 | Errors + latency on what arrives | Reduce before the network |
| Critical route (checkout) | 1.0 for that route | Always keep | Custom sampler or attribute policy |
| Batch / cron | 1.0 | Keep | Few, valuable traces |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel or Go monolith on two servers behind a load balancer. JSON logs to stdout with a request-scoped trace id, RED metrics on /metrics, /up for the load balancer, a slow-query log on the database, Pulse for the "what is slow" view. Tracing still pays: one trace shows the 40 queries of an N+1 page inside one process. The simplest correct setup: Prometheus scraping two targets, Loki or a hosted log service, and OpenTelemetry auto-instrumentation exporting to a Collector on each host.
Modular monolith: boundaries without the network
Same process, several modules (orders, billing, catalog). Add the module as a bounded attribute (code.namespace or a module label with five values) on spans and metrics so each module team has its own RED row; give each module its own logger channel name; keep one trace per request with INTERNAL spans at module boundaries, which later become the CLIENT/SERVER pair when a module is extracted. Ownership: every metric and dashboard has an owning module, which is the input for alert routing later.
Microservices: one request, many processes
A checkout request crosses the gateway, orders, payments and a queue worker. What must survive every boundary: the traceparent header (HTTP, gRPC, broker headers, job payloads), service.name on every resource, the same semantic conventions, and the same log field names. The flow:
Hop Telemetry
1 client -> gateway root SERVER span, access log, RED for the gateway
2 gateway -> orders traceparent injected; orders SERVER span (child); RED per route
3 orders -> PostgreSQL CLIENT span (db.system.name, db.operation.name), pool USE gauges
4 orders -> payments CLIENT span + payments SERVER span; 5xx -> Error status, exception event
5 orders -> queue traceparent in job/message; producer span
6 worker CONSUMER span, queue wait histogram, log lines with trace_id
7 Collector tail sampling keeps this trace (payments error); spanmetrics count itA service mesh (Istio, Linkerd) can produce L7 RED metrics and proxy spans without code, but it cannot propagate context through your code: the application must still copy the incoming headers to outgoing calls (Service Mesh & the Sidecar Pattern).
Distributed data: replicas, caches, regions
Telemetry itself becomes distributed data. Clocks differ between hosts, so span timings across machines can show a child starting before its parent by a few milliseconds (skew, not causality). Read replicas and caches need attributes on spans (db.replica, cache hit/miss) or the slow-read cause is invisible. Multi-region: each region runs its own Collector tier and Prometheus pair with external_labels: {region: ...}, and a global query layer (Thanos Querier, Mimir) merges them; tail sampling must stay within a region because all spans of a trace must meet in one sampler, so cross-region traces need a region-aware routing key or head sampling. The observability stack must survive the outage it reports on: run it in a separate failure domain, and alert on the telemetry pipeline itself (exporter queue full, Collector refused spans, Prometheus up of the Collector).
Scaling path: 1x, 10x, 100x
| Load | Metrics | Logs | Traces | People |
|---|---|---|---|---|
| 1x (100 rps, 5 services) | One Prometheus pair, 15d | Loki single binary or hosted | 100% sampled to Tempo/Jaeger | One shared dashboard set |
| 10x (1 000 rps, 30 services) | Prometheus per cluster + Mimir/Thanos | Agent pipeline with drop and sampling rules | Collector agent + tail sampling tier | Dashboards as code, owners per service |
| 100x (10 000+ rps, 200 services) | Per-tenant limits, cardinality budgets per team | Tiered retention, log-derived metrics, archive | Head sampling at source + tail; span metrics for RED | Observability platform team, cost reports per team |
Lab: one service, every signal
Experiment 1: what does a label cost? (run)
cd docs/snippets/system-design/observability-logs-metrics-traces/go
go run ./cmd/cardinalitydesign series samples/s disk (15d)
counter method x route x code 72000 4800 11.6 GB
histogram method x route, 14 buckets 102000 6800 16.4 GB
histogram + code label 1224000 81600 197.0 GB
counter + user_id (100k users) 7200000000 480000000 1131.6 TBReal output on this machine. Disk uses the Prometheus formula with 2 bytes per sample, 15 s scrape, 15 days and 30 instances (a back-of-envelope estimate; real compression varies). One label turned 102 k series into 1.2 M; a user id turns a counter into something no Prometheus can hold.
Experiment 2: the middleware tests with the race detector (run)
go test -race -count=1 -v ./obs--- PASS: TestContinuesIncomingTrace (0.00s)
--- PASS: TestRouteLabelKeepsCardinalityBounded (0.00s)
--- PASS: TestServerErrorMarksSpanAndIsAlwaysLogged (0.00s)
--- PASS: TestErrorStatusOnSpan (0.00s)
--- PASS: TestHistogramCarriesTraceExemplar (0.00s)
--- PASS: TestRedactsSensitiveKeys (0.00s)
--- PASS: TestDebugIsFilteredByLevel (0.00s)
ok academy/observability-logs-metrics-traces/obs 1.134sExperiment 3: run the server without a Collector (run)
go build -o /tmp/obs-server ./cmd/server
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 /tmp/obs-server &
for i in $(seq 1 20); do curl -s -o /dev/null localhost:8080/orders/$i; done
curl -s -i -H 'traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01' localhost:8080/orders/42 | head -2
curl -s -H 'Accept: application/openmetrics-text' localhost:8080/metrics | grep -E '^http_server_(requests_total|request_duration_seconds_bucket\{.*le="0.005"|active)'
curl -s -o /dev/null -w 'public pprof: %{http_code}\n' localhost:8080/debug/pprof/HTTP/1.1 200 OK
Trace-Id: 0af7651916cd43dd8448eb211c80319c
http_server_active_requests 0.0
http_server_request_duration_seconds_bucket{method="GET",route="/orders/{id}",le="0.005"} 21 # {trace_id="0af7651916cd43dd8448eb211c80319c"} 0.003799125 1.795654204542141e+09
http_server_requests_total{code="200",method="GET",route="/orders/{id}"} 21.0
public pprof: 404Real output. Twenty-one different paths, one series. The exemplar points at the trace we started with the traceparent header (sampled flag 01, so the parent-based sampler kept it). Of the 20 root requests only 3 wrote an access line (10% head sampling: lines follow sampled traces), for example {"level":"INFO","msg":"http request","http.route":"/orders/{id}","http.response.status_code":200,"duration_ms":3.819125,"trace_id":"33dab9cda2ad49420e9f7aaefa6d38e9",...}; the /debug/pprof/ probe on the public port was logged as WARN with route unmatched. With no Collector running, the SDK reported traces export: Post "http://127.0.0.1:4318/v1/traces": dial tcp 127.0.0.1:4318: connect: connection refused and the requests were unaffected: export never blocks serving.
Experiment 4: a heap profile from the private port (run)
for i in $(seq 1 300); do curl -s -o /dev/null localhost:8080/orders/$i; done
go tool pprof -top -nodecount=8 http://127.0.0.1:6060/debug/pprof/heapType: inuse_space
Showing nodes accounting for 4611.65kB, 100% of 4611.65kB total
flat flat% sum% cum cum%
1538.05kB 33.35% 33.35% 1538.05kB 33.35% runtime.mallocgc
512.20kB 11.11% 55.58% 512.20kB 11.11% go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).snapshot
512.16kB 11.11% 88.90% 512.16kB 11.11% net/http.(*Request).WithContext
0 0% 100% 2048.70kB 44.42% academy/observability-logs-metrics-traces/obs.(*Middleware).Wrap.func2Real output (trimmed). The heap is tiny (4.5 MB in use) and the instrumentation's own allocations are visible: span snapshots and the request clone made by WithContext. A profile is how you check the cost of observability itself. For a CPU profile use .../debug/pprof/profile?seconds=30.
Experiment 5: Laravel context, logs and metrics (expected, not run)
php artisan test --filter=ObservabilityTest
curl -s -i -H 'traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01' http://localhost/orders/42 | grep Trace-Id
tail -1 storage/logs/stderr.json # or the container log
curl -s http://localhost/metrics | grep app_http_server_requests_totalPASS Tests\Feature\ObservabilityTest (3 tests)
Trace-Id: 0af7651916cd43dd8448eb211c80319c
{"message":"order charged","context":{"order_id":42,"amount_cents":1999},"level_name":"INFO","extra":{"trace_id":"0af7651916cd43dd8448eb211c80319c"}}
app_http_server_requests_total{method="GET",route="orders/{order}",code="200"} 1Expected, not run (no Laravel application or Redis in this environment). Where Context metadata appears in the JSON (extra or context) depends on the Laravel version's Monolog integration; the point is that the job's line carries the request's trace id.
Experiment 6: the full pipeline (expected, not run)
Run an agent Collector with otel-collector-agent.yaml, a sampler Collector with otel-collector-sampler.yaml, Tempo, Loki, Mimir and Grafana (for example from the Grafana docker-otel-lgtm image, not used here per the lab cost rule). Send 1 000 requests with 2% returning 500. Expected, not run: Tempo holds about every error trace plus about 5% of the rest (roughly 20 + 49 traces), while traces_span_metrics_calls_total from the spanmetrics connector counts all 1 000 calls; in Grafana the p99 panel shows exemplar dots that open Tempo, and "Logs for this span" opens Loki filtered by trace_id.
Common misconceptions
| Belief | Reality |
|---|---|
| Observability is having logs, metrics and traces | It is being able to answer new questions; that needs joined, context-rich signals |
| OpenTelemetry stores my data | "OpenTelemetry is not an observability backend itself"; it produces and moves telemetry |
| Averaging per-pod p99 gives the service p99 | Quantiles cannot be aggregated; sum histogram buckets, then histogram_quantile |
| Any label is fine on a metric | Every label combination is a series; unbounded labels cause cardinality explosions |
Put trace_id on a metric to link it to traces | Use an exemplar; a label would create one series per request |
rate(sum(x)) equals sum(rate(x)) | "always take a rate() first, then aggregate" or counter resets break it |
| The Pushgateway is the way to push metrics | "the only valid use case ... is ... a service-level batch job" |
| 10% head sampling keeps enough errors | It keeps 10% of errors; tail sampling keeps all of them |
| Tail sampling works on any Collector fleet | All spans of a trace must reach the same instance: route by trace id |
| Loki is a cheaper Elasticsearch | Loki indexes labels only; full-text search is a scan |
| Telescope is a production monitor | Laravel documents it for local development; use Pulse, Horizon and OpenTelemetry in production |
| Health checks should test every dependency | A failing liveness on a dependency outage restarts every pod and fixes nothing |
| Logging more is safer | More volume, more cost, more PII; log less, structured, with trace ids |
| Monitoring is obsolete | Symptom-based monitoring is still what pages; observability is what you use after the page |
Cheat sheet
| Topic | What to remember |
|---|---|
| Signals | Metrics say what and how much, traces say where, logs say what exactly, profiles say which code |
| Join key | trace_id in logs, exemplars on metrics, span ids in profiles |
| Logs | JSON, constant message, typed fields, levels, trace id by middleware, redact at source |
| Metric types | Counter _total, gauge, histogram (prefer native), summary only when you never aggregate |
| Cardinality | Product of label values; keep most metrics under 10 series; route templates, _OTHER, unmatched |
| Prometheus | Pull every 15-30 s, up, sample_limit, 15d local, remote write for long term |
| PromQL | rate then sum by; histogram_quantile(0.99, sum by (le, ...) (rate(..._bucket[5m]))) |
| Rules | level:metric:operations; dashboards and alerts read recorded series |
| Methods | RED per service, USE per resource, golden signals per user-facing system |
| Traces | SERVER/CLIENT/PRODUCER/CONSUMER/INTERNAL; 5xx Error, 4xx Unset on server spans |
| Propagation | traceparent 00-trace-parent-flags; inject at every hop including jobs and messages |
| Sampling | ParentBased(TraceIDRatio) in SDK; tail in Collector with trace-id routing |
| OpenTelemetry | API, SDK, OTLP 4317/4318, Collector receivers -> processors -> exporters |
| Profiling | pprof on a private port; continuous with Pyroscope or Parca |
| Laravel | Context + JSON Monolog + tap redaction, PromPHP with Redis, Pulse, Horizon horizon:snapshot, Telescope dev only, /up |
| Cost | Drop, sample, aggregate, downsample, tier; retention per signal; PII never logged |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can you not compute a service-wide p99 from per-pod summaries, and what do you do instead? Important
Answer
Answer: Summaries compute quantiles inside each process and "you cannot aggregate quantiles". Expose a histogram, sum the bucket rates across pods keeping le, then apply histogram_quantile once.
2 — A metric has labels method (5 values), route (40), code (12) and runs on 30 instances. How many series, and what happens if you add user_id with 100 000 values? Must-know
Answer
Answer: 5 x 40 x 12 x 30 = 72 000 series. With user_id it becomes 7.2 billion: a cardinality explosion. User ids belong on spans and logs.
3 — What are the four fields of traceparent and what does the last one mean? Important
Answer
Answer: Version (00), trace-id (32 hex), parent-id (16 hex, the caller's span id) and trace-flags; bit 0 of the flags is the sampled flag.
4 — Why does tail sampling need a load_balancing exporter in front of it? Good to know
Answer
Answer: "All spans for a given trace MUST be received by the same collector instance" for the decision to see the whole trace; routing by traceID makes that true across a fleet.
5 — Why is rate(sum(http_requests_total)[5m]) wrong? Must-know
Answer
Answer: Summing first hides per-series counter resets (a pod restart looks like a drop); rate must see each raw counter: "always take a rate() first, then aggregate".
6 — When is the Pushgateway the right tool, and what are its pitfalls? Important
Answer
Answer: For the outcome of a service-level batch job. Pitfalls: single point of failure and bottleneck, no up per instance, and it never forgets pushed series.
7 — In the Go middleware, why are exemplars attached only when the trace is sampled? Good to know
Answer
Answer: An exemplar points to a trace id; if the trace was not recorded, the link leads nowhere.
8 — What is the difference between utilization and saturation in the USE method? Give a PHP-FPM example of each. Must-know
Answer
Answer: Utilization is how busy the resource is (active processes / total); saturation is queued work it cannot serve (phpfpm_listen_queue, phpfpm_max_children_reached).
9 — How does the trace id of an HTTP request reach a Laravel queued job in this chapter's code? Important
Answer
Answer: The middleware stores trace_id in Context and the traceparent in hidden Context; Laravel captures Context at dispatch and hydrates it in the worker; the job extracts the traceparent and starts a CONSUMER span under it.
10 — Why should a liveness probe not check the database? Must-know
Answer
Answer: During a database outage every pod would fail liveness and be restarted together, which adds load and fixes nothing; dependency health belongs in readiness (carefully) and in metrics and alerts.
11 — Loki and Elasticsearch both store logs. What is the core design difference? Important
Answer
Answer: Loki indexes only a small set of labels per stream and stores compressed chunks in object storage; Elasticsearch builds an inverted index on the content for full-text search, at higher storage and memory cost.
12 — Name three places to remove personal data from telemetry, from earliest to latest. Important
Answer
Answer: At the call site (constant messages, no PII fields), in the logger/SDK (slog ReplaceAttr, Monolog processor), and in the Collector (redaction, attributes delete/hash); then retention and access control in the store.
Glossary
| Term | Meaning |
|---|---|
| Observability | Ability to explain any internal state of a system from its outputs (term from control theory) |
| Monitoring | Collecting predefined metrics and alerting on known conditions |
| Unknown unknowns | Failure modes nobody predicted; observability's target |
| High cardinality | A field with very many distinct values (user id, trace id) |
| Cardinality explosion | Uncontrolled growth of metric series from unbounded label values |
| Telemetry | Data a system emits about itself: metrics, logs, traces, profiles |
| Signal | One kind of telemetry |
| Structured logging | Logs as typed key-value records, usually JSON |
| JSON logs | One JSON object per line |
| Log level | Severity: debug, info, notice, warning, error, critical, alert, emergency |
| Correlation id | An id grouping related lines; best implemented as the trace id |
| Trace id | 16-byte id shared by every span of a trace |
| Span id | 8-byte id of one span |
| Sampling | Keeping only a share of traces or logs |
| Log sampling | Dropping a share of low-value log lines |
| Redaction | Masking or removing sensitive values before storage |
| PII | Personally identifiable information |
| Fluent Bit | Lightweight CNCF telemetry agent for logs, metrics, traces |
| Vector | Observability pipeline tool for logs and metrics |
| Loki | Grafana's log store indexing labels only |
| LogQL | Loki's query language |
| Elasticsearch | Search engine with inverted indexes, used for logs (ELK) |
| OpenSearch | Apache-licensed fork of Elasticsearch and Kibana |
| ELK | Elasticsearch, Logstash, Kibana |
| ClickHouse | Columnar SQL database used for logs, traces and metrics (ClickStack) |
| Retention | How long data is kept |
| TTL | Time to live; ClickHouse rule deleting rows after an interval |
| Metric | A numeric measurement as a time series |
| Time series | Values over time for one metric name and label set |
| Counter | Monotonic cumulative metric, reset only on restart |
| Gauge | Metric that can go up and down |
| Histogram | Observations counted into buckets; aggregatable |
| Native histogram | Prometheus sparse exponential histogram stored as one sample |
| Summary | Client-side quantiles; not aggregatable |
| Bucket | Histogram range with an inclusive upper bound le |
| Label | Key-value dimension of a metric |
| Prometheus | Pull-based metrics system and TSDB |
| Pull model | The server scrapes targets |
| Scrape interval | How often a target is scraped |
| Exposition format | Prometheus text format for /metrics |
| OpenMetrics | Standardised exposition format with exemplars and # EOF |
up | Synthetic per-target series: 1 if the scrape succeeded |
| Pushgateway | Cache for metrics pushed by batch jobs |
| StatsD | UDP push protocol and daemon for counters, timers, gauges |
| PromQL | Prometheus query language |
| rate | PromQL per-second increase of a counter over a range |
| histogram_quantile | PromQL quantile estimate from histogram buckets |
| Recording rule | Precomputed PromQL stored as a new series |
| Remote write | Prometheus pushing samples to another store |
| Thanos | HA Prometheus with object-storage long-term retention |
| Mimir | Grafana's multi-tenant long-term Prometheus store |
| Cortex | CNCF multi-tenant Prometheus store, Mimir's ancestor |
| VictoriaMetrics | Time series database compatible with Prometheus |
| RED method | Rate, Errors, Duration per service |
| USE method | Utilization, Saturation, Errors per resource |
| Four golden signals | Latency, traffic, errors, saturation |
| SLI | Service level indicator: a user-centred measurement |
| Trace | Tree of spans for one request |
| Span | One unit of work with timing, attributes, status |
| Parent span | The span that caused a span; root has none |
| Span kind | SERVER, CLIENT, PRODUCER, CONSUMER, INTERNAL |
| Span event | Timestamped annotation on a span, such as an exception |
| Span link | Reference from a span to a span in another trace |
| Context propagation | Carrying trace context across process boundaries |
| traceparent | W3C header with version, trace id, parent id, flags |
| tracestate | W3C header with vendor-specific trace data |
| Baggage | W3C header carrying application key-values with the context |
| Head sampling | Decision at the trace start |
| Tail sampling | Decision after the trace is complete |
| OpenTelemetry | Vendor-neutral API, SDKs, Collector and OTLP |
| OTel SDK | Implementation of the API: sampling, processing, export |
| Auto-instrumentation | Instrumentation added without code changes |
| OTel Collector | Agent/gateway with receivers, processors, exporters |
| OTLP | OpenTelemetry Protocol over gRPC (4317) or HTTP (4318) |
| Receiver | Collector component accepting data |
| Processor | Collector component transforming data |
| Exporter | Component sending data to a backend |
| Connector | Collector component joining two pipelines |
| Jaeger | CNCF tracing backend from Uber |
| Tempo | Grafana's object-storage trace backend |
| Zipkin | Distributed tracing system from Twitter |
| Honeycomb | SaaS observability built on wide events |
| Datadog | Commercial SaaS monitoring platform |
| New Relic | Commercial SaaS observability platform with native OTLP ingest |
| Semantic conventions | Standard attribute and metric names |
| Exemplar | Example trace reference attached to a metric sample |
| Profiling | Sampling stacks to attribute resource use to code |
| pprof | Go profile format and tool, net/http/pprof endpoints |
| Continuous profiling | Always-on low-overhead production profiling |
| Pyroscope | Grafana's continuous profiling database |
| Parca | eBPF-based continuous profiler |
| Grafana | Dashboard and exploration UI |
| Dashboard as code | Dashboards generated and versioned in git |
| LGTM | Loki, Grafana, Tempo, Mimir |
| Pulse | Laravel's first-party production dashboard |
| Telescope | Laravel's development debug assistant |
| Horizon | Laravel's Redis queue dashboard and supervisor |
| promhttp | Go package serving /metrics |
| slog | Go's structured logging package log/slog |
| Health endpoint | URL for liveness/readiness checks (/up, /healthz, /readyz) |
| Alerting | Turning symptoms into notifications; see the next chapter |
References
- OpenTelemetry, Observability primer: https://opentelemetry.io/docs/concepts/observability-primer/
- OpenTelemetry, What is OpenTelemetry: https://opentelemetry.io/docs/what-is-opentelemetry/
- OpenTelemetry, Traces: https://opentelemetry.io/docs/concepts/signals/traces/
- OpenTelemetry, Metrics: https://opentelemetry.io/docs/concepts/signals/metrics/
- OpenTelemetry, Logs: https://opentelemetry.io/docs/concepts/signals/logs/
- OpenTelemetry, Baggage: https://opentelemetry.io/docs/concepts/signals/baggage/
- OpenTelemetry, Profiles: https://opentelemetry.io/docs/concepts/signals/profiles/
- OpenTelemetry, Context propagation: https://opentelemetry.io/docs/concepts/context-propagation/
- OpenTelemetry, Sampling: https://opentelemetry.io/docs/concepts/sampling/
- OpenTelemetry Collector: https://opentelemetry.io/docs/collector/
- OpenTelemetry Collector configuration: https://opentelemetry.io/docs/collector/configuration/
- OTLP specification: https://opentelemetry.io/docs/specs/otlp/
- Semantic conventions: https://opentelemetry.io/docs/concepts/semantic-conventions/
- HTTP spans conventions: https://opentelemetry.io/docs/specs/semconv/http/http-spans/
- HTTP metrics conventions: https://opentelemetry.io/docs/specs/semconv/http/http-metrics/
- Database spans conventions: https://opentelemetry.io/docs/specs/semconv/db/database-spans/
- Tail sampling processor: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/tailsamplingprocessor/README.md
- Redaction processor: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/redactionprocessor/README.md
- Load-balancing exporter: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/exporter/loadbalancingexporter/README.md
- Span metrics connector: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/connector/spanmetricsconnector/README.md
- OpenTelemetry Go: https://opentelemetry.io/docs/languages/go/ and https://pkg.go.dev/go.opentelemetry.io/otel
- otelhttp: https://pkg.go.dev/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp
- OpenTelemetry PHP: https://opentelemetry.io/docs/languages/php/
- OpenTelemetry PHP instrumentation: https://opentelemetry.io/docs/languages/php/instrumentation/
- OpenTelemetry PHP propagation: https://opentelemetry.io/docs/languages/php/propagation/
- OpenTelemetry PHP zero-code: https://opentelemetry.io/docs/zero-code/php/ and https://opentelemetry.io/docs/zero-code/php/auto/
- OpenTelemetry Laravel auto-instrumentation: https://github.com/open-telemetry/opentelemetry-php-contrib/tree/main/src/Instrumentation/Laravel
- Prometheus overview: https://prometheus.io/docs/introduction/overview/
- Prometheus metric types: https://prometheus.io/docs/concepts/metric_types/
- Prometheus naming: https://prometheus.io/docs/practices/naming/
- Prometheus histograms and summaries: https://prometheus.io/docs/practices/histograms/
- Prometheus instrumentation: https://prometheus.io/docs/practices/instrumentation/
- Prometheus, when to use the Pushgateway: https://prometheus.io/docs/practices/pushing/
- Prometheus recording rule practices: https://prometheus.io/docs/practices/rules/
- PromQL functions: https://prometheus.io/docs/prometheus/latest/querying/functions/
- Prometheus exposition formats: https://prometheus.io/docs/instrumenting/exposition_formats/
- Prometheus configuration: https://prometheus.io/docs/prometheus/latest/configuration/configuration/
- Prometheus storage: https://prometheus.io/docs/prometheus/latest/storage/
- Prometheus feature flags: https://prometheus.io/docs/prometheus/latest/feature_flags/
- OpenMetrics specification: https://prometheus.io/docs/specs/om/open_metrics_spec/
- W3C Trace Context: https://www.w3.org/TR/trace-context/
- W3C Baggage: https://www.w3.org/TR/baggage/
- Google SRE Book, Monitoring Distributed Systems: https://sre.google/sre-book/monitoring-distributed-systems/
- Brendan Gregg, The USE Method: https://www.brendangregg.com/usemethod.html
- Grafana Labs, The RED Method: https://grafana.com/blog/2018/08/02/the-red-method-how-to-instrument-your-services/
- Dapper (Google, 2010): https://research.google/pubs/dapper-a-large-scale-distributed-systems-tracing-infrastructure/
- Honeycomb, What is observability: https://www.honeycomb.io/what-is-observability
- Charity Majors, Observability is a many-splendored thing: https://charity.wtf/2020/03/03/observability-is-a-many-splendored-thing/
- Wikipedia, Observability (control theory, secondary): https://en.wikipedia.org/wiki/Observability
- Grafana Loki overview: https://grafana.com/docs/loki/latest/get-started/overview/
- Loki label best practices: https://grafana.com/docs/loki/latest/get-started/labels/bp-labels/
- Grafana Tempo: https://grafana.com/docs/tempo/latest/
- Grafana Mimir: https://grafana.com/oss/mimir/
- Grafana Pyroscope: https://grafana.com/docs/pyroscope/latest/
- Grafana provisioning: https://grafana.com/docs/grafana/latest/administration/provisioning/
- Thanos: https://thanos.io/
- Cortex: https://cortexmetrics.io/docs/
- VictoriaMetrics: https://docs.victoriametrics.com/victoriametrics/single-server-victoriametrics/
- Parca: https://www.parca.dev/
- Fluent Bit: https://docs.fluentbit.io/manual
- Vector: https://vector.dev/docs/
- Jaeger: https://www.jaegertracing.io/docs/latest/
- Zipkin: https://zipkin.io/
- New Relic OTLP endpoint: https://docs.newrelic.com/docs/opentelemetry/best-practices/opentelemetry-otlp/
- ClickHouse observability: https://clickhouse.com/docs/use-cases/observability
- ClickHouse TTL: https://clickhouse.com/docs/guides/developer/ttl
- Prometheus Pushgateway: https://github.com/prometheus/pushgateway
- StatsD: https://github.com/statsd/statsd
- prometheus/client_golang: https://github.com/prometheus/client_golang and https://pkg.go.dev/github.com/prometheus/client_golang/prometheus/promhttp
- Go net/http/pprof: https://pkg.go.dev/net/http/pprof
- Go log/slog: https://pkg.go.dev/log/slog
- Go diagnostics: https://go.dev/doc/diagnostics
- PromPHP prometheus_client_php: https://github.com/PromPHP/prometheus_client_php
- hipages php-fpm_exporter: https://github.com/hipages/php-fpm_exporter
- Laravel 13 Pulse: https://laravel.com/docs/13.x/pulse
- Laravel 13 Telescope: https://laravel.com/docs/13.x/telescope
- Laravel 13 Horizon: https://laravel.com/docs/13.x/horizon
- Laravel 13 Logging: https://laravel.com/docs/13.x/logging
- Laravel 13 Context: https://laravel.com/docs/13.x/context
- Laravel 13 Deployment (health route): https://laravel.com/docs/13.x/deployment
- Laravel 13 Middleware: https://laravel.com/docs/13.x/middleware
- Laravel 13 Queues: https://laravel.com/docs/13.x/queues