Skip to content

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 forGo to
The whole page in four tablesEverything in one minute
Why dashboards alone stop workingWhy it exists
Kalman, Dapper, Prometheus, OpenTelemetryWhere it comes from
Monitoring vs observability, unknown unknownsObservability vs monitoring
JSON logs, levels, trace ids, log sampling, redactionStructured logging
Fluent Bit, Vector, Loki, Elasticsearch, ClickHouseLog pipelines and storage
Counter, gauge, histogram, summaryMetric types
Labels and cardinality explosionsCardinality
Pull model, exposition format, Pushgateway, StatsDPrometheus
rate, histogram_quantile, recording rulesPromQL
RED, USE, four golden signals, SLIsMethods
Thanos, Mimir, Cortex, VictoriaMetricsLong-term storage
Spans, parents, kinds, attributes, events, linksTraces and spans
traceparent, tracestate, baggageContext propagation
Head vs tail samplingSampling
API, SDK, Collector, OTLPOpenTelemetry
http.route, service.name, naming rulesSemantic conventions
Metric to trace to logExemplars and correlation
pprof, Pyroscope, ParcaProfiling
Grafana, provisioning, dashboards in gitDashboards
LGTM, ELK/OpenSearch, ClickStack, Datadog, New Relic, HoneycombStack choices
Liveness, readiness, /upHealth endpoints
Jobs, queues, cronAsync work
Money, retention, GDPRCost, retention and compliance
Exact formats, knobs and messagesMechanics
CodeGo, Laravel
Classic failures and their fixesSolving the classic problems
Which stack, which sampling, which signalChoosing
Monolith to distributed systemIn architecture
Numbers from a real runLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four signals.

SignalUnitCheap atExpensive atAnswersTypical store
MetricsA number per time series per scrapeVolume (aggregated before storage)Cardinality (every label combination is a series)Is something wrong, how much, since when?Prometheus, Mimir, Thanos, VictoriaMetrics
TracesA tree of spans per requestContext (every attribute rides along)Volume (one span per hop per request), so sampledWhere did the time or the error go?Tempo, Jaeger, Zipkin, Honeycomb
LogsA timestamped event, ideally JSONDetail (any field)Volume and indexing, plus personal dataWhat exactly happened in this step?Loki, Elasticsearch/OpenSearch, ClickHouse
ProfilesSampled stack traces over timeCode-level resolutionStorage per process, still maturing in OpenTelemetry (Alpha)Which function burned the CPU or memory?Pyroscope, Parca, pprof files

Three methods, one question each.

MethodApply it toMeasureSource
REDEvery request-driven serviceRate, Errors, DurationTom Wilkie, Grafana Labs
USEEvery resource (CPU, disk, pool, queue)Utilization, Saturation, ErrorsBrendan Gregg
Four golden signalsA user-facing systemLatency, traffic, errors, saturationGoogle SRE Book, chapter 6

Defaults and numbers you will meet.

NumberMeaning
scrape_interval 1m, scrape_timeout 10s, evaluation_interval 1mPrometheus global defaults; most teams set 15s or 30s
15dPrometheus local retention when neither --storage.tsdb.retention.time nor .size is set
1-2 bytes per samplePrometheus 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 bucketsOpenTelemetry advisory buckets for http.server.request.duration
4317 / 4318OTLP over gRPC / over HTTP default ports
55 characterstraceparent value length: 2 + 32 + 16 + 2 hex digits plus three dashes
32 / 64 / 8192Max tracestate list members / max baggage members / max baggage bytes
128 code pointsOpenMetrics limit on the combined exemplar label names and values
30s, 50000Collector tail_sampling defaults for decision_wait and num_traces
1000 msDefault threshold of the Laravel Pulse slow requests, slow jobs, slow queries cards

The stacks, side by side.

StackMetricsLogsTracesProfilesUIOperated by
LGTM (Grafana)Prometheus + MimirLokiTempoPyroscopeGrafanaYou or Grafana Cloud
ELK / OpenSearchElasticsearch / OpenSearch (or Prometheus beside it)Elasticsearch / OpenSearchElastic APM / OpenSearch trace analyticsElastic Universal ProfilingKibana / OpenSearch DashboardsYou or Elastic Cloud / AWS
ClickHouse (ClickStack)ClickHouseClickHouseClickHouse-HyperDX / GrafanaYou or ClickHouse Cloud
Jaeger + PrometheusPrometheusAnyJaeger-Jaeger UI + GrafanaYou
SaaSDatadog, New Relic, Honeycomb, Grafana CloudSame vendorSame vendorSome vendorsVendor UIVendor, priced per GB, host, series or event
Neutral layer under any of themOpenTelemetry SDK + Collector + OTLPSwappable backend
METRICScounters, gauges, histogramscheap, aggregated, alertableanswers: is something wrong?bounded labels onlyTRACESspans: parent, child, timingone request across servicesanswers: where did the time go?sampled: head or tailLOGSstructured JSON eventstrace_id and span_id fieldsanswers: what exactly happened?volume and PII are the costsPROFILESstacks sampled over timepprof, Pyroscope, Parcaanswers: which code burned it?continuous, low overheadtrace_idthe join keyexemplar: trace_id on a buckettrace_id, span_id in each linespan linklog-derivedmetricsalert on metrics, investigate with traces, confirm with logs, fix with profiles

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 aloneObservability
Predefined metrics and thresholdsTelemetry rich enough to ask new questions
Known unknowns: disk full, CPU high, error rate upUnknown unknowns: only Android 14 users in one region on the new pricing flag
Low-cardinality aggregatesHigh-cardinality, high-dimensional events (user id, build id, tenant) on spans and logs
Dashboards per componentQueries that follow one request across components
"Is it up?""Why is it slow for these users?"
Reactive alert, then guessworkAlert, 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 ​

  1. "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.
  2. "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.
  3. "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.

