OpenTelemetry Tracing in FastAPI with Secret Scrubbing

Observability

Configure FastAPI OpenTelemetry to reduce secret exposure in traces. Learn safe header capture, Collector redaction, sampling limits, and sentinel-data tests.

TL;DR

  • Distributed traces help follow a request through FastAPI, database calls, and downstream services, but instrumentation can also export credentials, personal data, or payment details.
  • There is no honest universal “zero-overhead” claim. Measure CPU, memory, latency, and exporter pressure under your traffic, then tune sampling and batching against an explicit telemetry budget.
  • Prevent sensitive data at the source. Do not record request bodies, authorization headers, raw SQL parameters, or arbitrary exception text unless a reviewed use case requires it.
  • Use OpenTelemetry FastAPI instrumentation with a narrow attribute policy, sanitize any captured headers, and apply Collector redaction as a secondary control before export.
  • Test the exported spans and logs with sentinel secrets. A clean dashboard does not prove that every signal and path is safe.

Tracing helps explain latency across service boundaries

A trace connects spans that describe parts of one operation. A FastAPI server span can contain a database client span and an outbound HTTP span. Their parent-child relationships and trace identifiers let an engineer find where time was spent without joining separate log files by guesswork. OpenTelemetry provides APIs and conventions for creating this telemetry, while SDKs and exporters send it to a collector or backend.

The same instrumentation can create a data exposure path. Request headers, query strings, route parameters, SQL statements, exception messages, baggage, and custom span attributes may hold secrets or personally identifiable information. Automatically collecting those values turns a monitoring system into another sensitive-data store. OpenTelemetry's security guidance puts responsibility on implementers to understand and review the data emitted by their instrumentation libraries. OpenTelemetry guidance for handling sensitive data

Instrumenting a service is therefore a data-governance decision as well as a performance decision. Define what operators need to diagnose and collect the smallest set that supports that purpose. Record a route template such as /accounts/{account_id} instead of a raw URL containing an identifier. Record a stable operation name instead of a SQL query with bind values. Capture an opaque request ID rather than a session token.

Start with the smallest useful FastAPI setup

The OpenTelemetry Python contrib package provides FastAPI instrumentation. It creates spans around server requests and can be configured with request and response hooks. Install compatible versions of the API, SDK, exporter, and instrumentation packages from your dependency lock file. The example below shows the shape of setup; configure resource identity and exporter endpoint through your deployment configuration rather than hardcoding credentials. OpenTelemetry FastAPI instrumentation documentation

from fastapi import FastAPI
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

resource = Resource.create({
    "service.name": "billing-api",
    "service.version": "2026.11.20",
    "deployment.environment.name": "production",
})
provider = TracerProvider(resource=resource)
provider.add_span_processor(
    BatchSpanProcessor(OTLPSpanExporter())
)
trace.set_tracer_provider(provider)

app = FastAPI()
FastAPIInstrumentor.instrument_app(
    app,
    excluded_urls="health,ready",
    http_capture_headers_server_request=[],
    http_capture_headers_sanitize_fields=["authorization", "cookie", "set-cookie"],
)

Do not install a second provider from a different application module or initialize instrumentation before your intended resource and sampler are set. The FastAPI instrumentor can be attached programmatically or through zero-code instrumentation. Pick one model per process and document the startup order so auto-instrumentation does not double-instrument a route.

The header capture list above is deliberately empty. Sanitizing a header is only relevant when header capture is enabled; it is not a reason to capture every header. The instrumentation docs expose environment variables and parameters for capturing specified headers and a separate list of header names to sanitize. These environment names are experimental, so pin and verify the contrib version you deploy. FastAPI header capture and sanitization options

Do not confuse instrumentation with permission to collect

Keep request bodies out of spans by default

Body capture is rarely needed to understand a production latency issue. Payment credentials, password-reset tokens, health data, and customer text can appear in a JSON request body. A route hook that records the body for “debugging” may export it to every trace backend and retention tier. Prefer a request size, content type, validated operation name, and a non-sensitive application identifier.

If an incident requires payload inspection, use a separately authorized, time-limited process with field-level redaction and access logging. Do not enable broad body capture globally or place raw samples in baggage. Baggage propagates across service boundaries, so a single unsafe value can be copied into downstream telemetry.

