About Skills Projects Blog Contact View my CV ↗ Español
OpenTelemetry + Grafana hands-on: end-to-end observability that actually works

OpenTelemetry + Grafana hands-on: end-to-end observability that actually works

Hands-on OpenTelemetry and Grafana guide: signals, Collector, Python and Go instrumentation, Tempo/Loki/Mimir, queries, alerts, and cost.

By Omar Flores
Table of Contents

It is two in the morning and a customer says their payment takes eight seconds. You open the dashboard: p99 is green. You open the logs: there is a timeout, but it does not say which service. You open the traces: the transaction disappears at a hop that neither of the other tools mentions. You have three sources of truth and none of them is telling the same story.

That is the problem OpenTelemetry solves. It does not sell you another backend: it defines a common language so your application emits traces, metrics, and logs with the same context, and so any tool can read them. Grafana is where those signals come together and become an answerable question.

This guide is hands-on. We spin up a full stack in one container, instrument Python and Go, configure the Collector, and write the queries people actually use during an incident.


What OpenTelemetry is and what problem it solves

OpenTelemetry is a CNCF project born from the merger of OpenTracing and OpenCensus. Its goal is to keep instrumentation independent from the backend you pick today. It is a framework and toolkit for generating, exporting, and collecting telemetry; it is not an observability backend.

The piece people usually confuse is OTLP. OpenTelemetry defines the protocol, the SDKs, and the semantic conventions; OTLP is the format and transport those SDKs use to talk to a Collector or a backend. If your application speaks OTLP, you can swap Tempo for Jaeger, or Mimir for another Prometheus-compatible store, without rewriting instrumentation.

Semantic conventions are the naming contract. service.name, service.version, deployment.environment.name, http.request.method, http.response.status_code, db.system. If two services call the same thing by different names, the dashboards lie even when the data exists. The key rule: service.name must be unique, stable, and known to the whole team.


Traces, metrics, and logs: three signals, one story

A trace tells the journey of a request. A span is one operation inside that journey: an HTTP call, a database query, a payment provider call. Spans share a trace_id, carry their own span_id, and point to a parent_id that builds the tree.

A metric counts how often something happens and at what magnitude. A counter accumulates, a gauge represents an instant value, and a histogram spreads durations across buckets. Metrics are cheap to query and expensive to explain: they tell you p95 went up, not why.

A log records an event with detail. It is the most expensive signal to store. Its value multiplies when it carries the trace_id and span_id from context, because then you can jump from the log to the trace without guessing.

flowchart LR
    A[Python or Go app] -->|OTLP| C[Collector]
    C --> T[Tempo: traces]
    C --> L[Loki: logs]
    C --> M[Mimir: metrics]
    G[Grafana] --> T
    G --> L
    G --> M

The three connect through trace context in logs and exemplars in metrics. Without jumping between signals, you have three tools, not observability.


The Collector: the missing glue

The Collector receives telemetry, processes it, and exports it. It has receivers, processors, exporters, and connectors; pipelines are declared under service. Why not export directly from the application? Because the Collector gives you retries, batching, memory limits, redaction, and sampling without touching code, and it decouples you from the backend.

A detail that causes half the support tickets: OTLP gRPC listens on 4317 and OTLP HTTP on 4318. They are not interchangeable.

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

processors:
  memory_limiter:
    check_interval: 1s
    limit_mib: 512
  batch:
    send_batch_size: 8192
    timeout: 5s

exporters:
  debug:
    verbosity: basic

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [debug]
    metrics:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [debug]
    logs:
      receivers: [otlp]
      processors: [memory_limiter, batch]
      exporters: [debug]

memory_limiter goes first: if the Collector runs out of memory, it rejects data instead of dying. batch groups data to reduce connections and improve compression. debug verifies data is arriving; in production you replace it with real exporters.


A full stack in one container

For the lab you do not need to wire five services by hand. Grafana publishes grafana/otel-lgtm, an image that bundles the Collector, Grafana, Tempo, Loki, Prometheus, and Pyroscope. Do not put it in front of customers.

docker run -d --name otel-lgtm \
  -p 3000:3000 -p 4317:4317 -p 4318:4318 \
  grafana/otel-lgtm

Open http://localhost:3000 with admin / admin. Under Explore you get the three datasources: Tempo for TraceQL, Loki for LogQL, and Prometheus for PromQL.

