Published

OpenTelemetry Tail Sampling: Preserve Errors and Respect Trace Affinity

Tail sampling needs enough of each trace to make a decision on the same collector.

Tail sampling needs enough of each trace to make a decision on the same collector. Model decision latency and memory, route by trace ID, and replay late or incomplete error traces before changing retention. The local gate checks reviewed records, not source truth.

Requirement / parameterPlatform targetVerification cycleArtifact output
trace affinity preservedOpenTelemetry and observability costsOn relevant changeSource and review decision
error replay passedOne controlled populationAfter collectionNormalized record
memory measuredOwned operating processAfter a known-failure testCheck report

Architectural breakdown

Use matched usage windows and the billing unit in the actual contract. Accepted telemetry, exported bytes, indexed events and billable series are different measurements. Include infrastructure, engineering time and incident coverage in the comparison. A useful pilot has one defined population, a replayable set of critical incidents and a rollback condition; a lower event count alone is not sufficient evidence of a better operating result.

Implementation boundary: Dropping 90 percent of healthy traces does not imply a 90-percent bill reduction or complete error retention.

Implementation sequence

Route spans consistently by trace ID before the tail-sampling decision point. Replay a healthy trace, an error trace and a late-arriving error span. Measure memory use during the decision wait and inspect behavior across collector restarts. Compare retained trace coverage and billed ingestion separately, accounting for upstream sampling that may already have removed spans.

Architecture and evidence flow

OpenTelemetry and observability costs
        |
        v
Authoritative source / controlled workload
        |
        v
trace affinity preserved -> error replay passed
        |
        v
Reviewed decision -> memory measured
        |
        v
Retained result + owned exception / response

Follow the source, transformation and decision as separate trust boundaries. A collector error must remain visible through the final result. Keep the raw observation reference and the policy revision together so another operator can reproduce the decision. Test both the allowed path and the expected failure; a diagram describes the intended flow and does not establish that a particular deployment implements it.

Before and after the controlled pilot

DimensionBaseline workflow to recordPilot acceptance evidence
trace affinity preservedCurrent source, coverage and manual review timeRetained source and a repeated check
error replay passedCurrent gaps, errors and exception ownershipKnown-failure result and assigned follow-up
memory measuredCurrent handoff, response or operating effortOperator replay and documented next action
Time and costActual task counts, minutes and billed unitsMatched window, maintenance effort and explicit assumptions

This comparison defines what to measure; it is not an observed customer saving. Record the baseline before the change, include maintenance and exception handling, and keep unmatched scope visible. Calculate a difference only after both windows use the same population and service obligations. Use the source-specific implementation sequence above to choose the evidence rather than importing a generic percentage from a case-study headline.

Get the complete reference kit by work email. The kit page lists the actual archive contents and preview; submitting does not subscribe you to marketing.

Native reference artifact

Review inputs, permissions and configuration context; keep source exports private.

# Collector-contrib fragment; all spans for a trace must reach this instance.
processors:
  tail_sampling/reviewed:
    decision_wait: 30s
    num_traces: 50000
    expected_new_traces_per_sec: 1000
    policies:
      - name: retain-errors
        type: status_code
        status_code:
          status_codes: [ERROR]
      - name: healthy-sample
        type: probabilistic
        probabilistic:
          sampling_percentage: 10
# Tune capacity using measured trace sizes, late spans and collector restarts.

Download this reference artifact. Use documented authentication; keep credentials outside source files.

Define the local evidence contract

Independent local record format: these Booleans require source review and normalization. This is separate from official FedRAMP and vendor schemas.

{
  "version": 1,
  "id": "tcinfra-reference-089",
  "title": "OpenTelemetry Tail Sampling: Preserve Errors and Respect Trace Affinity",
  "maxAgeHours": 24,
  "objective": "Tail sampling needs enough of each trace to make a decision on the same collector. Model decision latency and memory, route by trace ID, and replay late or incomplete error traces before changing retention.",
  "boundary": "Dropping 90 percent of healthy traces does not imply a 90-percent bill reduction or complete error retention.",
  "reference": "https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/tailsamplingprocessor",
  "checks": [
    {
      "field": "traceAffinityPreserved",
      "equals": true,
      "interpretation": "Record the reviewed evidence for trace affinity preserved."
    },
    {
      "field": "errorReplayPassed",
      "equals": true,
      "interpretation": "Record the reviewed evidence for error replay passed."
    },
    {
      "field": "memoryMeasured",
      "equals": true,
      "interpretation": "Record the reviewed evidence for memory measured."
    }
  ]
}

Save as policy.json; the following fixture.json is synthetic.

{
  "synthetic": true,
  "scope": "one controlled reference population",
  "sourceRef": "synthetic://content-core/089",
  "records": [
    {
      "id": "synthetic-089-a",
      "observedAt": "2026-11-03T12:00:00Z",
      "traceAffinityPreserved": true,
      "errorReplayPassed": true,
      "memoryMeasured": true
    }
  ]
}