Review URL and database instrumentation

Query parameters can contain email addresses, reset tokens, search text, or signed URLs. Avoid recording the raw query string. If you need a route dimension, use the framework's route template and keep high-cardinality values out of metrics. SQL instrumentation may record statement text or parameter values depending on the library and configuration. Inspect the exact package version and disable statement or parameter capture unless there is a reviewed need.

Exception messages can contain file paths, SQL fragments, remote responses, or snippets of user input. Export the exception type, a stable error code, and trace context. Keep detailed stack traces in a protected log sink when required, with their own redaction and access controls. Avoid attaching the same exception to both a span and a log unless the correlation provides operational value.

Sanitize before crossing a trust boundary

Prefer source-level data minimization because it prevents sensitive values from being created in telemetry at all. Collector processors can add a second filtering layer before export, especially when multiple services send into a shared collector. OpenTelemetry documents a Collector redaction processor that removes attributes outside an allowlist and can mask values matching configured patterns. Collector redaction and allowlist guidance

processors:
  redaction/trace_allowlist:
    allow_all_keys: false
    allowed_keys:
      - http.request.method
      - http.response.status_code
      - url.scheme
      - server.address
      - service.name
      - service.version
      - deployment.environment.name
      - app.request.id
    blocked_values:
      - '(?i)bearer\s+[a-z0-9._~+/-]+'
      - '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}'
  batch:

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [redaction/trace_allowlist, batch]
      exporters: [otlp]

Collector distributions do not all include the same processors, and component maturity can change. Confirm that your image contains the processor and that its configuration is valid for the exact release. Put the redaction processor in every relevant pipeline and every export route. A configured processor that is absent from a signal pipeline has no effect. Keep separate redaction policies for logs, traces, and metrics because they have different attribute sets.

Redaction is not a substitute for safe instrumentation. An allowlist for span attributes does not automatically prove that event payloads, log bodies, resource attributes, or data copied into an exporter queue are safe. Read the processor's scope and test the output that actually leaves the process. Minimize at source, then apply filtering at the collector as defense in depth.

Make sensitive data hard to add accidentally

Write an instrumentation policy that names allowed attributes and prohibited data classes. For example, allow a service name, route template, status code, dependency name, and coarse operation label. Prohibit authorization headers, cookies, request and response bodies, raw SQL parameters, payment details, and user-provided strings. Require a review when a new custom attribute is introduced.

Use typed helper functions for custom spans rather than letting every route invent attribute names. A helper can accept a validated event type and a bounded enum for result, then attach only those values. Avoid tenant IDs or user IDs as metric labels because their cardinality can grow with customers. If traces need an account correlation field, use an approved opaque identifier with retention controls and ensure it cannot be used as a credential.

Use allowlists to control HTTP header capture. If you must capture a header, configure a small set and explicitly sanitize values such as authorization, cookie, and session headers. Never use a pattern like .* to capture every request and response header in production. The current FastAPI instrumentation documents a sanitize-fields parameter and matching environment variable; test both request and response paths because they use distinct configuration options.

Measure overhead instead of promising zero overhead

Tracing adds work: span creation, context propagation, attribute collection, sampling, queueing, serialization, and export. A batch processor reduces network calls but uses memory and can drop data when queues fill. A sampler lowers volume but may hide rare failures unless you choose a policy that preserves errors or tail-samples downstream. The right cost depends on route mix, number of spans, attribute sizes, exporter behavior, and concurrent traffic.

Establish a baseline with instrumentation disabled, then compare with instrumentation enabled under the same workload and deployment limits. Measure p50 and p95 request latency, CPU per request, memory, spans per request, exporter queue occupancy, dropped spans, and Collector resource use. Include slow downstream responses, exporter unavailability, and a burst that exercises queue limits. Run long enough to observe memory and batch behavior, and compare cold and warm startup separately.

Set an explicit budget such as “tracing should add no more than the agreed latency and CPU envelope under the production-like load test.” The number should come from your service-level objective and measurements. Do not repeat an unmeasured fixed percentage or call a setup zero overhead. Sampling, dropping attributes, and filtering health checks can lower cost, but validate that the resulting trace still answers the team's common incident questions.

Sampling is not a privacy control. An unsampled request may still generate logs or metrics with sensitive data, and a sampled request can preserve an unsafe attribute. Redact or avoid collecting sensitive values before export, then sample the remaining telemetry to manage volume.

Test the exported telemetry, not only the code path

Put recognizable sentinel values in test credentials and input fields, such as a fake bearer token, fake email address, and synthetic card-like number. Exercise normal requests, validation failures, exceptions, outbound HTTP calls, SQL errors, and response headers. Capture the spans and logs at the exporter boundary, then assert the sentinels do not appear in attributes, span names, events, exception descriptions, resource attributes, or log bodies.

Also test the absence of accidental collection. Send an authorization header while header capture is disabled, then enable the explicit sanitized header configuration in a separate test. Confirm the value is absent or replaced by a redaction marker according to the intended policy. Test the Collector config with the exact distribution and release in CI or a deployment validation job, and verify processor order and signal coverage.

Configuration drift is a security risk. A later dependency update can change semantic conventions, span names, or captured attributes. Pin instrumentation versions, review dependency updates, and run sentinel tests when changing them. OpenTelemetry semantic conventions can evolve; check the attributes emitted by your deployed version rather than assuming a name from a blog post applies forever. OpenTelemetry HTTP span semantic conventions

Keep tracing useful during exporter failures

Instrumentation must not turn an observability outage into an application outage. Use batch export with bounded queues, configure exporter timeouts, and monitor dropped spans. Do not make each user request wait synchronously for a remote trace backend. Decide whether telemetry loss should be fail-open or fail-closed for your environment; typical request tracing should not block application correctness, while audit records that are legally required need a separate durable audit system.

Protect the collector endpoint with network boundaries, TLS, and authentication when it crosses a trust boundary. Limit who can query traces and set retention based on diagnostic need. Telemetry often reveals internal topology, customer identifiers, and incident timing even after obvious secrets are removed. Review vendor retention and data residency settings before exporting production traces.

Track telemetry pipeline health with independent metrics: export failures, queue utilization, rejected spans, processor errors, and collector memory. If your only visibility into telemetry failure uses that same telemetry pipeline, add a health check or external signal. For application logs that need trace correlation without high-cardinality labels, see our guide to structured logging with OpenTelemetry.

Frequently asked questions

Does OpenTelemetry add zero overhead to FastAPI?

No. Creating spans, propagating context, collecting attributes, sampling, and exporting all use CPU, memory, and network capacity. The cost depends on the workload, instrumentations, and sampling and batching configuration. Measure the production-like service with and without tracing, including exporter failures and dropped-span behavior, before setting an overhead budget.

Is Collector redaction enough to keep traces free of secrets?

No. Prevent unsafe values from entering telemetry at the source first. Collector processors provide a secondary filter, and each processor covers specific signals and fields. Test spans, events, logs, metrics, resource attributes, and exporter output for sentinel secrets using the exact Collector distribution and configuration you deploy.

Should I capture authorization headers for debugging?

Usually no. Authorization headers and cookies are credentials and should not be exported. If a reviewed use case requires header capture, allowlist only the required header and configure the instrumentation's sanitization field. Verify that the output contains a redaction marker rather than the original value.

How do I check OpenTelemetry overhead in production?

Compare an instrumented and uninstrumented build under the same production-like workload. Measure request latency percentiles, CPU, memory, spans per request, exporter queue pressure, and dropped spans. Include failure and burst scenarios, then choose sampling and batching settings that meet both the service's telemetry questions and resource budget.

Keep observability inside a deliberate data boundary

OpenTelemetry makes distributed execution easier to inspect, but it cannot decide which attributes are safe for your organization. Define an allowlist, minimize data before span creation, restrict header capture, and apply Collector redaction as a secondary control. Measure overhead with your own traffic and validate the exact telemetry that leaves the service.

If you are instrumenting FastAPI services that handle payment or customer data, talk with our engineering team about building a trace policy, exporter pipeline, and sentinel-data test suite that fit your operational needs.

Dumb Potato Editorial

Putting this into practice?

Share the problem you’re solving and the tradeoffs you’re weighing with our engineering team.

See how we help with cloud and devops

Discuss your project