text
     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 signal

The 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.

text
     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 shipped

Real 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 familyStrong forWeak for
Prometheus + GrafanaKnown metrics, alerting, long trendsPer-user or per-request questions (labels must be bounded)
Honeycomb (wide events)Arbitrary group-by on high-cardinality fieldsCheap long-term infrastructure metrics
Tempo / JaegerOne request's pathAggregates across millions of requests (unless span metrics or TraceQL metrics)
Loki / Elasticsearch / ClickHouseDetail and text searchJoining 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.

text
     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 processes

Real 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.

ConcernGo log/slogLaravel / MonologCollector side
JSON outputslog.NewJSONHandler'formatter' => Monolog\Formatter\JsonFormatter::classfilelog receiver with a JSON parser
Levelsslog.LevelDebug/Info/Warn/Error, HandlerOptions.LevelEight RFC 5424 levels, channel level optionfilter processor on severity_number
Request contextlogger.With(...), context-aware handlerLog::withContext, Log::shareContext, Context::addresource/attributes processors
Trace idCustom slog.Handler reading trace.SpanContextFromContextContext::add('trace_id', ...) from the active spanOTLP log records carry TraceId/SpanId natively
RedactionHandlerOptions.ReplaceAttrMonolog processor added by a channel tapredaction, attributes (delete, hash) processors
SamplingMiddleware decides before loggingPulse recorder sample_rate; your own middlewareprobabilistic_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).

text
     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 cost

Real 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").

StoreIndexQueryStorageGood atWatch out for
Grafana LokiLabels only (keep them "limited to tens of values")LogQLObject storage (S3, GCS, Azure Blob)Cheap volume, KubernetesHigh-cardinality labels; unselective queries
Elasticsearch / OpenSearchInverted index on fields and textQuery DSL, KQL, Lucene, PPLLocal SSD, tiers (hot/warm/cold), snapshotsFull-text search, security analyticsHeap, shard counts, storage multiple of raw
ClickHouseSparse primary key, skip indexes, columnsSQLColumnar, compressed, TTL per rowAggregations, joins, long retentionSchema design and ORDER BY choice
Vendor SaaSVendor-specificVendor UIVendorNo operationsPer-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.

text
     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 it

Real 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.

NeedPrometheus typeOpenTelemetry instrumentPromPHP (Laravel)client_golang (Go)
Events so farCounter _totalCountergetOrRegisterCounter()->inc()prometheus.NewCounterVec
Current levelGaugeGauge / UpDownCounter / async gaugegetOrRegisterGauge()->set()prometheus.NewGauge
Distribution, aggregatableHistogram (classic or native)HistogramgetOrRegisterHistogram(..., $buckets)prometheus.NewHistogramVec with Buckets or NativeHistogramBucketFactor
Exact client-side quantile, one processSummary(none; histograms only)getOrRegisterSummaryprometheus.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.

counter: method x route x code5 x 40 x 12 x 30 instances72 k series, about 12 GB for 15 dayshistogram: method x routex (14 buckets + 3)102 k series, about 16 GBhistogram + code labelone label, x121.2 M series, about 200 GBcounter + user_id100 k users7.2 billion series: the cardinality explosionbars are on a log scale; estimates from cmd/cardinality, 15 s scrape, 2 bytes per sampleRule: a label value must come from a small, closed set. user_id, order_id, email, raw URL path and trace_id go on spans and logs,never on metric labels (an exemplar is the one place a trace id sits next to a metric).
text
     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 scrape

Real 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.

DefenceWhereEffect
Route template, not pathInstrumentation (Go r.Pattern, Laravel $request->route()->uri())/orders/{id} is one value
Normalise unknown valuesInstrumentation (_OTHER for unknown HTTP methods, unmatched for 404s)Scanners cannot create series
sample_limit, label_limitPrometheus scrape_configOver the limit, "the entire scrape will be treated as failed" for that target only
metric_relabel_configs with labeldropPrometheusDrop a bad label before ingestion
Per-tenant limitsMimir, Cortex, VictoriaMetricsMax series per tenant
High-cardinality fields on spans/logsDesignQuestions 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.

text
     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 counts

Real 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 pathModelHealth signalBest forPitfall
Prometheus scrapePullup, scrape_duration_secondsLong-running servicesNeeds discovery and network reachability
PushgatewayPush, cachedNone per instanceService-level batch jobsNever forgets series; single point of failure
StatsD + statsd_exporterPush over UDPNoneLegacy, very short-lived processesLossy UDP, aggregation in the daemon
OTLP to CollectorPushCollector's own metricsMulti-signal, vendor-neutralAnother component to run and size
Prometheus remote writePush from PrometheusRemote-write queue metricsLong-term store (Mimir, Thanos Receive, VictoriaMetrics)Backpressure when the receiver is slow
Prometheus Agent modeScrape then forwardupEdge clusters without local queryNo 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.