In production, the equivalent is usually Grafana Alloy or the Collector as an agent on every node, plus a gateway that writes to Tempo, Loki, and Mimir. Mimir is the natural replacement for Prometheus when you need scale and multi-tenancy. The OTLP contract is the same in the lab and in production: what you instrument today is not thrown away tomorrow.


Python instrumentation without touching the code

Python has one of the smoothest OpenTelemetry stories: automatic instrumentation for Flask, FastAPI, Django, SQLAlchemy, and a long list of libraries. opentelemetry-distro ships the opentelemetry-instrument agent and the opentelemetry-bootstrap command, which detects your dependencies and installs the matching instrumentation.

python -m venv .venv
source .venv/bin/activate
pip install flask opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install

With the lab Collector running, export over HTTP so you do not depend on gRPC:

export OTEL_SERVICE_NAME=checkout-api
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=staging
opentelemetry-instrument flask run -p 5000

OTEL_SERVICE_NAME feeds service.name. OTEL_RESOURCE_ATTRIBUTES adds resource attributes to every signal; that is where you put environment, version, and team.

Automatic instrumentation covers the edges: inbound requests, outbound calls, queries. For the core of your business logic you need manual spans:

from opentelemetry import trace

tracer = trace.get_tracer("checkout")


def charge(order):
    with tracer.start_as_current_span("payment.charge") as span:
        span.set_attribute("payment.provider", "stripe")
        span.set_attribute("order.item_count", len(order.items))

        try:
            return provider.charge(order)
        except Exception as exc:
            span.record_exception(exc)
            span.set_status(trace.Status(trace.StatusCode.ERROR, str(exc)))
            raise

start_as_current_span makes the span the parent of everything that happens inside. record_exception adds an event with the stack trace; set_status marks the span as failed so Tempo can find it. Do not put the customer email or card number in attributes; that is a privacy incident with a trace_id attached.


Go instrumentation with real control

Go has no agent magic, and that is good: you see exactly what is created and when it closes. You need the SDK, the OTLP exporter, and the net/http instrumentation.

go get go.opentelemetry.io/otel \
  go.opentelemetry.io/otel/sdk \
  go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc \
  go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp

The following fragment configures the TracerProvider and instruments the server. The exporter reads OTEL_EXPORTER_OTLP_ENDPOINT; if it is absent, it uses localhost:4317.

func newTracerProvider(ctx context.Context) (*sdktrace.TracerProvider, error) {
	exporter, err := otlptracegrpc.New(ctx)
	if err != nil {
		return nil, err
	}

	res, err := resource.Merge(
		resource.Default(),
		resource.NewSchemaless(
			attribute.String("service.name", "checkout-api"),
			attribute.String("deployment.environment.name", "production"),
		),
	)
	if err != nil {
		return nil, err
	}

	return sdktrace.NewTracerProvider(
		sdktrace.WithBatcher(exporter, sdktrace.WithBatchTimeout(5*time.Second)),
		sdktrace.WithResource(res),
	), nil
}

