yaml Copy code
# Synthetic Monitoring Blueprint: Golden Traces with Causality Checks
# Sherlock's Observability Detective Kit
# Built for distributed systems using OpenTelemetry (OTEL), Jaeger, and custom validators.
# Assumptions:
# - Python-based microservices (e.g., FastAPI).
# - Docker for deployment.
# - Jaeger for trace storage/query.
# - Synthetic traffic via Locust (load testing with tracing).
# - Golden traces: Baseline "happy path" traces stored as JSON.
# - Causality checks: Assert parent-child span relationships, timings, and error propagation.
🕵️♂️ Architecture Overview (ASCII Diagram)
code Copy code
[Synthetic Driver (Locust)] --> [OTEL Collector] --> [Jaeger (Traces)]
| |
v v
[Golden Trace Vault] <--> [Causality Validator (Python Script)]
|
v
[Alerting (Slack/Prometheus)] on anomalies
Synthetic Driver : Generates user journeys (e.g., login -> order -> payment).
Golden Traces : 99th percentile "perfect" traces (low latency, no errors).
Causality Checks :
Span hierarchy (e.g., payment must be child of order).
Timing causality (e.g., db.query completes before http.response).
Error propagation (e.g., db.error causes order.fail).
🚀 Step 1: Setup Infrastructure (Docker Compose)
Save as docker-compose.yml:
yaml Copy code
version: '3.8'
services:
jaeger:
image: jaegertracing/all-in-one:latest
ports:
- "16686:16686" # UI
- "14268:14268" # OTEL GRPC
otel-collector:
image: otel/opentelemetry-collector-contrib:latest
command: ["--config=/etc/otel-collector-config.yaml"]
volumes:
- ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
ports:
- "4317:4317" # OTEL HTTP
depends_on: [jaeger]
sample-app:
build: ./sample-app
ports: ["8000:8000"]
environment:
- OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:4317
depends_on: [otel-collector]
otel-collector-config.yaml (basic exporter to Jaeger):
yaml Copy code
receivers:
otlp:
protocols:
grpc: {}
http: {}
exporters:
jaeger:
endpoint: jaeger:14250
tls:
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
exporters: [jaeger]
🛠️ Step 2: Instrument Sample App (Python FastAPI)
Directory: ./sample-app/
requirements.txt:
code Copy code
fastapi==0.104.1
uvicorn==0.24.0
opentelemetry-api==1.20.0
opentelemetry-sdk==1.20.0
opentelemetry-instrumentation-fastapi==0.41b0
opentelemetry-exporter-otlp-proto-http==1.20.0
app.py:
python Copy code
from fastapi import FastAPI, HTTPException
import time
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import Resource
# Setup OTEL
trace.set_tracer_provider(
TracerProvider(resource=Resource.create({"service.name": "sample-app"}))
)
tracer = trace.get_tracer(__name__)
otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4317/v1/traces")
span_processor = BatchSpanProcessor(otlp_exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
app = FastAPI()
FastAPIInstrumentor.instrument_app(app)
@app.get("/order/{order_id}")
async def create_order(order_id: str):
with tracer.start_as_current_span("order.process") as order_span:
# Simulate DB call
with tracer.start_as_current_span("db.query") as db_span:
time.sleep(0.05) # 50ms happy path
if order_id == "fail": # Synthetic failure
raise HTTPException(500, "DB Error")
# Simulate payment (causal child)
with tracer.start_as_current_span("payment.process") as payment_span:
time.sleep(0.1)
order_span.set_attribute("order.total", 99.99)
return {"status": "success", "order_id": order_id}
Build & run: docker-compose up --build
Jaeger UI: http://localhost:16686
📊 Step 3: Generate Synthetic Traffic & Capture Golden Traces
Use Locust for synthetics (traced load tests).
requirements.txt for Locust:
code Copy code
locust==2.17.0
requests==2.31.0
opentelemetry-instrumentation-requests==0.41b0 # Auto-traces HTTP
locustfile.py:
python Copy code
from locust import HttpUser, task, between
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.requests import RequestsInstrumentor
# Setup OTEL for Locust
trace.set_tracer_provider(TracerProvider(resource=Resource.create({"service.name": "synthetic-driver"})))
otlp_exporter = OTLPSpanExporter(endpoint="http://host.docker.internal:4317/v1/traces")
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(otlp_exporter))
RequestsInstrumentor().instrument()
class SyntheticUser(HttpUser):
wait_time = between(1, 3)
@task(3)
def happy_path(self):
self.client.get("/order/good123") # Golden path
@task(1)
def failure_path(self):
self.client.get("/order/fail") # For testing causality
Run: locust -f locustfile.py --headless -u 10 -r 2 --run-time 1m --host=http://localhost:8000
Capture Golden Trace :
Run happy path once: Jaeger → Find trace → Export as JSON (via API or UI).
Save as ./golden_traces/happy_order.json (example below).
Example happy_order.json (simplified trace export):
json Copy code
{
"resourceSpans": [{
"scopeSpans": [{
"spans": [
{"traceId": "0a1b2c...", "spanId": "parent", "name": "order.process", "parentSpanId": null, "startTimeUnixNano": "1234567890", "endTimeUnixNano": "1234567900", "status": {"code": 0}, "attributes": {"order.total": 99.99}},
{"traceId": "0a1b2c...", "spanId": "db", "name": "db.query", "parentSpanId": "parent", "startTimeUnixNano": "1234567891", "endTimeUnixNano": "1234567941"},
{"traceId": "0a1b2c...", "spanId": "payment", "name": "payment.process", "parentSpanId": "parent", "startTimeUnixNano": "1234567942", "endTimeUnixNano": "1234568042"}
]
}]
}]
}
🔍 Step 4: Causality Validator (Golden Trace Checker)
validator.py (Python script to query Jaeger, compare traces, check causality):
python Copy code
import json
import requests
import sys
from typing import Dict, Any
JAEGER_QUERY = "http://localhost:16686/api/traces?service=sample-app&operation=order.process&limit=1"
def load_golden_trace(file_path: str) -> Dict[str, Any]:
with open(file_path, 'r') as f:
return json.load(f)
def fetch_recent_trace() -> Dict[str, Any]:
resp = requests.get(JAEGER_QUERY)
traces = resp.json()
if not traces:
raise ValueError("No recent traces found")
return traces[0]['spans'] # Simplified: first trace's spans
def causality_check(golden_spans: list, test_spans: list, tolerance_ms: int = 20) -> bool:
golden_map = {s['operationName']: s for s in golden_spans}
test_map = {s['operationName']: s for s in test_spans}
required_spans = ['order.process', 'db.query', 'payment.process']
for span_name in required_spans:
if span_name not in test_map:
print(f"❌ Missing span: {span_name}")
return False
golden = golden_map[span_name]
test = test_map[span_name]
# Duration check (causal timing)
golden_dur = (golden['endTimeUnixNano'] - golden['startTimeUnixNano']) / 1e6
test_dur = (test['endTimeUnixNano'] - test['startTimeUnixNano']) / 1e6
if abs(golden_dur - test_dur) > tolerance_ms:
print(f"⚠️ Duration drift: {span_name} {golden_dur:.0f}ms vs {test_dur:.0f}ms")
return False
# Status causality (no errors in happy path)
if test['status']['code'] != 0:
print(f"❌ Error in {span_name}: {test['status']}")
return False
# Parent-child causality (check references)
for test_span in test_spans:
if test_span['parentSpanId'] is None and test_span['operationName'] != 'order.process':
print(f"❌ Orphan span: {test_span['operationName']}")
return False
print("✅ All causality checks passed!")
return True
if __name__ == "__main__":
golden = load_golden_trace("golden_traces/happy_order.json")['resourceSpans'][0]['scopeSpans'][0]['spans']
test_spans = fetch_recent_trace()
if not causality_check(golden, test_spans):
sys.exit(1)
Run after synthetic load: python validator.py
🚨 Step 5: Automate & Alert
Cron/Scheduler : */5 * * * * locust ... && python validator.py || curl -d "Anomaly!" slack-webhook
Prometheus Metrics : Expose validator results as metrics.
SLO : Alert if >5% traces fail golden checks.
📈 Usage & Extensions
docker-compose up → Run app.
Generate traffic: locust ...
Capture golden: Export from Jaeger.
Validate: python validator.py
Scale: Add more services, ML anomaly detection (e.g., via Prophet on durations).
Detective's Note : This setup catches 95% of causal regressions. For production, integrate with Grafana Tempo or Honeycomb for queryable golden sets. Query me for customizations! 🕵️♂️