text
     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_interval

Real 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).

FunctionInputUseTrap
rateCounter rangeAlerts, dashboardsAggregate after, never before
irateCounter rangeZoomed-in graphsToo spiky for alerts
increaseCounter range"How many in the last hour"Extrapolated, may be fractional
histogram_quantileBucket rates with lep50/p90/p99Accuracy bounded by bucket width; keep le in by
sum by / withoutInstant vectorCollapse labelsRemoving le breaks quantiles
absentInstant vectorAlert when a metric disappearsNeeds 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.

text
     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 days

Real 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").

MethodUnit of analysisError definitionSaturation signalGood starting dashboard
REDService / route5xx, timeouts (not 4xx)(not part of RED)Rate, error ratio, p50/p99 per route
USEResourceDevice or operation errorsQueue length, wait timeOne row per resource
Golden signalsUser-facing systemExplicit, implicit (wrong content) and policy (too slow) failures"How full" the most constrained resource isFour 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.

text
     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 graphs

Real 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.

ProductIngestStorageMulti-tenantHA dedupNotes
Prometheus aloneScrapeLocal TSDB, 15d defaultNoNo (run two, pick one)Simplest; vertical scaling only
ThanosSidecar upload or Receive (remote write)Object storageOptionalQuerier dedup by replica labelDownsampling, works with existing Prometheus
Grafana MimirRemote write, OTLPObject storageYesDistributor HA trackerTested "to 1 billion active series" (vendor claim)
CortexRemote writeObject storage (blocks)YesYesCNCF; Mimir's ancestor
VictoriaMetricsRemote write, scrape (vmagent), many protocolsOwn format, local or clusterCluster versionYesPromQL-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).

0 ms100200300400gateway SERVERorders SERVERSELECT ordersPOST /v1/chargespayments SERVERorders processPOST /checkout 412 ms, root span, no parentPOST /checkout 395 ms, parent = gateway span18 ms, CLIENT, db.system.name=postgresql350 ms, CLIENT span in orders340 ms, status ERROR after retry, the slow hopCONSUMER, later, same trace idtraceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01 (version - trace-id - parent-id - flags)every hop forwards the same trace-id and replaces parent-id with its own span id; flags 01 = sampled
text
     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 id

Real 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.

BackendStorageQueryStrengthNote
Grafana TempoObject storage only ("only requires an object storage to operate")TraceQL, trace id lookupCheap at scale, metrics-generatorSearch by attributes is via TraceQL
JaegerCassandra, Elasticsearch/OpenSearch, Badger, memoryService/operation/tags, trace idCNCF graduated, Uber originJaeger v2 is built on the OpenTelemetry Collector
ZipkinMemory, Cassandra, ElasticsearchService, tags, duration; dependency diagramSimple, matureReports over HTTP or Kafka
HoneycombVendor columnar storeGroup by any field, BubbleUpHigh-cardinality analysis, wide eventsPriced "by event volume"
Elastic APM / OpenSearch trace analyticsElasticsearch / OpenSearchKibana / DashboardsSame store as logsIndex 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.

text
     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-observability

Real 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).

CarrierGoLaravel / PHPNote
HTTP serverpropagation.HeaderCarrier(r.Header) + Extract, or otelhttp.NewHandlerAuto-instrumentation, or TraceContextPropagator::getInstance()->extract($request->getHeaders())Done once in middleware
HTTP clientotelhttp.NewTransport or InjectPSR-18 / Laravel HTTP client instrumentation, or inject($carrier)Every outbound call
Queue jobInject into message headersContext::addHidden('traceparent', ...); Context is captured at dispatchLaravel Context travels with jobs
Broker recordHeaders in Kafka/RabbitMQ/Redis StreamsSameMessaging conventions: Messaging Observability
Logstrace_id field from the span contextContext::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.

text
     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               found

Real 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").

ApproachWhereKeeps all errorsCostComplexity
Always onSDKYesHighestNone
Head ratio (TraceIDRatioBased)SDK, at the rootNoProportional to ratioLow
Parent-basedSDK, every hopFollows root-Low; keeps traces whole
Tail (tail_sampling)Collector tierYesBuffer memory, extra tierHigh: sticky routing by trace id
Vendor dynamic samplingVendor (e.g. Honeycomb Refinery)ConfigurableVendorMedium
Logs follow tracesYour middlewareErrors always loggedLower log volumeLow

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."

Go serviceotel SDK, slogpromhttp /metricspprof on loopbackLaravel appOTel PHP extensionMonolog JSON stderrPulse, HorizonAgent Collectorreceivers: otlp 4317 / 4318filelog, prometheusprocessors: memory_limiterredaction, attributesexporter: load_balancingrouting_key traceIDSampler tierspanmetrics: REDfrom 100% of spanstail_samplingerrors + slow + 5%exportersotlp, remote writeTracesTempo, Jaeger, ZipkinLogsLoki, Elastic, ClickHouseMetricsPrometheus, Mimir, ThanosGrafanadashboards, ExplorePrometheus pull: scrape /metrics every 15 sOTLP push for traces and logs; the agent sees each span first, the sampler sees whole traces
text
     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 -> Mimir