func checkoutHandler(w http.ResponseWriter, r *http.Request) {
	ctx, span := otel.Tracer("checkout").Start(r.Context(), "payment.charge")
	defer span.End()

	span.SetAttributes(attribute.String("payment.provider", "stripe"))

	if err := charge(ctx); err != nil {
		span.RecordError(err)
		span.SetStatus(codes.Error, err.Error())
		http.Error(w, "payment failed", http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusAccepted)
}

Three things people forget. defer span.End() is not optional: an unclosed span is never exported. tp.Shutdown with a timeout flushes the batch when the process exits; without it, the last spans are lost during a deploy. And otelhttp.NewHandler(mux, "checkout-api") creates server spans and HTTP metrics, but knows nothing about your business logic.


Sampling and span metrics

The minimal Collector does not survive production. These two blocks deliver the most value per line: tail sampling so you do not store every trace, and the span_metrics connector so spans generate RED metrics.

processors:
  tail_sampling:
    decision_wait: 10s
    num_traces: 100000
    policies:
      - name: errors
        type: status_code
        status_code:
          status_codes: [ERROR]
      - name: slow
        type: latency
        latency:
          threshold_ms: 500
      - name: baseline
        type: probabilistic
        probabilistic:
          sampling_percentage: 5

connectors:
  span_metrics:
    dimensions:
      - name: http.request.method
      - name: http.response.status_code
      - name: http.route
    metrics_flush_interval: 15s

tail_sampling decides after seeing the complete trace, so it keeps every error and only a percentage of normal traffic. Policies combine with OR: if a trace matches errors or slow, it stays. decision_wait and num_traces define how much buffer the Collector holds.

The architectural trap: every span in a trace must reach the same Collector. If you run three replicas behind a service load balancer, each one sees a fragment and the decision is wrong. You need a load-balancing layer keyed by trace_id in front of the sampling tier, or a single Collector with enough memory.

The span_metrics connector produces traces.span.metrics.calls and traces.span.metrics.duration from spans. Watch cardinality: http.route is a good attribute; http.url with user IDs is a bomb.


Tempo, Loki, and Mimir: queries that answer

Tempo stores traces and queries them with TraceQL. Loki indexes labels and filters the body with LogQL. Mimir is Prometheus-compatible, accepts OTLP, and applies PromQL. In Mimir, service.name maps to the job label by default; if you come from OTel dashboards, check that difference before copying a query.

All three accept OTLP. Tempo listens on 4317/4318; Loki receives at /otlp/v1/logs and Mimir at /otlp/v1/metrics; the exporter uses /otlp as the base:

exporters:
  otlphttp/tempo:
    endpoint: http://tempo:4318
  otlphttp/loki:
    endpoint: http://loki:3100/otlp
  otlphttp/mimir:
    endpoint: http://mimir:9009/otlp

In Tempo, to see errors from one service:

{ resource.service.name = "checkout-api" && status = error }

To find slow traces and see whether time is spent in the database, combine the duration filter with the descendant operator:

{ resource.service.name = "checkout-api" && trace:duration > 2s }
{ resource.service.name = "checkout-api" } >> { span.db.system = "postgresql" && span:duration > 100ms }

trace:duration measures the whole trace; span:duration measures one operation. Confusing them is the number one cause of percentiles that do not add up.

In Loki, the service label arrives as service_name because Loki normalizes dots to underscores:

{service_name="checkout-api"} |= "payment" |= "error"

In Mimir, p95 HTTP latency from the metrics otelhttp generates:

histogram_quantile(0.95,
  sum by (le) (
    rate(http_server_request_duration_seconds_bucket{job="checkout-api"}[5m])
  )
)

And the 5xx error rate:

sum(rate(http_server_request_duration_seconds_count{job="checkout-api", http_response_status_code=~"5.."}[5m]))
/
sum(rate(http_server_request_duration_seconds_count{job="checkout-api"}[5m]))

Metrics tell you if there is a problem; traces tell you where; logs tell you what.


Alerts that don’t wake the wrong people

A good alert fires on a symptom the user feels, has a threshold that survives noise, and links to a runbook.

In Grafana, a managed alert combines queries, an expression, and a condition. For checkout, the condition would be a 5xx rate above 5% for 10 minutes, plus a second rule for p95 above one second. for: 10m prevents a one-minute spike from waking the whole team.

Do not alert on CPU at 80%. Alert on latency, errors, and queue saturation that affects users. CPU is a cause; the symptom is the payment that never finishes.

Grafana Alerting can query multiple datasources in one rule: PromQL for the rate, LogQL for the error pattern, and an annotation with the dashboard and runbook.

Also configure NoData and Error explicitly. If the Collector stops exporting, a misconfigured rule can stay green forever.


Performance, common mistakes, and a checklist

Observability gets expensive when you instrument without judgment. These are the mistakes I see most:

  • Confusing 4317 with 4318. The SDK sends gRPC to an HTTP port and the Collector receives nothing.
  • Putting batch before tail_sampling. Sampling needs the complete trace; keep batch at the end.
  • Uncontrolled cardinality. user.id, request.id, or the full URL create millions of series.
  • Sampling before generating span metrics. If you drop traces first, RED metrics are biased.
  • PII in attributes. An email in a span is personal data traveling to three backends.

For performance: use compression (gzip or zstd), raise send_batch_size carefully, size the exporter queue, and measure the Collector itself.

  • service.name, service.version, and deployment.environment.name are defined and consistent.
  • Sampling is a documented decision: head, tail, or none.
  • Span metrics are generated before traces are dropped.
  • Tempo, Loki, and Mimir have different, justified retention per signal.
  • Logs carry trace_id and span_id; exemplars are enabled.
  • Alerts fire on symptoms, with for and a runbook.

You do not instrument to fill a dashboard. You instrument so that, at two in the morning, the system tells you where to look.