> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Sampling

> Demonstrates applying OpenTelemetry Python sampling to reduce trace volume using a TraceIdRatioBased sampler and console exporter while preserving representative traces for debugging and observability.

This lesson demonstrates how to apply sampling to reduce the number of traces generated by a service. Sampling helps lower telemetry volume sent to backends while preserving a representative subset for debugging and observability.

For demonstration we use the Console exporter so sampled spans are printed directly to application stdout. You can replace it with another exporter (for example, the OTLP exporter) and sampling behavior will remain the same.

## Why sampling?

* Reduces network, storage, and processing costs by exporting fewer traces.
* Keeps a representative subset of traces for performance and error analysis.
* Deterministic sampling (based on trace ID) ensures consistent decisions across services that share the same trace context.

## Example: TraceIdRatioBased sampler (10%) + Console exporter

Below is a complete example that sets up:

* a `TraceIdRatioBased` sampler with 10% sampling,
* a `BatchSpanProcessor`,
* a `ConsoleSpanExporter` for demo output (with an OTLP exporter commented out if you want to send traces to a collector instead).

```python theme={null}
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor
from opentelemetry.sdk.trace.sampling import TraceIdRatioBased
def configure_tracer():
    # Use ConsoleSpanExporter for demo; replace with OTLPSpanExporter to send to a collector:
    exporter = ConsoleSpanExporter()
    # exporter = OTLPSpanExporter(endpoint="http://localhost:4318/v1/traces")

    span_processor = BatchSpanProcessor(exporter)
    resource = Resource.create({
        "service.name": "charge-service",
        "service.version": "0.5.0"
    })

    # TraceIdRatioBased accepts a float between 0.0 and 1.0.
    # e.g., 0.1 means roughly 10% of traces will be sampled.
    sampler = TraceIdRatioBased(0.1)

    provider = TracerProvider(resource=resource, sampler=sampler)
    provider.add_span_processor(span_processor)

    # Make this provider the global tracer provider
    trace.set_tracer_provider(provider)
```

<Callout icon="lightbulb" color="#1CB2FE">
  The `TraceIdRatioBased` sampler uses the trace ID to produce a deterministic sampling decision. A ratio of `0.1` will sample approximately 10% of traces; `0.0` samples none and `1.0` samples all.
</Callout>

## How to use this in your app

1. Call `configure_tracer()` during application startup (before handling incoming requests).
2. Run your service (for example, a Flask app exposing a `/charge` endpoint).
3. Generate requests (e.g., with `curl`) and watch application stdout for exported spans when requests are sampled.

Example requests:

```plaintext theme={null}
curl http://127.0.0.1:5000/charge
Charging Users Bank Account

curl http://127.0.0.1:5000/charge
Charging Users Bank Account

curl http://127.0.0.1:5000/charge
Charging Users Bank Account
```

Because sampling is probabilistic and based on trace IDs, you should see roughly 1 out of 10 requests produce exported trace output when using a `TraceIdRatioBased(0.1)` sampler.

## Sampler options at a glance

| Sampler             | Use case                                                                      | Example                  |
| ------------------- | ----------------------------------------------------------------------------- | ------------------------ |
| `TraceIdRatioBased` | Probabilistic sampling using trace ID for consistent sampling across services | `TraceIdRatioBased(0.1)` |
| `AlwaysOn`          | Capture all traces (useful for debugging)                                     | `AlwaysOn()`             |
| `AlwaysOff`         | Capture no traces (useful to disable tracing)                                 | `AlwaysOff()`            |

## Resource example

When creating resources, include identifying attributes for your service:

* Example resource used above:
  `{ "service.name": "charge-service", "service.version": "0.5.0" }`

## Best practices & troubleshooting

* Use a conservative sampling ratio in production to control telemetry costs; consider higher sampling for error traces or slow requests.
* If you require guaranteed capture of specific requests (e.g., errors), implement custom sampling logic or use a tail-based sampling approach at the collector.
* If you switch to OTLP, verify your collector/backend is reachable and the endpoint is correctly configured.
* Monitor the rate of sampled traces and adjust the ratio if you need more or fewer traces.

<Callout icon="warning" color="#FF6B6B">
  Avoid setting `TraceIdRatioBased` too low in early production or when first instrumenting a service—you may miss important traces. For debugging or initial rollout, start with higher sampling and reduce once you have confidence in coverage and cost.
</Callout>

## Links and references

* Console exporter docs: [https://opentelemetry-python.readthedocs.io/en/stable/](https://opentelemetry-python.readthedocs.io/en/stable/)
* OTLP exporter docs: [https://opentelemetry-python.readthedocs.io/en/stable/exporter/otlp/](https://opentelemetry-python.readthedocs.io/en/stable/exporter/otlp/)
* OTLP protocol: [https://opentelemetry.io/docs/reference/specification/protocol/otlp/](https://opentelemetry.io/docs/reference/specification/protocol/otlp/)
* Flask: [https://flask.palletsprojects.com/](https://flask.palletsprojects.com/)

Using sampling reduces the volume of traces sent to your backend while maintaining a useful subset for observability and debugging. Adjust the sampling strategy to match your telemetry needs and cost constraints.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/prep-course-opentelemetry-certified-associate-certification-otca/module/d97970ef-6201-45c2-813e-e03bc75ad77a/lesson/2ef4294a-be10-4925-abc3-d83b36af61b5" />
</CardGroup>