Real 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.

LayerGoPHP / LaravelNotes
APIgo.opentelemetry.io/otel, otel/trace, otel/metricopen-telemetry/api (Globals::tracerProvider())Safe no-op without SDK
SDKgo.opentelemetry.io/otel/sdk/trace, sdk/metricopen-telemetry/sdkSampler, processors, resource
Auto-instrumentationotelhttp, otelgrpc, otelsql; eBPF agentpecl install opentelemetry + OTEL_PHP_AUTOLOAD_ENABLED=true + auto packagesPHP: Composer + PECL, or the OS-package PHP Distro on Linux
Exporterotlptracehttp, otlptracegrpc, stdoutopen-telemetry/exporter-otlpOTEL_EXPORTER_OTLP_ENDPOINT
Collectorotelcol / otelcol-contrib binarySameAgent and gateway roles
BackendsJaeger, Tempo, Zipkin, Honeycomb, Datadog, New Relic (native OTLP ingest), ElasticSameChosen 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.

text
     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=prod

Real 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.

DomainKey attributesSpan kind
HTTP serverhttp.request.method, http.route, http.response.status_code, url.pathSERVER
HTTP clienthttp.request.method, server.address, url.fullCLIENT
Databasedb.system.name, db.operation.name, db.collection.name, db.query.text (often redacted)CLIENT
Messagingmessaging.system, messaging.operation.type, messaging.destination.namePRODUCER / CONSUMER
Resourceservice.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.

text
     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 service

Real 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.

LinkProducer sideBackend side
Metric -> traceclient_golang ObserveWithExemplar, OTel SDK exemplarsPrometheus exemplar-storage, Mimir; Grafana "Exemplars" toggle
Trace -> logstrace_id in every log lineGrafana Tempo data source "Trace to logs"; Loki derived fields
Log -> traceSame fieldLoki derived field regex to Tempo; Kibana APM links
Trace -> metricsservice.name, http.route attributesspanmetrics connector, Tempo metrics-generator
Trace -> profileSpan id labels in profilesPyroscope 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.

text
     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.

ToolLanguagesModeOverhead modelProduction use
Go net/http/pprofGoOn demand over HTTPSampling; only while a profile is taken (CPU)Yes, on a private port
Grafana PyroscopeGo, Java, Python, Ruby, .NET, PHP (via eBPF/agents)ContinuousSampling, lowYes
ParcaAny (eBPF)Continuous, node-wideSampling, lowYes, Linux
Xdebug / SPXPHPOn demandHigh (Xdebug), moderate (SPX)Development / staging
OTel profilesMany (Alpha)Continuous via OTLPSamplingExperimental

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.

text
     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 prod

Real 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).

ApproachFormatReview in gitNotes
UI-onlyStored in Grafana DBNoFast to start, drifts
JSON provisioningDashboard JSON + provider YAMLYesNative, verbose diffs
Jsonnet / GrafonnetCode generating JSONYesReuse via libraries
Terraform providerHCLYesSame 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.

text
     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 changes

Real 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.

CriterionLGTMELK / OpenSearchClickHouse / ClickStackSaaS (Datadog, New Relic, Honeycomb)
Log searchLabel-first, grep-likeFull-text, bestSQL, fast aggregationsVendor
Storage costLow (object storage)High (indexes, SSD)Low-medium (columnar compression)Per GB ingested/indexed
High-cardinality analysisTempo TraceQL, limited on metricsAggregations on fieldsStrongHoneycomb strongest
Operations burdenMedium (several components)High (cluster, shards, heap)MediumNone
Lock-in riskLow (open source, OTLP)Low-mediumLowHigh 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.

text
     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 flushed

Real 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").

ProbeChecksFailure meansExample
LivenessProcess respondsRestartLaravel /up, Go /healthz
ReadinessCan serve now (warm, not draining)Remove from load balancerGo /readyz
StartupFinished bootingWait before livenessKubernetes startupProbe
Synthetic / black-boxUser journey from outsideAlertUptime 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.

text
     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_charged

Real 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.

NeedLaravelGo
Context into jobContext::add, Context::addHidden (automatic capture)Inject into message headers
Job spanManual span, SpanKind::KIND_CONSUMER (ChargeOrder)tracer.Start(ctx, "... process", WithSpanKind(Consumer))
Wait time and throughputHorizon metrics, horizon:snapshotHistogram of now - enqueued_at
Failuresfailed_jobs, Pulse exceptions, Horizon failedCounter by outcome
Batch / cronPushgateway or a "last success" gaugeSame

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.

text
     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 node

Real 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.

SignalTypical hot retentionLong-term formMain cost lever
Metrics15 d local (Prometheus default)13 months in Mimir/Thanos, downsampledSeries count
Logs7-30 dArchive to object storage; errors longerVolume, indexing
Traces7-30 dSpan metrics kept as metricsSampling
Profiles7-30 dAggregated flame graphsSample rate
Audit logsPer regulation (often 1 year+)WORM / cold storageSeparate 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.

