---
title: "Configure Sampling"
description: "Learn how to configure sampling in your app using the Sentry Python SDK."
url: https://docs.sentry.io/platforms/python/tracing/configure-sampling/
last_updated: 2026-11-20T18:09:29.000Z
---

# Configure Sampling for Python

If you find that Sentry's tracing functionality is generating too much data, for example, if you notice your spans quota is quickly being exhausted, you can choose to sample your traces.

Sampling allows you to keep enough traces to debug failures and slowdowns without sending every span. The Python SDK provides two ways to control the sampling rate. You can review the options and [examples](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#traces-sampler-examples) below.

The examples on this page are for SDK `3.x`. The **SDK 2.x** tabs show the equivalent code for the default transaction mode of SDK `2.x`.

If you use [stream mode](https://docs.sentry.io/platforms/python/tracing/streamed-spans.md) in SDK `2.x`, follow the **SDK 3.x** examples, but call the tracing functions on `sentry_sdk.traces` (for example, `sentry_sdk.traces.start_span()`) and set `trace_lifecycle="stream"` in `sentry_sdk.init()`.

## [Sampling Configuration Options](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sampling-configuration-options)

### [1. Uniform Sample Rate (`traces_sample_rate`)](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#1-uniform-sample-rate-traces_sample_rate)

`traces_sample_rate` is a floating-point value between `0.0` and `1.0`, inclusive, which controls the probability with which each service span (in SDK `2.x`, each transaction) will be sampled:

```python
sentry_sdk.init(
    # ...

    # Set traces_sample_rate to 1.0 to capture 100%
    # of service spans for tracing.
    # We recommend adjusting this value in production.
    traces_sample_rate=1.0,
)
```

With `traces_sample_rate` set to `0.25`, each service span in your application is randomly sampled with a probability of `0.25`, so you can expect that one in every four service spans will be sent to Sentry.

### [2. Sampling Function (`traces_sampler`)](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#2-sampling-function-traces_sampler)

For more granular control, you can provide a `traces_sampler` function. This approach allows you to:

* Apply different sampling rates to different types of service spans
* Filter out specific service spans entirely
* Make sampling decisions based on service span data
* Control the inheritance of sampling decisions in distributed traces
* Use custom attributes to modify sampling

It is strongly recommended when using a custom `traces_sampler` that you respect the parent sampling decision. This ensures your traces will be complete.

In distributed systems, implementing inheritance logic when trace information is propagated between services will ensure consistent sampling decisions across your entire distributed trace.

```python
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    # Use the parent sampling decision if we have an incoming trace.
    # Note: we strongly recommend respecting the parent sampling decision,
    # as this ensures your traces will be complete!
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    # Examine provided sampling context along with anything in the
    # global namespace to compute the sample rate for this span
    if "...":
        # These are important - take a big sample
        return 0.5
    elif "...":
        # These are less important - only take 1%
        return 0.01
    elif "...":
        # These aren't worth tracking - drop these spans
        return 0

    # Default sample rate
    return 0.1

sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)
```

*Other available variations of the above snippet: SDK 2.x*

Traces Sampler Examples

1. Prioritizing Critical User Flows

```python
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    # Use the parent sampling decision if we have an incoming trace.
    # Note: we strongly recommend respecting the parent sampling decision,
    # as this ensures your traces will be complete!
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    span_ctx = sampling_context["transaction_context"]
    name = span_ctx["name"]
    op = span_ctx["op"]

    # Sample all checkout spans
    if name and ('/checkout' in name or op == 'checkout'):
        return 1.0

    # Sample 50% of login spans
    if name and ('/login' in name or op == 'login'):
        return 0.5

    # Sample 10% of everything else
    return 0.1

sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)
```

*Other available variations of the above snippet: SDK 2.x*

2. Handling Different Environments and Error Rates

```python
import os
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    # Use the parent sampling decision if we have an incoming trace.
    # Note: we strongly recommend respecting the parent sampling decision,
    # as this ensures your traces will be complete!
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    environment = os.environ.get("ENVIRONMENT", "development")

    # Sample all spans in development
    if environment == "development":
        return 1.0

    # Sample more spans if there are recent errors
    # Note: hasRecentErrors is a custom attribute that needs to be set
    if sampling_context.get("hasRecentErrors") is True:
        return 0.8

    # Sample based on environment
    if environment == "production":
        return 0.05  # 5% in production
    elif environment == "staging":
        return 0.2   # 20% in staging

    # Default sampling rate
    return 0.1

# Initialize the SDK with the sampling function
sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)

# Custom attributes need to be set on the scope, after continue_trace
# (which resets the propagation context) and before start_span
# (which is when sampling happens), in order to be available
# in the traces_sampler
sentry_sdk.Scope.set_custom_sampling_context({"hasRecentErrors": True})
with sentry_sdk.start_span(
    name="GET /api/users",
    attributes={"sentry.op": "http.request"},
) as span:
    # your code here
```

*Other available variations of the above snippet: SDK 2.x*

3. Controlling Sampling Based on User and Transaction Properties

```python
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    # Use the parent sampling decision if we have an incoming trace.
    # Note: we strongly recommend respecting the parent sampling decision,
    # as this ensures your traces will be complete!
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    # Always sample for premium users
    # Note: user.tier is a custom attribute that needs to be set
    if sampling_context.get("user", {}).get("tier") == "premium":
        return 1.0

    # Sample more spans for users experiencing errors
    # Note: hasRecentErrors is a custom attribute
    if sampling_context.get("hasRecentErrors") is True:
        return 0.8

    # Sample less for high-volume, low-value paths
    name = sampling_context["transaction_context"]["name"]
    if name and name.startswith("/api/metrics"):
        return 0.01

    # Default sampling rate
    return 0.2

# Initialize the SDK with the sampling function
sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)

# To set custom attributes for this example:
sentry_sdk.Scope.set_custom_sampling_context(
    {"user": {"tier": "premium"}, "hasRecentErrors": True}
)
with sentry_sdk.start_span(
    name="GET /api/users",
    attributes={"sentry.op": "http.request"},
) as span:
    # Your code here
```

*Other available variations of the above snippet: SDK 2.x*

4. Complex Business Logic Sampling

```python
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    # Use the parent sampling decision if we have an incoming trace.
    # Note: we strongly recommend respecting the parent sampling decision,
    # as this ensures your traces will be complete!
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    # Always sample critical business operations
    # Note: sentry.op is an SDK-provided attribute
    span_ctx = sampling_context["transaction_context"]
    if span_ctx["op"] in ["payment.process", "order.create", "user.verify"]:
        return 1.0

    # Sample based on user segment
    # Note: user.segment is a custom attribute
    user_segment = sampling_context.get("user", {}).get("segment")
    if user_segment == "enterprise":
        return 0.8
    elif user_segment == "premium":
        return 0.5

    # Sample based on transaction value
    # Note: transaction.value is a custom attribute
    transaction_value = sampling_context.get("transaction", {}).get("value")
    if transaction_value is not None and transaction_value > 1000:  # High-value transactions
        return 0.7

    # Sample based on error rate in the service
    # Note: service.error_rate is a custom attribute
    error_rate = sampling_context.get("service", {}).get("error_rate")
    if error_rate is not None and error_rate > 0.05:  # Error rate above 5%
        return 0.9

    # Default sampling rate
    return 0.1

# Initialize the SDK with the sampling function
sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)

# To set custom attributes for this example:
sentry_sdk.Scope.set_custom_sampling_context(
    {"user": {"segment": "enterprise"}, "transaction": {"value": 1500}, "service": {"error_rate": 0.03}}
)
with sentry_sdk.start_span(
    name="Process Payment",
    attributes={"sentry.op": "payment.process"},
) as span:
    # Your code here
```

*Other available variations of the above snippet: SDK 2.x*

5. Performance-Based Sampling

```python
import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    # Use the parent sampling decision if we have an incoming trace.
    # Note: we strongly recommend respecting the parent sampling decision,
    # as this ensures your traces will be complete!
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    # Sample more spans with high memory usage
    # Note: memory_usage_mb is a custom attribute
    memory_usage = sampling_context.get("memory_usage_mb")
    if memory_usage is not None and memory_usage > 500:
        return 0.8

    # Sample more spans with high CPU usage
    # Note: cpu_percent is a custom attribute
    cpu_percent = sampling_context.get("cpu_percent")
    if cpu_percent is not None and cpu_percent > 80:
        return 0.8

    # Sample more spans with high database load
    # Note: db_connections is a custom attribute
    db_connections = sampling_context.get("db_connections")
    if db_connections is not None and db_connections > 100:
        return 0.7

    # Default sampling rate
    return 0.1

# Initialize the SDK with the sampling function
sentry_sdk.init(
    # ...
    traces_sampler=traces_sampler,
)

# To set custom attributes for this example:
sentry_sdk.Scope.set_custom_sampling_context(
    {"memory_usage_mb": 600, "cpu_percent": 85, "db_connections": 120}
)
with sentry_sdk.start_span(
    name="Process Data",
    attributes={"sentry.op": "data.process"},
) as span:
    # Your code here
```

*Other available variations of the above snippet: SDK 2.x*

## [The Sampling Context Object](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#the-sampling-context-object)

When the `traces_sampler` function is called, the Sentry SDK passes a `sampling_context` object with information from the relevant span to help make sampling decisions:

### [SDK 3.x](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sdk-3x)

```python
{
    "transaction_context": {
        "name": str,  # span title at creation time (SDK-provided)
        "op": str,  # short description of span type (SDK-provided)
        "data": dict[str, Any]  # attributes set at span-creation time (SDK- and user-provided)
    },
    "parent_sampled": Optional[bool],  # whether the parent span was sampled (SDK-provided)
    ...  # additional custom key-value pairs for sampling set via custom sampling context
}
```

### [SDK 2.x](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sdk-2x)

```python
{
    "transaction_context": {
        "name": str,  # transaction title at creation time (SDK-provided)
        "op": str,  # short description of transaction type (SDK-provided)
        "data": Optional[dict[str, Any]]
    },
    "parent_sampled": Optional[bool],  # whether the parent transaction was sampled (SDK-provided)
    ...  # additional custom data for sampling provided via custom_sampling_context
}
```

### [SDK-Provided vs. Custom Attributes](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sdk-provided-vs-custom-attributes)

The sampling context contains both SDK-provided attributes and custom attributes:

#### [SDK 3.x](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sdk-3x-1)

**SDK-Provided Attributes:**

* `transaction_context.name`: The name of the span
* `transaction_context.data`: Attributes set on the span at creation time, including `sentry.op`
* `parent_sampled`: Whether the parent span was sampled

**Custom Attributes:**

* Any data you add via `sentry_sdk.Scope.set_custom_sampling_context()`, called after `continue_trace` and before `start_span`. Use this for data that you want to use for sampling decisions but don't want to include in the span data that gets sent to Sentry.

#### [SDK 2.x](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sdk-2x-1)

**SDK-Provided Attributes:**

* `transaction_context.name`: The name of the transaction
* `transaction_context.op`: The operation type
* `parent_sampled`: Whether the parent transaction was sampled

**Custom Attributes:**

* Any data you add to the `custom_sampling_context` parameter in `start_transaction`. Use this for data that you want to use for sampling decisions but don't want to include in the transaction data that gets sent to Sentry. Read more about custom sampling context [here](https://docs.sentry.io/platforms/python/sampling__v2.x#custom-sampling-context-data).

## [Sampling Decision Precedence](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sampling-decision-precedence)

When multiple sampling mechanisms could apply, Sentry follows this order of precedence:

### [SDK 3.x](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sdk-3x-2)

1. If `traces_sampler` is defined, its decision is used. Although the `traces_sampler` can override the parent sampling decision, most users will want to ensure their `traces_sampler` respects the parent sampling decision.
2. If no `traces_sampler` is defined, but there is a parent sampling decision from an incoming distributed trace, we use the parent sampling decision.
3. If neither of the above, `traces_sample_rate` is used.
4. If none of the above are set, no spans are sampled. This is equivalent to setting `traces_sample_rate=0.0`.

### [SDK 2.x](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#sdk-2x-2)

1. If a sampling decision is passed to `start_transaction`, that decision is used.
2. If `traces_sampler` is defined, its decision is used. Although the `traces_sampler` can override the parent sampling decision, most users will want to ensure their `traces_sampler` respects the parent sampling decision.
3. If no `traces_sampler` is defined, but there is a parent sampling decision from an incoming distributed trace, we use the parent sampling decision.
4. If neither of the above, `traces_sample_rate` is used.
5. If none of the above are set, no transactions are sampled. This is equivalent to setting `traces_sample_rate=0.0`.

Sampling decisions are made when spans are created. Child spans inherit the sampling decision of their parent span unless filtered by `ignore_spans`.

## [How Sampling Propagates in Distributed Traces](https://docs.sentry.io/platforms/python/tracing/configure-sampling.md#how-sampling-propagates-in-distributed-traces)

Sentry uses a "head-based" sampling approach:

* A sampling decision is made in the originating service (the "head")
* This decision is propagated to all downstream services

The two key headers are:

* `sentry-trace`: Contains trace ID, span ID, and sampling decision
* `baggage`: Contains additional trace metadata including sample rate

The Sentry Python SDK automatically attaches these headers to outgoing HTTP requests when using auto-instrumentation with libraries like `requests`, `urllib3`, or `httpx`. For other communication channels, you can manually propagate trace information. Learn more about customizing tracing in [custom trace propagation](https://docs.sentry.io/platforms/python/tracing/distributed-tracing/custom-trace-propagation.md).

---

Find other pages: [Sitemap](https://docs.sentry.io/sitemap.md) lists every page with a one-line summary, and [llms.txt](https://docs.sentry.io/llms.txt) gives an overview with guidance for agents.
