A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.sentry.io/platforms/python/tracing/configure-sampling/ below:

Configure Sampling | Sentry for Python

Configure Sampling Learn how to configure sampling in your app.

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.

Effective sampling is key to getting the most value from Sentry's performance monitoring while minimizing overhead. The Python SDK provides two ways to control the sampling rate. You can review the options and examples below.

Sampling Configuration Options 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 transaction will be sampled:

Copied

sentry_sdk.init(
    

    
    
    
    traces_sample_rate=1.0,
)

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

2. Sampling Function (traces_sampler)

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

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.

Copied

import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    
    
    
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    
    
    if "...":
        
        return 0.5
    elif "...":
        
        return 0.01
    elif "...":
        
        return 0

    
    return 0.1

sentry_sdk.init(
    
    traces_sampler=traces_sampler,
)
Traces Sampler Examples Traces Sampler Examples
  1. Prioritizing Critical User Flows

Copied

import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    
    
    
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

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

    
    if name and ('/checkout' in name or op == 'checkout'):
        return 1.0

    
    if name and ('/login' in name or op == 'login'):
        return 0.5

    
    return 0.1

sentry_sdk.init(
    dsn="your-dsn",
    traces_sampler=traces_sampler,
)
  1. Handling Different Environments and Error Rates

Copied

import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    
    
    
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    custom_sampling_ctx = sampling_context["custom_sampling_context"]
    environment = os.environ.get("ENVIRONMENT", "development")

    
    if environment == "development":
        return 1.0

    
    
    if custom_sampling_ctx.get("hasRecentErrors") is True:
        return 0.8

    
    if environment == "production":
        return 0.05  
    elif environment == "staging":
        return 0.2   

    
    return 0.1


sentry_sdk.init(
    dsn="your-dsn",
    traces_sampler=traces_sampler,
)




with sentry_sdk.start_transaction(
    name="GET /api/users",
    op="http.request",
    custom_sampling_context={"hasRecentErrors": True},
) as transaction:
    
  1. Controlling Sampling Based on User and Transaction Properties

Copied

import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    
    
    
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    custom_sampling_ctx = sampling_context["custom_sampling_context"]

    
    
    if custom_sampling_ctx.get("user", {}).get("tier") == "premium":
        return 1.0

    
    
    if custom_sampling_ctx.get("hasRecentErrors") is True:
        return 0.8

    
    name = sampling_context["transaction_context"]["name"]
    if name and name.startswith("/api/metrics"):
        return 0.01

    
    return 0.2


sentry_sdk.init(
    dsn="your-dsn",
    traces_sampler=traces_sampler,
)


with sentry_sdk.start_transaction(
    name="GET /api/users",
    op="http.request",
    custom_sampling_context={"user": {"tier": "premium"}, "hasRecentErrors": True},
) as transaction:
    
  1. Complex Business Logic Sampling

Copied

import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    
    
    
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    
    
    transaction_ctx = sampling_context["transaction_context"]
    if transaction_ctx["op"] in ["payment.process", "order.create", "user.verify"]:
        return 1.0

    custom_sampling_context = sampling_context["custom_sampling_context"]

    
    
    user_segment = custom_sampling_context.get("user", {}).get("segment")
    if user_segment == "enterprise":
        return 0.8
    elif user_segment == "premium":
        return 0.5

    
    
    transaction_value = custom_sampling_context.get("transaction", {}).get("value")
    if transaction_value is not None and transaction_value > 1000:  
        return 0.7

    
    
    error_rate = custom_sampling_context.get("service", {}).get("error_rate")
    if error_rate is not None and error_rate > 0.05:  
        return 0.9

    
    return 0.1


sentry_sdk.init(
    dsn="your-dsn",
    traces_sampler=traces_sampler,
)


with sentry_sdk.start_transaction(
    name="Process Payment",
    op="payment.process",
    custom_sampling_context={"user": {"segment": "enterprise"}, "transaction": {"value": 1500}, "service": {"error_rate": 0.03}},
) as transaction:
    

  1. Performance-Based Sampling

Copied

import sentry_sdk
from sentry_sdk.types import SamplingContext

def traces_sampler(sampling_context: SamplingContext) -> float:
    
    
    
    parent_sampling_decision = sampling_context["parent_sampled"]
    if parent_sampling_decision is not None:
        return float(parent_sampling_decision)

    custom_sampling_ctx = sampling_context["custom_sampling_context"]

    
    
    memory_usage = custom_sampling_ctx.get("memory_usage_mb")
    if memory_usage is not None and memory_usage > 500:
        return 0.8

    
    
    cpu_percent = custom_sampling_ctx.get("cpu_percent")
    if cpu_percent is not None and cpu_percent > 80:
        return 0.8

    
    
    db_connections = custom_sampling_ctx.get("db_connections")
    if db_connections is not None and db_connections > 100:
        return 0.7

    
    return 0.1


sentry_sdk.init(
    dsn="your-dsn",
    traces_sampler=traces_sampler,
)


with sentry_sdk.start_transaction(
    name="Process Data",
    op="data.process",
    custom_sampling_context={"memory_usage_mb": 600, "cpu_percent": 85, "db_connections": 120},
) as transaction:
    
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:

Copied

{
    "transaction_context": {
        "name": str,  
        "op": str,  
        "data": Optional[dict[str, Any]]
    },
    "parent_sampled": Optional[bool],  
    "parent_sample_rate": Optional[float],  
    "custom_sampling_context": Optional[dict[str, Any]]  
}
SDK-Provided vs. Custom Attributes

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

SDK-Provided Attributes:

Custom Attributes:

Sampling Decision Precedence

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

  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
How Sampling Propagates in Distributed Traces

Sentry uses a "head-based" sampling approach:

The two key headers are:

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

Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4