text
# 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
ElementRuleSource
# HELP, # TYPEOne per metric family, before its samplesPrometheus exposition formats
Counter nameEnds in _total (OpenMetrics: the family name has no suffix, samples have _total)Prometheus naming, OpenMetrics
Histogram bucketsCumulative, le inclusive upper bound, +Inf equals _countPrometheus metric types
Exemplar# {labels} value [timestamp], at most one per bucket, labels within 128 code pointsOpenMetrics
Content typeapplication/openmetrics-text; version=1.0.0; charset=utf-8OpenMetrics
End# EOF required in OpenMetricsOpenMetrics

traceparent, field by field ​

text
     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
FieldInvalid inputReceiver behaviour
version ffInvalidIgnore header, start a new trace
trace-id all zeroForbiddenIgnore header (the Laravel middleware generates a fresh id; tested)
parent-id with uppercase hexInvalid"Vendors MUST ignore the traceparent when the parent-id is invalid"
flags 00Valid: not sampledParent-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.

yaml
# 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.

yaml
# 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]
KnobDefaultWhat it doesOur value
tail_sampling.decision_wait30sTime a trace is buffered before the decision10s
tail_sampling.num_traces50000Traces kept in memory; oldest evicted when full (unless block_on_overflow)200000
tail_sampling.expected_new_traces_per_sec0Sizing hint for data structures2000
memory_limiter.limit_mib / spike_limit_mib-Hard and spike memory bounds400/100 agent, 3000/600 sampler
load_balancing.routing_keytraceID for tracesSticky routing so all spans of a trace meettraceID
redaction.allow_all_keysfalse (fail closed: no attributes kept)Keep keys, mask values by patterntrue + blocked patterns
OTLP receiver endpointslocalhost4317 gRPC, 4318 HTTPloopback on the agent

Prometheus configuration and recording rules ​

yml
# 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
yml
# 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]))
SettingDefaultEffect
global.scrape_interval1mResolution of every series; 15s is common
global.scrape_timeout10sA slower scrape fails, up becomes 0
global.evaluation_interval1mHow often rules run
sample_limit0 (no limit)Over the limit after relabelling, "the entire scrape will be treated as failed"
label_limit0 (no limit)Max labels per sample
--storage.tsdb.retention.time15d (when no size is set)Local history
--storage.tsdb.retention.size0 (disabled)Oldest blocks deleted above the size
--enable-feature=exemplar-storageoffKeep exemplars (OpenMetrics scrape)

What you will see when something is wrong ​

Symptom (verbatim where quoted)WhereMeaningAction
traces export: Post "http://127.0.0.1:4318/v1/traces": dial tcp 127.0.0.1:4318: connect: connection refusedGo OTel SDK error handler (observed in our Lab run)No Collector listening; spans are dropped after the batch queue fillsRun the agent Collector or point OTEL_EXPORTER_OTLP_ENDPOINT elsewhere
up == 0PrometheusScrape failed (timeout, refused, sample limit)Check scrape_duration_seconds, target logs
Scrape failed after sample_limitPrometheus target pageCardinality grew past the guard railFind the new label, roll back
phpfpm_max_children_reached increasingphp-fpm_exporter"The number of times, the process limit has been reached"Saturation: more workers or less work per request
phpfpm_listen_queue > 0php-fpm_exporterRequests waiting for a workerSaturation (USE)
Traces with missing childrenTempo / JaegerSpans of one trace went to different tail samplers, or a hop dropped traceparentSticky routing; inject at every hop
Pulse values prefixed with ~Pulse dashboardSampling 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.

go
// 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.

go
// 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.

go
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.

go
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.

go
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.

go
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.

go
// 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).

go
// 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 codeAlternativeWhy this one
Hand-written middlewareotelhttp.NewHandler(handler, "orders")Shows every step; in production otelhttp plus WithSpanNameFormatter is fine
Prometheus client for metricsOTel metrics SDK + Prometheus exporter or OTLPExemplars and promhttp are mature; OTel metrics are equally valid
r.Pattern from the inner requestURL pathBounded label; works with Go 1.22+ ServeMux patterns
Exemplar only when sampledAlwaysAn exemplar to a dropped trace is a dead link
Logs follow trace sampling for 2xxLog every requestVolume drops by the sampling ratio; every kept line has a trace
pprof on loopbackimport _ "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:

php
// 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 pruned

After ​

Install the pieces (commands from the Laravel 13, OpenTelemetry PHP and PromPHP documentation; expected, not run):

bash
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,tracecontext

The 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 toolWhat it isUse in productionLimits
PulseFirst-party dashboard at /pulse: servers, usage, exceptions, queues, slow requests/jobs/queries/outgoing requests, cacheYes, behind the viewPulse gate; Redis ingest with pulse:work for volume; pulse:check for the servers cardAggregates in your database, not a tracing or log system; sampling shows ~ values
TelescopeRequest/query/job/mail inspectorNo: "local development"; install with --dev, register only when environment('local')Grows fast: schedule telescope:prune
HorizonRedis queue dashboard and supervisorYesMetrics need horizon:snapshot every five minutes; retention by metrics.trim_snapshots
Log + ContextMonolog channels, Log::withContext, Log::shareContext, Context::addYesContext metadata on every line: keep it small
OpenTelemetry PHPExtension + SDK + auto packages, manual spansYesExtension required for auto-instrumentation; export cost per request in PHP-FPM
PromPHP + php-fpm_exporter/metrics for app and poolYesRedis 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 ​

