Prompt
How do I trace database calls inside a microservices request
Latest observation
To trace database calls inside a microservices request, you generally want distributed tracing with context propagation so the same request can be followed from the edge service down to the database layer.
1) Use a trace/span model
A request gets a trace ID. Each operation inside it gets a span ID.
Example flow:
- API Gateway receives request → creates trace
- Service A handles request → span
- Service A calls Service B → child span
- Service B queries DB → DB span
That lets you see the full path and timing.
2) Propagate context across service boundaries
When Service A calls Service B, include tracing headers in the outbound request.
Common standard:
- W3C Trace Context:
traceparent,tracestate
Many tracing systems also support baggage or vendor-specific headers.
3) Instrument your services
Add tracing instrumentation to:
- incoming HTTP/gRPC handlers
- outbound HTTP/gRPC clients
- database client libraries
- message queues if used
Common tools:
- OpenTelemetry for instrumentation
- Jaeger, Zipkin, Grafana Tempo, Datadog, New Relic, Honeycomb for visualization/backend
4) Make DB calls create child spans
Your DB client instrumentation should create a span around each query or transaction.
Span data should include:
- query operation name
- database name/type
- table or logical operation
- duration
- error status
- row count if safe/appropriate
Avoid logging raw sensitive SQL if it may contain PII/secrets; use sanitized statements or operation names.
5) Correlate logs with traces
Also add the trace ID to application logs. Then you can jump from a trace to the exact logs for that request.
Typical pattern:
- log line includes
trace_idandspan_id - tracing UI links to logs
6) If you want to trace a specific request manually
Check whether your request ID or trace headers are:
- incoming at the edge
- passed between services
- present in DB span metadata
If not, the missing piece is usually context propagation or missing instrumentation in the DB client.
7) Example with OpenTelemetry
High-level idea:
- start a span at request entry
- call downstream services with injected trace context
- instrument the DB driver so queries become spans automatically
If you’re using a language/framework:
- Java: OpenTelemetry Java agent
- Node.js: OpenTelemetry SDK/instrumentation packages
- Python: OpenTelemetry instrumentation libs
- Go: OpenTelemetry SDK + instrumented DB/http clients
- .NET: OpenTelemetry + automatic instrumentation
8) Best practices
- Use automatic instrumentation where possible
- Name spans consistently
- Keep span attributes small and non-sensitive
- Sample intelligently in high-traffic systems
- Trace only what you need in production to limit overhead
If you want, I can show:
- an OpenTelemetry example for your language, or
- how to trace HTTP request → service → database query end-to-end.