Metrics, traces and logs from a real two-service system instrumented with OpenTelemetry: span waterfalls, traceparent propagation, correlated logs, histograms, sampling and a production Collector setup.
It's 3 a.m. and the alert says "checkout p99 latency above 2 seconds". To fix it, you need answers to three different questions. Is it really broken, and how badly? Where in the chain of services is the time going? What exactly happened in the requests that were slow? Each question needs a different kind of telemetry: metrics, traces and logs.
This tutorial explains the three pillars of observability, what each is good and bad at, and how OpenTelemetry (OTel), the vendor-neutral standard, ties them together. Everything is demonstrated on a real system: the two Flask services from Thinking Like a Systems Engineer, instrumented with the OpenTelemetry Python SDK (1.45). Every span, log line and metric shown here was produced by that code.
Monitoring answers questions you thought of in advance: "Is CPU above 90%?" "Is the error rate above 1%?" You build a dashboard and an alert for each one.
Observability is being able to answer questions you didn't think of in advance, from the outside, without shipping new code: "Why are only Android users in Brazil seeing slow checkouts since 14:05?" That requires telemetry rich enough to slice by any dimension, and connected well enough to follow one request across many services.
METRICS TRACES LOGS
"Is something wrong?" "Where is it wrong?" "What exactly happened?"
ββββββββββββββββββββ ββββββββββββββββββββββββββ ββββββββββββββββββββββββββ
numbers over time one request's path through timestamped events with
cheap, aggregated every service, with timings full detail
alerting, dashboards latency breakdown, deps debugging, auditing
alert fires βββΆ open an example trace βββΆ read the logs for that trace_id
The real power isn't in any single pillar. It's in jumping between them, and that only works if they share identifiers. That's what OpenTelemetry standardises.
OpenTelemetry is a CNCF project that defines one API, one SDK per language, and one wire protocol (OTLP) for traces, metrics and logs. You instrument your code once, then send the data to whatever backend you like: Jaeger, Grafana Tempo/Loki/Mimir, Prometheus, Datadog, Honeycomb, New Relic and many more.
ββββββββββββββββββ your service ββββββββββββββββββ
β your code βββΆ OTel API (tracer, meter, logger) β
β auto-instrumentation: Flask, requests, SQLβ¦ β
β β β
β βΌ β
β OTel SDK: sampling, batching, resource attrs β
ββββββββββββββββββββββ¬ββββββββββββββββββββββββββββ
β OTLP (gRPC :4317 / HTTP :4318)
βΌ
ββββββββββββββββββ OTel Collector βββββββββββββββββ
β receivers β processors (batch, filter, redact, β
β tail sampling) β exporters β
ββββββββ¬ββββββββββββββββββ¬βββββββββββββββββ¬ββββββββ
βΌ βΌ βΌ
traces backend metrics backend logs backend
(Jaeger/Tempo) (Prometheus) (Loki/Elastic)
| Piece | Role |
|---|---|
| API | What your code calls: tracer.start_as_current_span(), meter.create_counter(). Safe to use in libraries: it does nothing until an SDK is configured |
| SDK | The implementation: sampling, batching, exporting |
| Instrumentation libraries | Ready-made spans and metrics for Flask, Django, requests, gRPC, SQL drivers, Kafka⦠|
| OTLP | The standard protocol for sending telemetry |
| Collector | A separate process that receives, processes and forwards telemetry, so apps stay vendor-neutral |
| Semantic conventions | Standard attribute names (http.route, db.system, service.name) so every tool understands your data |
The setup is one function that configures all three signals for a service. For the lab, spans go to a JSON-lines file and metrics to an in-memory reader. Production setup appears later.
"""One place to configure traces, metrics and logs for a service."""
import json
import logging
from opentelemetry import metrics, trace
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
class JsonLinesSpanExporter(SpanExporter):
"""Write each finished span as one JSON line. In production: OTLPSpanExporter β a collector."""
def __init__(self, path):
self.file = open(path, "a")
def export(self, spans):
for span in spans:
self.file.write(span.to_json(indent=None) + "\n")
self.file.flush()
return SpanExportResult.SUCCESS
class TraceContextFilter(logging.Filter):
"""Stamp every log record with the current trace and span IDs."""
def filter(self, record):
ctx = trace.get_current_span().get_span_context()
record.trace_id = format(ctx.trace_id, "032x") if ctx.is_valid else "-"
record.span_id = format(ctx.span_id, "016x") if ctx.is_valid else "-"
return True
class JsonFormatter(logging.Formatter):
def __init__(self, service):
super().__init__()
self.service = service
def format(self, record):
return json.dumps({
"time": self.formatTime(record, "%H:%M:%S"), "level": record.levelname,
"service": self.service, "trace_id": record.trace_id, "span_id": record.span_id,
"msg": record.getMessage(), **getattr(record, "fields", {}),
})
def setup(service):
resource = Resource.create({"service.name": service, "deployment.environment": "lab"})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(SimpleSpanProcessor(JsonLinesSpanExporter(f"spans-{service}.jsonl")))
trace.set_tracer_provider(tracer_provider)
reader = InMemoryMetricReader()
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
handler = logging.FileHandler(f"logs-{service}.jsonl")
handler.setFormatter(JsonFormatter(service))
handler.addFilter(TraceContextFilter())
log = logging.getLogger(service)
log.setLevel(logging.INFO)
log.addHandler(handler)
return trace.get_tracer(service), metrics.get_meter(service), log, reader
Service A counts words and calls Service B over HTTPS. Two lines of auto-instrumentation give us server spans for incoming requests, and client spans plus context propagation for outgoing ones. Then we add one custom span and one custom metric:
from telemetry import setup
tracer, meter, log, reader = setup("service-a")
import requests
from flask import Flask, jsonify, request
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
app = Flask(__name__)
FlaskInstrumentor().instrument_app(app) # a server span for every incoming request
RequestsInstrumentor().instrument() # a client span + traceparent header for every outgoing call
SERVICE_B = "https://localhost:8443/store"
words_hist = meter.create_histogram("message.words", unit="{word}", description="Words per message")
@app.post("/message")
def message():
text = request.get_json().get("text", "")
with tracer.start_as_current_span("count_words") as span:
word_count = len(text.split())
span.set_attribute("message.word_count", word_count)
words_hist.record(word_count)
log.info("counted words", extra={"fields": {"word_count": word_count}})
r = requests.post(SERVICE_B, json={"text": text, "word_count": word_count}, verify="rootCA.crt", timeout=5)
if r.status_code >= 400:
log.warning("service-b rejected message", extra={"fields": {"status": r.status_code}})
return jsonify(r.json()), r.status_code
Service B validates the message and wraps the SQLite insert in its own span:
@app.post("/store")
def store():
log.info("received", extra={"fields": {"traceparent": request.headers.get("traceparent")}})
data = request.get_json()
if not data.get("text"):
log.warning("empty message rejected")
return jsonify({"error": "text must not be empty"}), 400
data["received_at"] = datetime.now(timezone.utc).isoformat()
with tracer.start_as_current_span("sqlite.insert") as span:
span.set_attribute("db.system", "sqlite")
span.set_attribute("db.operation.name", "INSERT")
try:
with db:
cur = db.execute("INSERT INTO messages (text, word_count, received_at) VALUES (?, ?, ?)",
(data["text"], data["word_count"], data["received_at"]))
except sqlite3.Error as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
raise
stored.add(1)
data["id"] = cur.lastrowid
return jsonify(data), 201
Then three requests: two normal ones and one with an empty message.
for t in "the quick brown fox" "hello world" ""; do
curl -s -X POST localhost:5000/message -H 'Content-Type: application/json' -d "{\"text\":\"$t\"}"; echo
done
{"id":1,"received_at":"2026-11-30T19:44:22.945692+00:00","text":"the quick brown fox","word_count":4}
{"id":2,"received_at":"2026-11-30T19:44:22.984296+00:00","text":"hello world","word_count":2}
{"error":"text must not be empty"}
A trace is the whole journey of one request. It's made of spans: named, timed operations with a parent, forming a tree. A small script reads both services' exported spans and draws each trace as a waterfall:
trace cb019ac4036d670d635da0571ddb22b9 (33.8 ms)
POST /message service-a 0.0 + 33.8 ms |ββββββββββββββββββββββββββββββββββββββββ|
count_words service-a 0.8 + 0.0 ms |β |
POST service-a 2.4 + 30.7 ms | ββββββββββββββββββββββββββββββββββββ |
POST /store service-b 8.0 + 13.4 ms | βββββββββββββββ |
sqlite.insert service-b 9.2 + 11.5 ms | βββββββββββββ |
trace f47afcf3e1a6cf6cc69bce45f5eba142 (17.5 ms)
POST /message service-a 0.0 + 17.5 ms |ββββββββββββββββββββββββββββββββββββββββ|
count_words service-a 0.5 + 0.0 ms | β |
POST service-a 1.2 + 15.7 ms | βββββββββββββββββββββββββββββββββββ | ERROR
POST /store service-b 4.6 + 0.8 ms | β |
This is exactly the view Jaeger or Grafana Tempo gives you, and it answers questions that no metric can:
count_words takes under 0.1 ms.sqlite.insert is 11.5 of B's 13.4 ms: the fsyncs of a commit (see How a Database Works Inside).POST) starts at 2.4 ms, but B's server span starts at 8.0 ms. The 5.6 ms between them is a new TCP connection and TLS handshake, because requests.post() without a Session doesn't reuse connections. There's a similar gap at the end. B's server span covers only the Flask handler: calling B directly with curl shows a time to first byte about 10 ms longer than the handler span. That's time spent inside B's web server but outside the instrumented code, in work such as finishing the TLS handshake (an strace shows it sending two session tickets), starting a thread for the request, parsing it, and writing the response. Uninstrumented time is where to look next.Here's one real span exported by Service B, for a request sent straight to B with curl (so it has no parent: it's the root span of its trace):
{
"name": "POST /store",
"context": {
"trace_id": "0xf1edb48d374691daebb0553b0c3164e5",
"span_id": "0x5b449dad862190ad",
"trace_state": "[]"
},
"kind": "SpanKind.SERVER",
"parent_id": null,
"start_time": "2026-11-30T19:44:40.300406Z",
"end_time": "2026-11-30T19:44:40.314630Z",
"status": {
"status_code": "UNSET"
},
"attributes": {
"http.method": "POST",
"http.server_name": "127.0.0.1",
"http.scheme": "https",
"net.host.name": "localhost:8443",
"http.host": "localhost:8443",
"net.host.port": 8443,
"http.target": "/store",
"net.peer.ip": "127.0.0.1",
"net.peer.port": 53232,
"http.user_agent": "curl/8.5.0",
"http.flavor": "1.1",
"http.route": "/store",
"http.status_code": 201
},
"events": [],
"links": [],
"resource": {
"attributes": {
"telemetry.sdk.language": "python",
"service.name": "service-b",
"deployment.environment": "lab"
},
"schema_url": ""
}
}
| Field | Meaning |
|---|---|
trace_id |
128-bit ID shared by every span in the request |
span_id, parent_id |
This span's ID and its parent's, which builds the tree |
kind |
SERVER (handling an incoming request), CLIENT (making an outgoing one), INTERNAL, PRODUCER, CONSUMER |
attributes |
Key-value details following semantic conventions: route, status, peer, DB system⦠|
events |
Timestamped points inside the span, for example a recorded exception |
status |
UNSET, OK or ERROR |
resource |
Who produced it: service name, version, environment, host, pod |
How did B's span know its parent was in A? A's requests instrumentation added a header to the outgoing call, and B's log line recorded it:
{"time": "20:44:22", "level": "INFO", "service": "service-b", "trace_id": "cb019ac4036d670d635da0571ddb22b9", "span_id": "7625302390d13775", "msg": "received", "traceparent": "00-cb019ac4036d670d635da0571ddb22b9-0051b2bc6a682289-03"}
That's the W3C Trace Context traceparent header, the standard every OTel SDK speaks:
traceparent: 00 - cb019ac4036d670d635da0571ddb22b9 - 0051b2bc6a682289 - 03
ββ ββββββββββββββββββββββββββββββββ ββββββββββββββββ ββ
version trace ID parent span ID flags
(A's client span) 01 = sampled
02 = trace ID is random
B's Flask instrumentation reads the header and starts its server span as a child of A's client span, with the same trace ID. The same mechanism works through gRPC metadata, Kafka message headers and AWS SQS attributes. Propagation breaks if any hop drops the header: a proxy that strips unknown headers, a hand-rolled HTTP client, or a message queue without instrumentation. A trace that suddenly "ends" at a service boundary usually means exactly that.
In the failed request, A's client span is marked ERROR but B's server span isn't. That's deliberate, from the semantic conventions: a 4xx response means the client made a bad request, so it's an error from the caller's point of view, but the server did its job correctly. A 5xx marks both sides as errors. That keeps server error rates meaningful: bots sending garbage shouldn't page the on-call engineer.
Traces and logs are per-request and expensive to store at high volume. Metrics are aggregated: one time series per combination of attribute values, no matter how much traffic there is. That makes them the right tool for dashboards and alerts.
After eight requests to A and five to B (B had been restarted), here's what the metric readers held, summarised:
[a] http.server.duration (ms) {'http.method': 'POST', 'http.status_code': 201, 'http.target': '/message'} count=7 sum=215 min=28 max=34
bounds=[0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 250.0]... counts=[0, 0, 0, 0, 7, 0, 0, 0, 0]
[a] http.server.duration (ms) {'http.method': 'POST', 'http.status_code': 400, 'http.target': '/message'} count=1 sum=18 min=18 max=18
[a] message.words ({word}) {} count=8 sum=21 min=0 max=8
bounds=[0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 250.0]... counts=[1, 6, 1, 0, 0, 0, 0, 0, 0]
[a] http.client.duration (ms) {'http.method': 'POST', 'http.status_code': 201} count=7 sum=198 min=26 max=30
[b] http.server.duration (ms) {'http.method': 'POST', 'http.status_code': 201, 'http.target': '/store'} count=5 sum=70 min=12 max=16
[b] messages.stored ({message}) {} value=5
The auto-instrumentation produced request-duration histograms, split by status code, for free. Our custom message.words histogram shows the distribution of message sizes, and messages.stored is a counter.
| Instrument | Use for | Example |
|---|---|---|
| Counter | Things that only go up | requests served, bytes sent, messages stored |
| UpDownCounter | Things that go up and down | active requests, queue length, open connections |
| Histogram | Distributions | request latency, payload size, words per message |
| Gauge (observable) | A value sampled at collection time | CPU temperature, cache size, memory in use |
The average latency of A's successful requests is 215 / 7 β 31 ms. An average hides everything that matters: if 99 requests take 10 ms and one takes 2 seconds, the average is 30 ms and looks healthy. Histograms keep counts per bucket (here, all seven fell in the 25β50 ms bucket), so backends can compute percentiles: p50, p95, p99. Alert on p99, not on the average. Tail latency is what your unhappiest users experience, and in a fan-out architecture almost every request hits someone's tail.
Every unique combination of attribute values creates a new time series. http.route = "/users/{id}" is fine. http.target = "/users/48213" creates one series per user, and that's how a metrics bill grows from Β£100 to Β£40,000. Rules of thumb:
Two simple methods cover most of what you need:
RED, for every service (request-driven work):
| Metric | From | |
|---|---|---|
| Rate | Requests per second | http.server.duration count |
| Errors | Failed requests per second (5xx) | count filtered by status |
| Duration | Latency distribution (p50/p95/p99) | http.server.duration histogram |
USE, for every resource (CPU, memory, disk, connection pools, queues):
| Question | |
|---|---|
| Utilisation | How busy is it? (% of time or capacity in use) |
| Saturation | How much work is waiting? (queue length, run queue) |
| Errors | Is it failing? (I/O errors, rejected connections) |
Then define SLOs (service level objectives) on the RED metrics that users feel, for example "99.9% of redirects under 100 ms over 30 days", and alert when you're burning through your error budget too fast, not on every spike.
At 10,000 requests per second, keeping every span is expensive. Sampling keeps a representative subset:
| Strategy | How | Trade-off |
|---|---|---|
| Head sampling | Decide at the first span (e.g. keep 10% of trace IDs); downstream services follow the sampled flag in traceparent |
Cheap and consistent, but it may drop the one slow trace you needed |
| Tail sampling | The Collector buffers whole traces and decides after they finish: keep all errors, all slow traces, and 1% of the rest | Keeps the interesting traces, but needs memory and a stateful collector |
Metrics are never sampled, so rates and percentiles stay accurate, which is another reason to alert on metrics and investigate with traces.
In production, replace the lab exporters with OTLP and batching, and set the service name through standard environment variables:
from opentelemetry import metrics, trace
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
resource = Resource.create() # reads OTEL_SERVICE_NAME and OTEL_RESOURCE_ATTRIBUTES
tp = TracerProvider(resource=resource, sampler=ParentBased(TraceIdRatioBased(0.1))) # keep 10%
tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) # endpoint from OTEL_EXPORTER_OTLP_ENDPOINT
trace.set_tracer_provider(tp)
metrics.set_meter_provider(MeterProvider(
resource=resource,
metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter(), export_interval_millis=15000)],
))
export OTEL_SERVICE_NAME=service-a
export OTEL_RESOURCE_ATTRIBUTES=service.version=1.4.2,deployment.environment=prod
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
Key differences from the lab: BatchSpanProcessor exports in the background, instead of writing synchronously on the request path as SimpleSpanProcessor does. The sampler respects the caller's decision (ParentBased). And everything goes to a Collector, which you configure like this:
receivers:
otlp:
protocols:
grpc: { endpoint: 0.0.0.0:4317 }
http: { endpoint: 0.0.0.0:4318 }
processors:
memory_limiter: { check_interval: 1s, limit_percentage: 80, spike_limit_percentage: 20 }
batch: {}
attributes/redact:
actions:
- { key: http.request.header.authorization, action: delete }
exporters:
otlp/tempo: { endpoint: tempo:4317, tls: { insecure: true } }
prometheusremotewrite: { endpoint: http://mimir:9009/api/v1/push }
otlphttp/loki: { endpoint: http://loki:3100/otlp }
service:
pipelines:
traces: { receivers: [otlp], processors: [memory_limiter, attributes/redact, batch], exporters: [otlp/tempo] }
metrics: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [prometheusremotewrite] }
logs: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/loki] }
Python also has zero-code instrumentation: install opentelemetry-distro, run opentelemetry-bootstrap -a install to add instrumentations for your libraries, then start the app with opentelemetry-instrument python app.py. It's the fastest way to get the auto-instrumented spans and metrics shown above, and you can add custom spans later where the business logic needs them.
1. METRIC Alert: p99 of POST /message > 500 ms for 10 minutes (error budget burning)
β dashboard: only status 201, started 14:05, all regions
βΌ
2. TRACE Open an exemplar trace from the slow bucket:
POST /message 812 ms
ββ POST /store 790 ms
ββ sqlite.insert 771 ms β here
βΌ
3. LOGS Search trace_id = β¦ in service-b logs:
"database is locked; retrying" (a backup job started at 14:04)
βΌ
4. FIX Move the backup off-peak / use WAL mode; watch the p99 recover on the same dashboard
Metrics told you that something was wrong and when. The trace told you where. The logs told you why. Each signal is limited on its own. Correlated by trace ID, they let you find a cause in minutes instead of hours.
The one idea to keep: instrument once with OpenTelemetry, propagate context across every hop, put the trace ID in every log line, and keep metrics low-cardinality. Then any alert can be followed down to the exact request and line that explains it.