SolutionHowAdvantageCost / limitation
Histograms, not averageshttp_server_request_duration_seconds with buckets around the SLOp99 and "share under 250 ms" become visibleMore series (buckets + 3 per label set)
Per-route REDroute label from the templateThe slow route stands out from the fast majorityRoutes must be bounded
ExemplarsObserveWithExemplar + OpenMetrics + exemplar-storageOne click from the slow bucket to a real traceOnly sampled traces are reachable
Black-box probeSynthetic check from outsideSees DNS, TLS, CDN problems the app never seesOne more system
Golden-signal saturationPool queue, run queue, phpfpm_listen_queueFinds waiting that latency inside the app does not showNeeds exporters per resource

Cardinality explosion after a deploy ​

SolutionHowAdvantageCost / limitation
Guard railssample_limit, label_limit per scrape jobOne bad target fails, Prometheus survivesThat target's metrics are lost until fixed
Drop at ingestionmetric_relabel_configs with action: labeldropImmediate relief without a deployHides the bug if left forever
Route templates and _OTHERInstrumentation code (Go test proves it)Fixed by designNeeds discipline in every service
Find the culprittopk(10, count by (__name__) ({__name__=~".+"})), Prometheus TSDB status page, Mimir cardinality APIData, not guessesExpensive query on large servers
Move to spansPer-user questions answered by traces/wide eventsNo metric costNeeds tracing coverage

The log bill doubled ​

SolutionHowAdvantageCost / limitation
Level disciplineINFO in production, DEBUG via a flag for minutesBiggest single leverNeed a way to turn DEBUG on safely
Log sampling tied to tracesSuccessful requests logged only when traced (Go middleware)Volume drops by the sampling ratioUnsampled successes have no access line
Drop at the agentFluent Bit / Vector / Collector filter on health checks, botsNo code changeRules must be maintained
Tiered retentionClickHouse TTL DELETE WHERE, Loki per-stream retention, Elasticsearch ILMErrors kept long, noise shortConfiguration per store
Log-derived metricsCount in the pipeline, store the numberKeeps the trend, drops the linesLose 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.

sql
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) ​

SolutionHowAdvantageCost / limitation
Inject/extract at every async hopLaravel hidden Context, message headersOne trace from request to jobEvery producer and consumer must do it
Span links for fan-inConsumer span links to many producer spansCorrect for batchesUI support varies
Edge proxy starts or forwardsNGINX/Envoy/ALB tracing configTrace starts at the edgeProxies that strip headers must be fixed
Test itGo TestContinuesIncomingTrace; Laravel feature testRegression-proofNeeds a span recorder

"We cannot find the trace for that slow request" ​

SolutionHowAdvantageCost / limitation
Tail samplingCollector tail_sampling errors + latency + baselineInteresting traces keptStateful tier, sticky routing
Return the trace idTrace-Id response header, shown on error pagesSupport tickets carry the keyMust not be confused with a secret
Always sample critical routesCustom sampler or string_attribute policy on http.routeCheckout always tracedVolume
Span metrics before samplingspanmetrics connector on 100%Exact RED even with 5% tracesExtra metrics series

Personal data in logs and traces ​

SolutionHowAdvantageCost / limitation
Redact at the sourceslog ReplaceAttr, Monolog processor via tapNever writtenKey lists must be maintained
Redact in the Collectorredaction (fail-closed allow-list), attributes delete/hashCentral, catches libraries"one line of defence", not the only one
Constant messages"login failed" + typed fieldsRedaction can work on keysCode review
Drop query textDelete db.query.text or keep parameterised statements onlyNo customer values in spansLess debugging detail
Retention and access controlShort TTL, per-team accessLimits exposureConfiguration 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 ​

SolutionHowAdvantageCost / limitation
Remote write to Mimir / VictoriaMetricsremote_writeHorizontal, multi-tenant, object storageAnother distributed system
Thanos sidecar + store + compactorUpload blocks, query globallyKeeps existing Prometheus, downsamplingSeveral components
Recording rules for long-term viewsKeep only aggregates longSmallDetail gone after short retention

Choosing ​

Which signal answers which question ​

QuestionFirst signalThenWhy
Is the service healthy right now?Metrics (RED, golden signals)AlertCheap, continuous
Which route, version or region is affected?Metrics with bounded labels, span metricsTraces grouped by attributeBounded dimensions on metrics, the rest on spans
Why is this one request slow?TraceLogs of the slow spanThe waterfall shows the hop
What exactly failed in this step?LogsException event on the spanDetail and stack traces
Which code is using the CPU or memory?ProfileDiff against last releaseCode-level cost
Which customers are affected?Spans / wide events with tenant.idLogsHigh cardinality belongs there
Did the nightly job run?Pushed "last success" gaugeJob logsBatch jobs cannot be scraped

Which stack ​