Complete executable record checker

Save the complete shared Python 3.9+ checker as evidence-check.py, or download it. No network calls or cloud credentials are required.

#!/usr/bin/env python3
"""Local evidence-record gate. It does not collect or certify cloud state.
Python 3.9+; standard library only. JSON output contains metadata, not raw records.
"""
import argparse
import hashlib
import json
import sys
from datetime import datetime, timezone
from pathlib import Path


def timestamp(value):
    if not isinstance(value, str):
        raise ValueError('Timestamp must be an ISO 8601 string')
    result = datetime.fromisoformat(value.replace('Z', '+00:00'))
    if result.tzinfo is None:
        raise ValueError('Timestamp must include a timezone')
    return result.astimezone(timezone.utc)


def check(policy, dataset, now):
    if policy.get('version') != 1 or not policy.get('checks'):
        raise ValueError('Unsupported or empty policy')
    if not isinstance(dataset.get('records'), list) or not dataset['records']:
        raise ValueError('A nonempty, explicitly scoped population is required')
    if not dataset.get('scope') or not dataset.get('sourceRef'):
        raise ValueError('Missing population scope or source reference')
    errors = []
    seen = set()
    for row in dataset['records']:
        identity = row.get('id')
        if not isinstance(identity, str) or not identity or identity in seen:
            raise ValueError('Missing, invalid or duplicate record identity')
        seen.add(identity)
        age = (now - timestamp(row.get('observedAt'))).total_seconds()
        if age < 0 or age > policy['maxAgeHours'] * 3600:
            errors.append({'id': identity, 'field': 'observedAt', 'reason': 'freshness'})
        for rule in policy['checks']:
            value = row.get(rule['field'])
            expected = rule['equals']
            # JSON true must not compare equal to numeric 1.
            if type(value) is not type(expected) or value != expected:
                errors.append({'id': identity, 'field': rule['field'], 'reason': 'mismatch'})
    return {'policyId': policy['id'], 'recordsChecked': len(seen),
            'passed': not errors, 'failures': errors,
            'checkedAt': now.isoformat(),
            'meaning': 'Record completeness and policy match only; source truth requires review'}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('policy', type=Path)
    parser.add_argument('dataset', type=Path)
    parser.add_argument('--as-of', help='Explicit timestamp for reproducible synthetic tests')
    args = parser.parse_args()
    try:
        policy_bytes = args.policy.read_bytes()
        data_bytes = args.dataset.read_bytes()
        now = timestamp(args.as_of) if args.as_of else datetime.now(timezone.utc)
        report = check(json.loads(policy_bytes), json.loads(data_bytes), now)
        report['policySha256'] = hashlib.sha256(policy_bytes).hexdigest()
        report['inputSha256'] = hashlib.sha256(data_bytes).hexdigest()
        print(json.dumps(report, indent=2))
        return 0 if report['passed'] else 1
    except (OSError, ValueError, KeyError, TypeError) as error:
        print(json.dumps({'passed': False, 'error': type(error).__name__}), file=sys.stderr)
        return 2


if __name__ == '__main__':
    sys.exit(main())

Download the article policy and fixture, then run:

python3 evidence-check.py policy.json fixture.json \
  --as-of 2026-11-03T13:00:00Z
# Synthetic fixture: exit 0, passed=true, recordsChecked=1.
# Live observations: omit --as-of to use the actual current UTC clock.

Production Pitfalls

  1. Incomplete reasoning: Dropping 90 percent of healthy traces does not imply a 90-percent bill reduction or complete error retention.
  2. False success: change traceAffinityPreserved to false; expect exit 1. A missing field or numeric 1 must also fail.
  3. Stale coverage: empty input is rejected. An expired or future observation fails the policy window.

Exit 0 means agreement, 1 means mismatch, and 2 means invalid input or execution failure. Preserve these distinctions and independently review the source evidence.

Companion kit and implementation help

Inspect the OpenTelemetry and observability costs kit, scope an engineering sprint, or request a triage using sanitized environment details.

Continue reading

Sources and version notes

Reviewed November 3, 2026. Local fixtures test the record gate; cloud deployments, integrations and performance require environment tests.

Frequently asked questions

What does the local check verify for OpenTelemetry Tail Sampling?

It requires a nonempty scoped record set, fresh timestamps and explicit true values for trace affinity preserved, error replay passed, memory measured. It does not establish that the source facts are true.

Can the reference example be applied directly to production?

Dropping 90 percent of healthy traces does not imply a 90-percent bill reduction or complete error retention. Review the linked official documentation and test the installed versions in a controlled environment.

What should be retained with the result?

Keep the raw source reference, collection scope, observation time, policy revision, reviewer decision and any unresolved exception. The check output includes input and policy digests for reproducibility.

Browse all writing · RSS feed

Tymur Chmeruk

Written by

Tymur Chmeruk

Cloud Security & Infrastructure Engineer · Baltimore–Washington Metro · [email protected]