The OTel Collector: receivers, processors, exporters, pipelines
The process between your services and your backends: where telemetry is batched, scrubbed, sampled, routed and, if you configure it wrong, silently dropped
A Collector has one traces pipeline: receivers [otlp], processors [memory_limiter, batch], exporters [otlp/tempo, otlp/vendor]. The vendor endpoint goes down and its exporter's retry queue fills. What happens to spans going to Tempo?
The OpenTelemetry Collector is a single Go binary that receives telemetry, processes it, and sends it on. It does not store anything for long. It is a router with opinions, configured in YAML, and it is the component that turns “every service exports to Datadog” into “every service exports OTLP to a local address, and the platform team decides what happens next”.
Why a Collector at all
You can export from the SDK straight to a backend; the previous chapter did. It works until one of these is true.
- You want to change backends. Without a Collector, every service carries the vendor’s endpoint and API key in its configuration. Changing vendors, or adding a second one for a migration, is a redeploy of every service. With a Collector, services send OTLP to one address and the vendor is an exporter setting.
- You need to scrub data. PII in attributes, auth headers, query strings with tokens. Fixing it in each service takes a release; fixing it in the pipeline takes a config reload and applies to every service, including the one you did not know about.
- You need to drop noise. Health checks, readiness probes, synthetic monitors, debug-level logs from one chatty service. Every one you drop at the Collector is one you do not pay to store.
- You need tail sampling. Keeping all errors and slow traces while sampling the rest requires seeing every span of a trace before deciding. The SDK in one service cannot do that; a Collector that receives all spans can.
- You need to protect the application. The SDK’s batch processor holds 2048 spans and drops on overflow. A Collector on the same host accepts quickly over localhost, holds a bigger queue, and absorbs a backend outage without the application noticing.
- You need enrichment. Kubernetes pod, namespace, node and deployment names are known to the platform, not to the code. The Collector adds them.
The costs are real too: one more thing to run, monitor and upgrade; an extra network hop of latency for telemetry; and a single place where a bad config drops everything for everyone.
The pipeline model
A Collector config has five top-level sections and the fifth is the one that matters.
receivers: # how data gets in
otlp:
protocols:
grpc: { endpoint: 0.0.0.0:4317 }
http: { endpoint: 0.0.0.0:4318 }
processors: # what happens to it
memory_limiter: { check_interval: 1s, limit_mib: 400, spike_limit_mib: 100 }
batch: {}
exporters: # where it goes
otlp/tempo:
endpoint: tempo:4317
tls: { insecure: true }
connectors: {} # pipelines feeding pipelines
extensions: # health check, pprof, zpages, auth
health_check: {}
service: # what is actually switched on
extensions: [health_check]
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
Defining a component does nothing. A receiver, processor or exporter is active only when a pipeline in service.pipelines lists it. This is the first thing to check when a config change appears to have no effect.
Component ids are type[/name]: otlp and otlp/tempo are both the OTLP exporter type with different configurations. You can define as many instances of a type as you like.
Each pipeline handles one signal: traces, metrics or logs (and you can have several per signal, named traces/sampled, logs/audit). The pipeline mechanics have three rules worth memorising:
- One receiver can feed several pipelines. The Collector creates a single receiver instance and fans data out to the first processor of each pipeline. The call is synchronous: if one pipeline’s first processor blocks, the others attached to that receiver block too.
- Processors are never shared. Listing
batchin two pipelines creates two independent instances with their own state. Order within a pipeline is the order of the list, and order matters. - Exporters fan out. The last processor sends each batch to every exporter in the pipeline, and each exporter gets its own copy. Several pipelines can share an exporter instance.
Connectors join pipelines: a connector is an exporter at the end of one pipeline and a receiver at the start of another. The spanmetrics connector reads spans and emits RED metrics into a metrics pipeline; the routing connector sends data to different pipelines by attribute; the forward connector chains pipelines so you can apply common processing once and branch afterwards.
Processors you will use
Processor order in a pipeline follows one principle: refuse early, drop early, batch late.
memory_limiter goes first. Every check_interval (set it to 1s; the default is 0s, which disables checking) it measures heap use. Above the soft limit, which is limit_mib minus spike_limit_mib (default 20% of the limit), it refuses incoming data with a retryable error, so OTLP clients back off and retry instead of the Collector being OOM-killed. Above the hard limit it also forces a garbage collection. In a container, use limit_percentage: 80 and spike_limit_percentage: 20 so the limit tracks the cgroup. Placed anywhere but first, it cannot push back on the receiver, and refused data is lost instead of retried.
batch goes last, after anything that drops. It sends a batch when it reaches send_batch_size (default 8192 items) or after timeout (default 200 ms), whichever comes first; send_batch_max_size (default 0, unlimited) caps a batch for backends with request-size limits. Batching cuts export requests by two or three orders of magnitude and compresses far better. The project docs state it should come after memory_limiter and any sampling processors. Recent Collector versions are moving batching into the exporters’ own sending queue, but the processor remains the common pattern.
attributes inserts, updates, upserts, deletes, hashes, extracts or converts attributes on spans, log records and metric data points. Actions take a key or a pattern (a regex over attribute names, for delete and hash). hash replaces the value with its SHA-256, which keeps a field joinable without exposing it. include and exclude blocks with match_type: strict or regexp restrict it to certain services or span names. The README now says it is superseded by transform, but for straight deletes and hashes it is the clearest config you can write.
resource does the same actions on resource attributes: add deployment.environment.name for everything from this cluster, delete process.command_line because it contains secrets.
filter drops data that matches OTTL conditions. Any matching condition drops the item. From Collector v0.146.0 the config keys are trace_conditions, metric_conditions and log_conditions, with path prefixes (span.attributes, resource.attributes, log.body); earlier versions use the now-deprecated nested form traces: { span: [...] } with unprefixed paths, which newer versions still accept. Dropping a parent span orphans its children, so filter on spans that have none, such as health-check server spans, or drop at the SDK with an excluded-URLs setting instead.
transform runs OTTL statements: set, delete_key, keep_keys, replace_pattern, truncate_all, limit, with where clauses. It is the general-purpose tool: redact a credit card pattern from a log body (replace_pattern(log.body, "\\b\\d{13,16}\\b", "****")), rename an attribute during a semantic-convention migration, cap attribute values at 4096 bytes with truncate_all(span.attributes, 4096). error_mode: ignore (the default) logs a failing statement and carries on; propagate drops the payload.
tail_sampling buffers spans by trace id for decision_wait (default 30 s), holding up to num_traces (default 50 000) traces in memory, then applies policies: status_code to keep errors, latency to keep slow traces, probabilistic for a baseline, string_attribute and numeric_attribute for VIP tenants, rate_limiting, and and/composite to combine them. Memory is roughly spans per second times decision wait times span size: 20 000 spans per second for 30 s at 1 KB each is 600 MB. It needs every span of a trace in the same Collector instance, which is why it sits behind a loadbalancing exporter that routes by trace id. The sampling chapter covers what it hides.
k8sattributes looks up the pod that sent the data (by connection IP or a pod-ip resource attribute) and adds k8s.namespace.name, k8s.pod.name, k8s.pod.uid, k8s.pod.start_time, k8s.deployment.name and k8s.node.name. It needs RBAC: get, watch and list on pods and namespaces, plus replicasets for deployment names. In the agent pattern, run it with a node filter so each agent watches only its own node’s pods.
Exporters
otlp (gRPC) and otlphttp cover most backends today: Tempo, Jaeger, Loki’s OTLP endpoint (http://loki:3100/otlp; Grafana’s docs say Collector log ingestion into Loki must use otlphttp), Mimir and every commercial vendor. prometheus exposes a scrape endpoint; prometheusremotewrite pushes. debug prints telemetry to the Collector’s own log, with verbosity: basic (the default: counts only), normal or detailed (every attribute), and sampling_initial / sampling_thereafter to keep it from flooding; it replaced the older logging exporter, which was removed in v0.111.0. file writes JSON lines, and the loadbalancing exporter routes by trace id or service name to a tier of downstream Collectors.
Most exporters share a common helper with a sending_queue (in memory by default, optionally persisted to disk through the file_storage extension so a restart does not lose the queue) and retry_on_failure with exponential backoff. Those two settings decide what happens during a backend outage: queue capacity divided by your item rate is how long you can survive, after which new data is dropped and counted.
Agent and gateway
Two patterns, usually combined.
An agent Collector runs beside the workload: a sidecar container, a Kubernetes DaemonSet, a systemd unit on a VM. Applications export to localhost:4317, which is fast and almost never fails, so the SDK’s small queue never fills. The agent adds host and Kubernetes metadata, scrapes local metrics and tails log files. It keeps processing light because it shares the node’s resources with the workload.
A gateway is a central pool of Collectors behind a load balancer. The project docs list its benefits as separation of concerns such as centrally managed credentials and centralised policy management such as filtering and sampling, and its costs as one more thing that can fail, added latency in cascades, and higher resource use. Tail sampling and span-derived metrics need state per trace or per service, so a gateway that does them is two tiers: a stateless first tier with the loadbalancing exporter, routing by traceID, and a stateful second tier with tail_sampling.
The common production shape is SDK to agent on the node, agent to gateway, gateway to backends. Small setups, including the lab, run one Collector that plays both roles.
Watching the Collector
A Collector that drops data looks exactly like a quiet system. You find out only from its own telemetry. It exposes Prometheus metrics on port 8888 (configured under service.telemetry.metrics, with level set to none, basic, normal (default) or detailed). The ones that tell you about loss:
| metric | meaning | alert when |
|---|---|---|
otelcol_receiver_accepted_spans |
spans in | it drops to zero for a pipeline that should have traffic |
otelcol_receiver_refused_spans |
refused by memory_limiter back-pressure | any sustained rate |
otelcol_exporter_sent_spans |
spans out, per exporter | it diverges from accepted minus filtered |
otelcol_exporter_send_failed_spans |
spans the exporter gave up on | any sustained rate |
otelcol_exporter_queue_size / _queue_capacity |
sending queue fill | above 60 to 70% (the scaling guide’s threshold) |
The same set exists for _metric_points and _log_records. The health_check extension serves liveness on port 13133 (default localhost:13133, so set endpoint: 0.0.0.0:13133 for a Kubernetes probe). The zpages extension serves live pipeline and span debugging pages on port 55679 (default localhost:55679). And the observing-the-platform chapter in module four is about the uncomfortable fact that the Collector’s metrics usually travel through the Collector.
Distributions: core, contrib and your own
The otelcol (core) distribution contains the OTLP receiver and exporters, batch, memory_limiter, debug and a few others: enough to forward. Almost everything in this chapter beyond those, including attributes, filter, transform, tail_sampling, k8sattributes, the Prometheus and Loki components and the health_check extension, lives in opentelemetry-collector-contrib and ships in the otelcol-contrib distribution. There are also otelcol-k8s and otelcol-otlp distributions with curated subsets. Contrib is convenient and large, with hundreds of components and a correspondingly large attack surface and binary. For production, the OpenTelemetry Collector Builder (ocb) builds a binary from a manifest listing exactly the components you use. Component stability varies, from development through alpha and beta to stable, and is printed at the top of each component’s README; attributes is beta and debug and health_check are alpha at the time of writing, so read the README of the version you run.
You will edit labs/observability/otel/collector.yaml to delete a PII attribute, drop health-check spans, and fan traces out to a second exporter, then prove each change in Tempo and in the Collector’s own logs.
1. Find the Collector and read its config.
cd labs/observability
OTEL_SDK_DISABLED=false OTEL_SEMCONV_STABILITY_OPT_IN=http/dup docker compose --profile telemetry up -d
IMG=otel/opentelemetry-collector-contrib:0.123.0 # the image compose.yaml pins for the otel-collector service
docker run --rm "$IMG" --version
sed -n '/^service:/,$p' otel/collector.yamlotelcol-contrib version 0.123.0 (contrib, because the stack uses contrib components; the compose service is otel-collector), then the service section: the Collector’s own metrics on port 8888, a traces pipeline exporting to otlp/tempo, a metrics pipeline exporting to prometheus and a logs pipeline exporting to otlphttp/loki, each with only the batch processor. The version decides which filter syntax you use in step 4.2. Send a span with PII and a health-check span, and see both arrive. The lab’s payments service leaks the card-holder name only into its logs, as the field card_holder (with FAULT_LEAK_PII=1; the O2 project scrubs that). Here you put the same key on a span yourself. Save as pii.py:
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.trace import SpanKind
tp = TracerProvider(resource=Resource.create({"service.name": "pii-test"}))
tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4317", insecure=True)))
tracer = tp.get_tracer("lab.pii")
with tracer.start_as_current_span("POST /charge", kind=SpanKind.SERVER, attributes={
"http.request.method": "POST", "url.path": "/charge",
"card_holder": "Ada Lovelace", "enduser.id": "ada@example.com", "order.id": 42}):
pass
with tracer.start_as_current_span("GET /health", kind=SpanKind.SERVER, attributes={
"http.request.method": "GET", "url.path": "/health", "http.target": "/health"}):
pass
tp.shutdown()python3 pii.py && sleep 8
curl -G -s http://localhost:3200/api/search --data-urlencode 'q={ resource.service.name = "pii-test" }' \
| jq -r '.traces[] | .rootTraceName'
curl -G -s http://localhost:3200/api/search --data-urlencode 'q={ span.card_holder != "" }' | jq '.traces | length'POST /charge and GET /health, and a count of at least 1: the card-holder name is searchable in your tracing backend. That is the incident from the top of the chapter, reproduced in one line of Python.3. Delete the PII attributes. Add an attributes processor under processors: in otel/collector.yaml:
attributes/scrub:
actions:
- key: card_holder
action: delete
- key: enduser.id
action: hash
- pattern: ^http\.request\.header\.(authorization|cookie)$
action: deleteenduser.id is hashed rather than deleted, so you can still count distinct users and join across spans without storing the address.
4. Drop health-check spans. Add a filter processor. The lab pins Collector 0.123.0, which uses this form:
filter/health:
error_mode: ignore
traces:
span:
- IsMatch(attributes["url.path"], "^/(health|healthz|ready|livez)$")
- IsMatch(attributes["http.target"], "^/(health|healthz|ready|livez)$")From v0.146.0 the same filter is written with trace_conditions and prefixed paths, and the form above becomes deprecated but still accepted:
filter/health:
error_mode: ignore
trace_conditions:
- IsMatch(span.attributes["url.path"], "^/(health|healthz|ready|livez)$")
- IsMatch(span.attributes["http.target"], "^/(health|healthz|ready|livez)$")Both conditions are there because services on the old HTTP conventions send http.target and services on the stable ones send url.path; in dual mode they send both, and either match drops the span.
IsMatch on a nil value is false rather than an error, so spans without the attribute pass through.5. Turn up the debug exporter and wire everything into the traces pipeline. The lab’s config already defines debug under exporters: with verbosity: basic, and no pipeline uses it. Change that block to:
debug:
verbosity: detailed
sampling_initial: 5
sampling_thereafter: 50Then edit the traces pipeline: the new processors, then batch last. The lab’s config defines no memory_limiter, so do not list one (the O2 project adds it):
traces:
receivers: [otlp]
processors: [filter/health, attributes/scrub, batch]
exporters: [otlp/tempo, debug]Validate before you restart, using the same image:
docker run --rm -v "$PWD/otel/collector.yaml:/c.yaml:ro" "$IMG" validate --config=/c.yaml && echo VALID
docker compose restart otel-collector
docker compose logs --since 30s otel-collector | grep -iE 'error|everything is ready|started' | tail -5VALID, then a startup line such as Everything is ready. Begin running and processing data. The config is bind-mounted read-only from otel/collector.yaml, so a restart picks it up. A typo in a processor name fails validation with the unknown component id, and listing a processor the file never defines (a pipeline that names memory_limiter when there is no memory_limiter: block, for example) fails with a reference to an undefined component; both are better found here than in a crash loop.6. Prove it.
python3 pii.py && sleep 8
curl -G -s http://localhost:3200/api/search --data-urlencode 'q={ resource.service.name = "pii-test" }' --data-urlencode 'start='$(( $(date +%s) - 60 )) --data-urlencode 'end='$(date +%s) \
| jq -r '.traces[] | .rootTraceName'
TID=$(curl -G -s http://localhost:3200/api/search --data-urlencode 'q={ resource.service.name = "pii-test" && name = "POST /charge" }' --data-urlencode 'limit=1' | jq -r '.traces[0].traceID')
curl -s "http://localhost:3200/api/v2/traces/$TID" | jq -r '.. | objects | select(.key? == "enduser.id" or .key? == "card_holder") | "\(.key)=\(.value.stringValue)"'
docker compose logs --since 30s otel-collector | grep -E 'card_holder|enduser.id|Name +: ' | headPOST /charge for the last minute: the health-check span was dropped. The attribute dump shows enduser.id= followed by a 64-character hex string and no card_holder at all. The Collector’s own log, written by the debug exporter, shows the same span with Name : POST /charge and the hashed enduser.id, and no health-check span: the debug exporter receives what the processors left, which makes it the cheapest way to see what your backends see. Fan-out worked: one batch, two exporters, two copies.7. Read the Collector’s self-metrics. Compose publishes the Collector’s metrics port, 8888, on the host (Prometheus also scrapes it as the otel-collector-internal job):
curl -s localhost:8888/metrics \
| grep -E '^otelcol_(receiver_accepted_spans|exporter_sent_spans|exporter_send_failed_spans|processor_(incoming|outgoing)_items)' | head -20otlp receiver (this Collector release adds a _total suffix to the counter names), and sent spans for each of otlp/tempo and debug with the same count, because each exporter receives a full copy. Processor incoming and outgoing item counts differ for filter/health by the number of health-check spans dropped. send_failed should be zero or absent.batch to the front of the processor list and memory_limiter to the end, then run the loadgen at LOADGEN_RPS=200 with a memory_limiter defined with a low limit (check_interval: 1s, limit_mib: 64). Validation still passes: the Collector does not enforce ordering. Under load, batch accumulates before the limiter sees anything, the limiter refuses data it can no longer push back to the receiver, and otelcol_receiver_refused_spans stays at zero while traces in Tempo go missing; with luck the container is OOM-killed instead, which at least shows up. Then remove filter/health from the pipeline but leave its definition in place: the config is valid, no error is logged, and health checks are back in Tempo. Both failures are silent, which is why the self-metrics in step 7 belong on a dashboard with alerts. Put the pipeline back to its step 5 form and the load back with docker compose up -d loadgen. The step 3 to 5 changes can stay or go: no later chapter depends on them, and the O2 project starts again from the original file.You run 40 services on one Kubernetes cluster, about 15 000 spans per second at peak, exporting straight from SDKs to a commercial vendor. Legal wants a guarantee that card-holder names never leave the cluster, and finance wants to keep 100% of error traces but only 10% of the rest. What Collector topology do you deploy?
- DOC Collector architecture
How pipelines, fan-out consumers and shared receivers actually work, including the warning that a blocking processor blocks every pipeline on the same receiver. Read the pipelines section; skip the extension internals.
- DOC Collector configuration
The reference for every section of the YAML, component naming, environment-variable expansion and connectors. Keep it open while you write the lab config.
- DOC Collector deployment patterns
The agent and gateway pages with their trade-offs, and the loadbalancing exporter setup for tail sampling. Read the gateway page in full before you design a two-tier topology.
- DOC Scaling the Collector
Which self-metrics say it is time to scale (refused data, queue at 60 to 70% of capacity), and why stateful components such as tail sampling need a load-balancing tier in front.
- DOC Internal telemetry
The full list of otelcol_* self-metrics with their levels, and how to expose them. The section on which metrics to alert on is the part to act on.
- CODE filter processor README
The current OTTL condition syntax, the legacy-key migration table, error_mode semantics and the warning about orphaned spans. Check it against the version you run, because the syntax changed in v0.146.0.
- CODE tail sampling processor README
Every policy type with examples, and the memory and scaling notes. Read before the sampling chapter in module four.
- CODE OTTL README
The language the filter and transform processors share: paths, contexts, functions and where clauses. Skim the grammar, then use the function list as a reference.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.