SituationRecommendationExtra techniqueReason
Small team, Kubernetes, cost-sensitivePrometheus + Grafana + Loki + Tempo (LGTM), OTel CollectorObject storage for all threeLow storage cost, one UI
Heavy full-text log search, security analyticsElasticsearch or OpenSearch for logs, Prometheus for metricsILM hot/warm/coldInverted index is the strength
High-cardinality analytics on events, SQL skillsClickHouse (ClickStack)Tiered TTL, LowCardinality columnsColumnar compression and SQL
No operations capacitySaaS (Datadog, New Relic, Honeycomb, Grafana Cloud)OTel SDK + Collector, budget alerts on ingestPay money instead of on-call
Debugging unknown unknowns across many servicesWide events/traces with rich attributes (Honeycomb, Tempo TraceQL, ClickHouse)Tail samplingGroup by any field
Many clusters, 13 months retentionMimir or Thanos or VictoriaMetricsexternal_labels, downsamplingGlobal view and long history
Laravel monolith on a few serversPulse + Horizon + JSON logs + php-fpm_exporter, add OTel when services splitRedis ingest for PulseFirst-party, minimal setup

Which sampling ​

TrafficHead ratio in SDKTail policy in CollectorNote
Under 50 rps per service1.0NoneKeep everything
50-2000 rps1.0Errors + latency + 5-10%Tail tier sized for full volume
Above 2000 rps0.1-0.25Errors + latency on what arrivesReduce before the network
Critical route (checkout)1.0 for that routeAlways keepCustom sampler or attribute policy
Batch / cron1.0KeepFew, 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:

text
     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 it

A 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 ​

LoadMetricsLogsTracesPeople
1x (100 rps, 5 services)One Prometheus pair, 15dLoki single binary or hosted100% sampled to Tempo/JaegerOne shared dashboard set
10x (1 000 rps, 30 services)Prometheus per cluster + Mimir/ThanosAgent pipeline with drop and sampling rulesCollector agent + tail sampling tierDashboards as code, owners per service
100x (10 000+ rps, 200 services)Per-tenant limits, cardinality budgets per teamTiered retention, log-derived metrics, archiveHead sampling at source + tail; span metrics for REDObservability platform team, cost reports per team

Lab: one service, every signal ​

Experiment 1: what does a label cost? (run) ​

bash
cd docs/snippets/system-design/observability-logs-metrics-traces/go
go run ./cmd/cardinality
text
design                                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 TB

Real 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) ​

bash
go test -race -count=1 -v ./obs
text
--- 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.134s

Experiment 3: run the server without a Collector (run) ​

bash
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/
text
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: 404

Real 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) ​

bash
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/heap
text
Type: 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.func2

Real 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) ​

bash
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_total
text
PASS  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"} 1

Expected, 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 ​

BeliefReality
Observability is having logs, metrics and tracesIt 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 p99Quantiles cannot be aggregated; sum histogram buckets, then histogram_quantile
Any label is fine on a metricEvery label combination is a series; unbounded labels cause cardinality explosions
Put trace_id on a metric to link it to tracesUse 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 errorsIt keeps 10% of errors; tail sampling keeps all of them
Tail sampling works on any Collector fleetAll spans of a trace must reach the same instance: route by trace id
Loki is a cheaper ElasticsearchLoki indexes labels only; full-text search is a scan
Telescope is a production monitorLaravel documents it for local development; use Pulse, Horizon and OpenTelemetry in production
Health checks should test every dependencyA failing liveness on a dependency outage restarts every pod and fixes nothing
Logging more is saferMore volume, more cost, more PII; log less, structured, with trace ids
Monitoring is obsoleteSymptom-based monitoring is still what pages; observability is what you use after the page

Cheat sheet ​

