wasAsked.

How would you add distributed tracing, structured logging, and correlation IDs across Java microservices?

Flipkart · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Microservices, Software Engineering

Community answers

Posted by wasAsked editorial collection

Use OpenTelemetry for traces, structured JSON logs that include trace IDs, and W3C trace context propagation everywhere. Distributed tracing - Spring Boot 3: Micrometer Tracing with the OpenTelemetry bridge (micrometer-tracing-bridge-otel plus an OTLP exporter), or the OpenTelemetry Java agent, which auto-instruments Spring MVC, WebClient and RestClient, JDBC, Kafka, gRPC and more without code changes. - W3C traceparent headers propagate trace context across HTTP calls automatically. - Messaging: Kafka and RabbitMQ instrumentation puts trace context into message headers so consumers continue the same trace. - Add custom spans for important business steps (Observation API or @Observed, or the OpenTelemetry API). - Export to an OpenTelemetry Collector, then Jaeger, Grafana Tempo, Zipkin or a commercial APM; use sampling (head or tail-based) to control cost. Structured logging - JSON logs (Spring Boot 3.4+ supports structured logging formats such as ECS and Logstash natively, or use logstash-logback-encoder). - Micrometer Tracing puts traceId and spanId into the MDC, so every log line includes them; Spring Boot's default log pattern includes them automatically when tracing is active. - Log with parameters and stable field names: log.info("Payment captured orderId={} amount={}", id, amount), or with structured key-value arguments. - Add business context to the MDC carefully (tenantId, orderId) and clear it after the request. Never log secrets, tokens or full personal data. - Ship logs centrally (ELK or OpenSearch, Grafana Loki, a cloud logging service). Correlation IDs - Prefer the W3C trace ID as the correlation ID across services. If an external correlation header (X-Correlation-ID) is required, accept it at the gateway, propagate it, and return the trace ID in responses and Problem Details. - Be careful with thread hand-offs (@Async, CompletableFuture executors, virtual threads): use context-propagating executors (Micrometer's ContextSnapshot or Spring's TaskDecorator) so MDC and trace context follow the work. Metrics and alerting - Micrometer metrics (RED: rate, errors, duration) exported to Prometheus and Grafana; exemplars link metric spikes to traces. - SLO-based alerts rather than alerting on every error. Result: from one failed request you can see the full trace across services, jump to the related logs, and find the slow or failing dependency quickly.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics