﻿---
title: Configure tracing collection
description: Learn how to configure and customize tracing collection through the {{agent}}.
url: https://www.elastic.co/elastic/docs-builder/docs/5113/reference/edot-collector/config/configure-tracing-collection
products:
  - Elastic Agent
  - Elastic Agent
  - Elastic Cloud Serverless
  - Elastic Observability
applies_to:
  - Serverless Observability projects: Generally available
  - Elastic Stack: Generally available
  - Elastic Agent: Generally available
---

# Configure tracing collection
Learn how to configure and customize tracing collection through the Elastic Agent.

## OTLP traces

Any application instrumented with OpenTelemetry SDKs can forward traces to the Elastic Agent using the [OTLP receiver](https://github.com/open-telemetry/opentelemetry-collector/tree/main/receiver/otlpreceiver). This is the recommended method for collecting application traces.
The following minimal configuration receives traces over gRPC and HTTP, enriches them for the Elastic APM UIs, and exports them to Elasticsearch:
```yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

connectors:
  elasticapm:

processors:
  elasticapm:

exporters:
  elasticsearch/otel:
    endpoints: ["${env:ELASTIC_ENDPOINT}"]
    api_key: ${env:ELASTIC_API_KEY}

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [elasticapm]
      exporters: [elasticapm, elasticsearch/otel]
    metrics/aggregated-metrics:
      receivers: [elasticapm]
      processors: []
      exporters: [elasticsearch/otel]
```

<note>
  Both the [`elasticapm` processor](https://www.elastic.co/elastic/docs-builder/docs/5113/reference/edot-collector/components/elasticapmprocessor) and the [`elasticapm` connector](https://www.elastic.co/elastic/docs-builder/docs/5113/reference/edot-collector/components/elasticapmconnector) are required for Elastic APM UIs to work properly. The processor enriches trace data with additional attributes, while the connector generates pre-aggregated APM metrics from tracing data.As they aren't included in the OpenTelemetry [Collector Contrib repository](https://github.com/open-telemetry/opentelemetry-collector-contrib), you can:
  - Use the Elastic Agent with the available configuration to ingest data into Elasticsearch.
  - [Build a custom, Elastic Agent-like Collector](https://www.elastic.co/elastic/docs-builder/docs/5113/reference/edot-collector/custom-collector) for ingesting data into Elasticsearch.
  - Use Elastic's [managed OTLP endpoint](https://docs-v3-preview.elastic.dev/elastic/docs-builder/docs/5113/solutions/observability/get-started/opentelemetry/quickstart/serverless) that does the enrichment for you.
</note>


## Tail-based sampling

<applies-to>
  - Elastic Agent: Preview since 9.2
</applies-to>

Tail-based sampling analyzes a complete trace before deciding whether to keep it, enabling intelligent decisions based on factors like errors or high latency. This is different from head-based sampling, which makes an early decision at the start of a trace.
Within the OpenTelemetry Collector, any processor that generates metrics from traces must run before the tail-sampling processor. If sampling happens first, metrics will be calculated on an incomplete data set, leading to inaccurate and misleading reporting.
<tip>
  To enforce a specific order of calculations and sampling decisions in the Elastic Agent, you can use the [Forward connector](https://github.com/open-telemetry/opentelemetry-collector/tree/main/connector/forwardconnector). Split the traces pipeline in two steps using the connector, with the first part applying calculations and the second part applying the tail-based sampling decision.
</tip>


### Create a two-step trace pipeline

Configure a two-step trace pipeline, ensuring that the first step includes the `elasticapm` connector and `forward` connector under the `exporters` section, and that the second step includes the `tail_sampling` processor.
The following configuration is a full working example with the `elasticapm` processor and connector, tail-based sampling, and aggregated APM metrics:
```yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

connectors:
  elasticapm: {}
  forward:

processors:
  elasticapm: {}
  tail_sampling:
    decision_wait: 10s
    num_traces: 100
    expected_new_traces_per_sec: 10
    policies:
      - name: errors
        type: status_code
        status_code:
          status_codes: [ERROR]
      - name: probabilistic-10-percent
        type: probabilistic
        probabilistic:
          sampling_percentage: 10

exporters:
  debug: {}
  elasticsearch/otel:
    endpoints:
      - ${ELASTIC_ENDPOINT}
    api_key: ${ELASTIC_API_KEY}

service:
  pipelines:
    traces/1-process-elastic:
      receivers: [otlp]
      processors: [elasticapm]
      exporters: [debug, elasticapm, forward]
    traces/2-process-tbs:
      receivers: [forward]
      processors: [tail_sampling]
      exporters: [debug, elasticsearch/otel]
    metrics/aggregated-otel-metrics:
      receivers: [elasticapm]
      processors: []
      exporters: [debug, elasticsearch/otel]
```


### Send tail-sampled data to Managed OTLP through a Gateway Collector

Use this configuration to run tail-based sampling in your own environment and send the results to the [Elastic Cloud Managed OTLP Endpoint](https://docs-v3-preview.elastic.dev/elastic/docs-builder/docs/5113/reference/managed-inputs/managed-otlp-endpoint). Run it on a self-managed Elastic Agent in [Gateway mode](/elastic/docs-builder/docs/5113/reference/edot-collector/modes#edot-collector-as-gateway). OpenTelemetry SDKs and upstream Collectors send telemetry to the Gateway, which generates APM metrics, applies tail-based sampling, and exports the results to the Elastic Cloud Managed OTLP Endpoint.
To use this configuration, you need your Elastic Cloud Managed OTLP Endpoint URL and an API key. The Elastic Cloud Managed OTLP Endpoint is available on Elastic Cloud Serverless and Elastic Cloud Hosted, but not on self-managed, Elastic Cloud Enterprise, or Elastic Cloud on Kubernetes deployments. If you send data directly to Elasticsearch, use the [two-step trace pipeline](#create-a-two-step-trace-pipeline) instead.
The `otlp_grpc/managed_otlp_aggregated` exporter adds the `x-elastic-apm-aggregation-processed: "true"` header. The Elastic Cloud Managed OTLP Endpoint uses this header to avoid aggregating the data again. Without the header, the Elastic Cloud Managed OTLP Endpoint aggregates the data a second time, which produces duplicate metrics. Send only the following data through this exporter:
- Traces kept by tail-based sampling
- Logs and metrics processed by the Gateway's `elasticapm` connector
- Metrics generated by the `elasticapm` connector

In this example, all incoming metrics and logs pass through the `elasticapm` connector. If you want the Elastic Cloud Managed OTLP Endpoint to aggregate some of your telemetry instead, send that telemetry through a separate pipeline that doesn't use the `elasticapm` connector, with an exporter that doesn't set the header.
Before you deploy this configuration to production, review [Scale tail-based sampling](#scale-tail-based-sampling).
The following configuration is a full working example. Before you run it, set the `ELASTIC_OTLP_ENDPOINT` and `ELASTIC_API_KEY` environment variables to your [Elastic Cloud Managed OTLP Endpoint URL](https://docs-v3-preview.elastic.dev/elastic/docs-builder/docs/5113/reference/managed-inputs/managed-otlp-endpoint#find-your-motlp) and [API key](https://docs-v3-preview.elastic.dev/elastic/docs-builder/docs/5113/reference/managed-inputs/authentication-delivery-and-failure-handling#authentication):
```yaml
receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318

connectors:
  elasticapm:
    # Aggregation state is stored in memory by default. For high-throughput
    # production workloads, uncomment and set a dedicated writable directory.
    # aggregation:
    #   directory: ${env:ELASTIC_APM_AGGREGATION_DIR}
  forward:

processors:
  elasticapm: {}
  tail_sampling:
    decision_wait: 10s
    num_traces: 200
    expected_new_traces_per_sec: 10
    policies:
      - name: errors
        type: status_code
        status_code:
          status_codes: [ERROR]
      - name: probabilistic-10-percent
        type: probabilistic
        probabilistic:
          sampling_percentage: 10

exporters:
  otlp_grpc/managed_otlp_aggregated:
    endpoint: ${env:ELASTIC_OTLP_ENDPOINT}
    headers:
      Authorization: ApiKey ${env:ELASTIC_API_KEY}
      x-elastic-apm-aggregation-processed: "true"

service:
  pipelines:
    # Incoming metrics and logs go to both the connector for APM metric
    # aggregation and Managed OTLP as their original signals.
    metrics:
      receivers: [otlp]
      processors: [elasticapm]
      exporters: [elasticapm, otlp_grpc/managed_otlp_aggregated]
    logs:
      receivers: [otlp]
      processors: [elasticapm]
      exporters: [elasticapm, otlp_grpc/managed_otlp_aggregated]
    # Enrich all spans and aggregate APM metrics before sampling. The forward
    # connector passes the same traces to the post-processing pipeline.
    traces/1-process-elastic:
      receivers: [otlp]
      processors: [elasticapm]
      exporters: [elasticapm, forward]
    # Make the tail-sampling decision and export only retained traces.
    traces/2-process-tbs:
      receivers: [forward]
      processors: [tail_sampling]
      exporters: [otlp_grpc/managed_otlp_aggregated]
    # Export APM metrics generated by the connector. These are distinct from
    # the incoming application metrics handled by the metrics pipeline.
    metrics/aggregated-otel-metrics:
      receivers: [elasticapm]
      processors: []
      exporters: [otlp_grpc/managed_otlp_aggregated]
```


### Scale tail-based sampling

The [tail-sampling processor](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/tailsamplingprocessor) keeps pending traces in memory until it decides whether to sample them. Use these settings to control how many traces the processor keeps and for how long:
- `decision_wait`: How long the processor waits after it receives the first span of a trace. A longer wait catches late spans, but the processor keeps each trace in memory for longer.
- `num_traces`: The maximum number of traces the processor keeps in memory. When the processor reaches this limit, it can evict traces before it makes a sampling decision.
- `expected_new_traces_per_sec`: The expected rate of new traces. The processor uses this value to preallocate internal data structures; it doesn't limit throughput.

Set `num_traces` higher than the peak number of new traces you expect during `decision_wait`, and leave headroom for traffic bursts and late spans. Before you deploy to production, test under representative load and check memory usage and early evictions.
Elastic Agent doesn't include the experimental upstream [Pebble tail-storage extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/tailstorage/pebbletailstorageextension), so the tail-sampling processor keeps pending traces in memory.
The `elasticapm` connector keeps its own metric aggregation state. The example leaves [`aggregation.directory`](https://github.com/elastic/opentelemetry-collector-components/tree/main/connector/elasticapmconnector#configuration) commented out because the path depends on your deployment. If you don't configure it, all aggregation state remains in memory and memory use can grow with throughput and metric cardinality. For high-throughput production workloads, uncomment the setting and provide a dedicated writable directory to store the state on disk.

#### Distribute traces with a load-balancing Collector

To scale tail-sampling Collectors horizontally, send all traces through a load-balancing Collector in front of them. In the load-balancing Collector, set `routing_key` to `traceID` so that all spans of a trace go to the same downstream tail-sampling Collector.
<tab-set>
  <tab-item title="Load-balancing Collector">
    ```yaml
    receivers:
      otlp:
        protocols:
          grpc:
            endpoint: 0.0.0.0:4317
          http:
            endpoint: 0.0.0.0:4318

    exporters:
      loadbalancing:
        protocol:
          otlp:
        resolver:
          static:
            hostnames: [http://localhost:4320, http://localhost:4321]
        routing_key: traceID

    service:
      pipelines:
        traces:
          receivers: [otlp]
          processors: []
          exporters: [loadbalancing]
    ```
  </tab-item>

  <tab-item title="Downstream Collector">
    ```yaml
    receivers:
      otlp:
        protocols:
          grpc:
            endpoint: 0.0.0.0:4317
          http:
            endpoint: 0.0.0.0:4318

    connectors:
      elasticapm: {}
      forward:

    processors:
      elasticapm: {}
      tail_sampling:
        decision_wait: 10s
        num_traces: 100
        expected_new_traces_per_sec: 10
        policies:
          - name: errors
            type: status_code
            status_code:
              status_codes: [ERROR]
          - name: probabilistic-10-percent
            type: probabilistic
            probabilistic:
              sampling_percentage: 10

    exporters:
      debug: {}
      elasticsearch/otel:
        endpoints:
          - ${ELASTIC_ENDPOINT}
        api_key: ${ELASTIC_API_KEY}

    service:
      pipelines:
        traces/1-process-elastic:
          receivers: [otlp]
          processors: [elasticapm]
          exporters: [debug, elasticapm, forward]
        traces/2-process-tbs:
          receivers: [forward]
          processors: [tail_sampling]
          exporters: [debug, elasticsearch/otel]
        metrics/aggregated-otel-metrics:
          receivers: [elasticapm]
          processors: []
          exporters: [debug, elasticsearch/otel]
    ```
  </tab-item>
</tab-set>


## Resources

To learn more about tail-based sampling in the OpenTelemetry Collector, refer to the [Tail sampling OTel documentation](https://opentelemetry.io/docs/concepts/sampling/#tail-sampling).