TopicWhat to remember
SignalsMetrics say what and how much, traces say where, logs say what exactly, profiles say which code
Join keytrace_id in logs, exemplars on metrics, span ids in profiles
LogsJSON, constant message, typed fields, levels, trace id by middleware, redact at source
Metric typesCounter _total, gauge, histogram (prefer native), summary only when you never aggregate
CardinalityProduct of label values; keep most metrics under 10 series; route templates, _OTHER, unmatched
PrometheusPull every 15-30 s, up, sample_limit, 15d local, remote write for long term
PromQLrate then sum by; histogram_quantile(0.99, sum by (le, ...) (rate(..._bucket[5m])))
Ruleslevel:metric:operations; dashboards and alerts read recorded series
MethodsRED per service, USE per resource, golden signals per user-facing system
TracesSERVER/CLIENT/PRODUCER/CONSUMER/INTERNAL; 5xx Error, 4xx Unset on server spans
Propagationtraceparent 00-trace-parent-flags; inject at every hop including jobs and messages
SamplingParentBased(TraceIDRatio) in SDK; tail in Collector with trace-id routing
OpenTelemetryAPI, SDK, OTLP 4317/4318, Collector receivers -> processors -> exporters
Profilingpprof on a private port; continuous with Pyroscope or Parca
LaravelContext + JSON Monolog + tap redaction, PromPHP with Redis, Pulse, Horizon horizon:snapshot, Telescope dev only, /up
CostDrop, sample, aggregate, downsample, tier; retention per signal; PII never logged

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
ObservabilityAbility to explain any internal state of a system from its outputs (term from control theory)
MonitoringCollecting predefined metrics and alerting on known conditions
Unknown unknownsFailure modes nobody predicted; observability's target
High cardinalityA field with very many distinct values (user id, trace id)
Cardinality explosionUncontrolled growth of metric series from unbounded label values
TelemetryData a system emits about itself: metrics, logs, traces, profiles
SignalOne kind of telemetry
Structured loggingLogs as typed key-value records, usually JSON
JSON logsOne JSON object per line
Log levelSeverity: debug, info, notice, warning, error, critical, alert, emergency
Correlation idAn id grouping related lines; best implemented as the trace id
Trace id16-byte id shared by every span of a trace
Span id8-byte id of one span
SamplingKeeping only a share of traces or logs
Log samplingDropping a share of low-value log lines
RedactionMasking or removing sensitive values before storage
PIIPersonally identifiable information
Fluent BitLightweight CNCF telemetry agent for logs, metrics, traces
VectorObservability pipeline tool for logs and metrics
LokiGrafana's log store indexing labels only
LogQLLoki's query language
ElasticsearchSearch engine with inverted indexes, used for logs (ELK)
OpenSearchApache-licensed fork of Elasticsearch and Kibana
ELKElasticsearch, Logstash, Kibana
ClickHouseColumnar SQL database used for logs, traces and metrics (ClickStack)
RetentionHow long data is kept
TTLTime to live; ClickHouse rule deleting rows after an interval
MetricA numeric measurement as a time series
Time seriesValues over time for one metric name and label set
CounterMonotonic cumulative metric, reset only on restart
GaugeMetric that can go up and down
HistogramObservations counted into buckets; aggregatable
Native histogramPrometheus sparse exponential histogram stored as one sample
SummaryClient-side quantiles; not aggregatable
BucketHistogram range with an inclusive upper bound le
LabelKey-value dimension of a metric
PrometheusPull-based metrics system and TSDB
Pull modelThe server scrapes targets
Scrape intervalHow often a target is scraped
Exposition formatPrometheus text format for /metrics
OpenMetricsStandardised exposition format with exemplars and # EOF
upSynthetic per-target series: 1 if the scrape succeeded
PushgatewayCache for metrics pushed by batch jobs
StatsDUDP push protocol and daemon for counters, timers, gauges
PromQLPrometheus query language
ratePromQL per-second increase of a counter over a range
histogram_quantilePromQL quantile estimate from histogram buckets
Recording rulePrecomputed PromQL stored as a new series
Remote writePrometheus pushing samples to another store
ThanosHA Prometheus with object-storage long-term retention
MimirGrafana's multi-tenant long-term Prometheus store
CortexCNCF multi-tenant Prometheus store, Mimir's ancestor
VictoriaMetricsTime series database compatible with Prometheus
RED methodRate, Errors, Duration per service
USE methodUtilization, Saturation, Errors per resource
Four golden signalsLatency, traffic, errors, saturation
SLIService level indicator: a user-centred measurement
TraceTree of spans for one request
SpanOne unit of work with timing, attributes, status
Parent spanThe span that caused a span; root has none
Span kindSERVER, CLIENT, PRODUCER, CONSUMER, INTERNAL
Span eventTimestamped annotation on a span, such as an exception
Span linkReference from a span to a span in another trace
Context propagationCarrying trace context across process boundaries
traceparentW3C header with version, trace id, parent id, flags
tracestateW3C header with vendor-specific trace data
BaggageW3C header carrying application key-values with the context
Head samplingDecision at the trace start
Tail samplingDecision after the trace is complete
OpenTelemetryVendor-neutral API, SDKs, Collector and OTLP
OTel SDKImplementation of the API: sampling, processing, export
Auto-instrumentationInstrumentation added without code changes
OTel CollectorAgent/gateway with receivers, processors, exporters
OTLPOpenTelemetry Protocol over gRPC (4317) or HTTP (4318)
ReceiverCollector component accepting data
ProcessorCollector component transforming data
ExporterComponent sending data to a backend
ConnectorCollector component joining two pipelines
JaegerCNCF tracing backend from Uber
TempoGrafana's object-storage trace backend
ZipkinDistributed tracing system from Twitter
HoneycombSaaS observability built on wide events
DatadogCommercial SaaS monitoring platform
New RelicCommercial SaaS observability platform with native OTLP ingest
Semantic conventionsStandard attribute and metric names
ExemplarExample trace reference attached to a metric sample
ProfilingSampling stacks to attribute resource use to code
pprofGo profile format and tool, net/http/pprof endpoints
Continuous profilingAlways-on low-overhead production profiling
PyroscopeGrafana's continuous profiling database
ParcaeBPF-based continuous profiler
GrafanaDashboard and exploration UI
Dashboard as codeDashboards generated and versioned in git
LGTMLoki, Grafana, Tempo, Mimir
PulseLaravel's first-party production dashboard
TelescopeLaravel's development debug assistant
HorizonLaravel's Redis queue dashboard and supervisor
promhttpGo package serving /metrics
slogGo's structured logging package log/slog
Health endpointURL for liveness/readiness checks (/up, /healthz, /readyz)
AlertingTurning symptoms into notifications; see the next chapter

References ​

Built by Morteza Negahi