Comprehensive guide to trace sampling strategies for production observability and monitoring systems.
Trace sampling strategies determine how many distributed traces are retained in an observability system, balancing signal fidelity against storage and processing costs. This matters when high-volume services generate thousands of traces per second, and retaining every trace is prohibitively expensive. Sampling decisions must be made at the instrumentation, collector, and backend levels, with consequences spanning latency, completeness, and alerting accuracy.
When a service generates a predictable number of requests per second and its performance is critical but not universally monitored, the choice of sampling strategy directly affects the quality of the diagnostic data available.
Fixed-rate sampling captures one trace for every *N* incoming requests, using a simple counter or modulo operation. This is ideal for services with stable traffic and consistent request patterns.
Sample every 5th trace:
trace_id % 5 == 0
It requires minimal configuration and performs consistently under load. The strategy fails silently when the service’s request volume changes abruptly: if the service suddenly doubles its throughput, the same sample rate now captures only half the expected number of traces, and the sampling interval becomes too coarse. This leads to gaps in the timeline, especially during transient spikes.
Adaptive sampling improves on fixed-rate by adjusting the sampling rate in real time based on metrics such as request rate, duration, or error rate. It uses a sliding window to compute metrics and dynamically changes the sampling threshold.
For example, a service that samples 10% of traces when average latency is below 100ms, but increases to 30% when latency exceeds 500ms:
{
"sampling_strategy": "adaptive",
"metrics": [
{
"metric": "latency_p95",
"thresholds": [
{ "value": 100, "sample_rate": 0.1 },
{ "value": 500, "sample_rate": 0.3 }
]
}
]
}
The system computes latency_p95 over a 5-minute window and updates the sample rate every minute. The key failure mode is sampling lag: a spike in latency may not trigger increased sampling until the window has passed, so early signals from a new error cluster are delayed.
Header-based sampling uses a trace context header to propagate a sampling decision from upstream services. It relies on a trace_sampling header that contains a boolean or numeric flag.
GET /api/v1/users/123
Host: userservice.example.com
trace_sampling: 1
When a downstream service receives a trace with trace_sampling: 1, it applies the same sampling decision, possibly modifying it based on its own logic. This enables hierarchical sampling: a gateway samples all traces, then a service like payment samples only those with trace_sampling: 1, and notification samples only those with trace_sampling: 1 and error: true.
The mechanism fails silently when headers are dropped or misformatted. A trace_sampling: 1 header may be sent as trace_sampling: true, trace_sampling: "1", or trace_sampling: 1.0, leading to inconsistent sampling decisions. The reader must explicitly validate the header format and ensure all services use the same schema.
In a distributed system with multiple services, sampling must be coordinated so that traces are consistent across boundaries. The goal is to avoid trace fragmentation—where a single end-to-end request is split across multiple traces due to inconsistent sampling decisions.
Centralized sampling uses a dedicated service or backend that analyzes metrics across all services and applies sampling decisions to all incoming spans. The system collects metrics like request rate, error rate, latency, and service health, then sends sampling instructions to all instrumentation libraries.
A service receives a sampling decision via an HTTP endpoint:
POST /sampling/decision
Host: sampler.example.com
Content-Type: application/json
{
"service": "orderservice",
"timestamp": "2024-02-05T12:00:00Z",
"rate": 0.25,
"conditions": [
{ "type": "error", "value": true },
{ "type": "latency", "threshold": 1000 }
]
}
The service then applies the rate and conditions to incoming requests. This strategy ensures uniform sampling across services, but it introduces latency between decision and application. A new error cluster may take 1–2 minutes to be captured in traces because the sampler collects data over a window before sending the decision.
Decentralized sampling places the decision logic at the edge. Each service samples based on local metrics and sends decisions upstream. The gateway service collects all sampling decisions and forwards them to the collector.
A typical implementation uses a SamplingDecision message:
{
"trace_id": "a1b2c3d4e5f6",
"sample": true,
"reason": [
"error",
"latency_p95_exceeded"
],
"metadata": {
"service": "orderservice",
"duration_ms": 1240,
"error_count": 3
}
}
Each service sends such a message to the collector, which aggregates decisions and applies them to the trace. This model is resilient to network outages, but it requires careful coordination to avoid overlapping sampling decisions—where multiple services independently decide to sample a trace, resulting in redundant data.
The critical failure mode is sampling drift: two services sample a trace independently, but due to different timing or metrics, one decides to sample while the other does not. The result is a trace that starts in one service but is missing from the next. This is common when services use different sampling intervals or metrics.
Different types of workloads demand different sampling strategies.
High-throughput, low-latency services—such as API gateways, message brokers, and caching layers—benefit from probability-based sampling. These services receive a large number of requests with low variance in duration and error rate.
A typical configuration uses a probabilistic sampling algorithm where each incoming request is sampled with a fixed probability.
{
"sampling": {
"type": "probabilistic",
"rate": 0.1
}
}
Each request is sampled with 10% probability, using a random number generator seeded by the request’s trace ID. This ensures a representative sample across time, even under bursty traffic. However, the strategy fails when the system experiences bursty traffic patterns. A sudden influx of 5,000 requests per second may result in a non-uniform sample: some time windows contain many traces, others few, leading to uneven coverage.
To mitigate this, stratified sampling divides requests into categories (e.g., by service, method, or error status) and applies different probabilities to each group.
{
"sampling": {
"type": "stratified",
"strata": [
{
"condition": "service == 'payment'",
"rate": 0.4
},
{
"condition": "method == 'POST' and error == true",
"rate": 0.8
},
{
"condition": "method == 'GET' and duration_ms < 100",
"rate": 0.05
}
]
}
}
This ensures that error-prone POST requests are heavily sampled, while fast GET requests are sampled sparsely. The challenge lies in defining consistent condition evaluation. A condition like method == 'POST' must be evaluated identically across all services, including case sensitivity and encoding. A POST request may be received as Post, post, or POST due to HTTP header normalization, leading to mismatched sampling.
Long-running, event-driven processes—such as batch jobs, ETL pipelines, and workflows—require event-based sampling. Here, sampling decisions are triggered by specific events rather than request arrivals.
A workflow service samples a trace whenever a task fails or exceeds a duration threshold.
{
"sampling": {
"type": "event_based",
"events": [
{
"type": "task_failed",
"sample_rate": 1.0
},
{
"type": "task_duration_exceeded",
"threshold_ms": 5000,
"sample_rate": 0.5
}
]
}
}
When a task fails, the entire workflow trace is sampled with 100% probability. When a task takes more than 5 seconds, the trace is sampled with 50% probability. This ensures that performance issues and failures are captured in detail, while normal workflows are sampled lightly.
The failure mode is event loss. If a task fails but the event is not emitted or is delayed, the trace may not be sampled, leading to missed diagnostics. A common issue is event deduplication: the same event may be fired multiple times, causing multiple sampling decisions for the same trace.
Once sampling is deployed, it must be monitored and tuned.
Sampling efficiency is measured by the ratio of sampled traces to total traces over a window.
$ psql -c "
SELECT
COUNT(*) FILTER (WHERE sampled = true) as sampled_count,
COUNT(*) as total_count,
(COUNT(*) FILTER (WHERE sampled = true)) / COUNT(*) as sample_rate
FROM traces
WHERE timestamp >= now() - '1h'::interval
"
This query reveals whether the current strategy is achieving its target. A sample rate of 0.25 but expected 0.30 indicates that sampling is too aggressive or too sparse.
Sampling consistency is checked by analyzing trace spans across services. A trace should have a consistent trace_sampling header throughout, but in practice, headers are often inconsistent.
# Detect inconsistencies in trace_sampling header
$ curl -X POST -H "Content-Type: application/json" \
-d '{
"query": "SELECT
trace_id,
service,
header_value,
COUNT(*) as count
FROM trace_spans
WHERE header_key = 'trace_sampling'
GROUP BY trace_id, service, header_value
HAVING COUNT(*) > 1
ORDER BY trace_id, service"
}' \
https://collector.example.com/api/v1/query
This identifies traces where the sampling decision varies across services—e.g., orderservice samples a trace but paymentservice does not, even though the header was set.
The most common failure is sampling drift due to clock skew. Services with different time zones or NTP configurations may apply sampling decisions at different times, causing some traces to be sampled on the edge of a window. This is exacerbated when the collector uses a different clock than the services.
To detect and correct this, sampling drift detection uses a sampling_timestamp header that records when the sampling decision was made.
trace_sampling: 1
sampling_timestamp: 2024-02-05T12:00:00.123Z
The collector computes the expected sampling time based on the service’s clock, compares it to the actual decision time, and flags drifts exceeding 100ms.
trace_sampling: 1 but forget to include it in the outgoing HTTP request.duration > 1000 condition may use milliseconds in one service and seconds in another.These failures are silent: traces appear to be sampled, but the system misses key events, making root cause analysis harder. The reader must instrument the sampling logic with logs, metrics, and health checks to catch these issues early.
This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy