Never export unredacted spans from your app and hope the SaaS vendor filters them later! Scrubbing must happen inside your VPC—either in a custom Python SpanProcessor (zero infra changes) or at the OpenTelemetry Collector (transform processor) before OTLP egress.
1. Custom Python PiiScrubbingSpanProcessor (Zero Response Latency)
Because BatchSpanProcessor runs on a background thread, wrapping it with a delegating SpanProcessor scrubs on_end() attributes off the hot FastAPI request path:
import re
from opentelemetry.sdk.trace import SpanProcessor, ReadableSpan
EMAIL_RE = re.compile(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+")
SSN_RE = re.compile(r"\d{3}-\d{2}-\d{4}")
def scrub_pii(val: str) -> str:
val = EMAIL_RE.sub("[REDACTED_EMAIL]", val)
val = SSN_RE.sub("[REDACTED_SSN]", val)
return val
class PiiScrubbingSpanProcessor(SpanProcessor):
def __init__(self, downstream: SpanProcessor):
self.downstream = downstream
def on_start(self, span, parent_context=None):
self.downstream.on_start(span, parent_context)
def on_end(self, span: ReadableSpan):
# Scrub mutable _attributes dict before BatchSpanProcessor exports to Datadog
if hasattr(span, "_attributes") and span._attributes:
for k, v in list(span._attributes.items()):
if isinstance(v, str) and ("prompt" in k or "tool" in k or "input" in k):
span._attributes[k] = scrub_pii(v)
self.downstream.on_end(span)
def shutdown(self):
self.downstream.shutdown()
def force_flush(self, timeout_millis: int = 30000):
return self.downstream.force_flush(timeout_millis)
2. Defense-in-Depth: OpenTelemetry Collector transform Processor
Also add replace_pattern rules inside your VPC's otel-collector-config.yaml so even third-party library spans (like httpx or sqlalchemy) get scrubbed before leaving your AWS VPC for Datadog.