Skip to content

[FEATURE] Implement Trace ID / Correlation ID propagation across logs, HTTP responses, and Kafka #215

Closed

Description

@aniebietafia

Problem

In a high-concurrency microservice or modular monolith environment, tracing the flow of a single client request through the system is complex. When an exception is thrown internally:

  • It is difficult to distinguish a specific user's execution path from other concurrent operations.
  • Downstream async operations (like Kafka events or scheduled tasks) lose all association with the initiating HTTP request.
  • Clients have no unique identifier to reference when reporting API errors to support team.

Proposed Solution

  1. Implement a Servlet Filter (TraceIdFilter) that checks incoming request headers for a trace ID (X-Correlation-Id or X-Trace-Id). If missing, generate a new UUID.
  2. Put the trace ID in the Mapped Diagnostic Context (MDC) of SLF4J/Logback using the key "traceId".
  3. Propagate the trace ID back to the client in the HTTP response header X-Trace-Id and inside the ApiResponse payload.
  4. Pass the trace ID as a header on any Kafka messages published during the request.
  5. In Kafka consumers, extract the trace ID header, seed the consumer thread's MDC, and clear it upon task completion.

User Stories

  • As a developer, I want to search for a single Trace ID in the log aggregator and see the entire request timeline, including MVC handlers, DB queries, Kafka publishing, and async job executions.
  • As an API client, I want to receive a transaction identifier in the headers so that I can provide it to support if a request fails.

Acceptance Criteria

  • A servlet filter TraceIdFilter generates/propagates a transaction ID per request.
  • The response headers include X-Trace-Id.
  • The MDC contains the key "traceId" throughout the request lifecycle.
  • Logging layouts print the trace ID in all log statements.
  • Kafka producers attach traceId to record headers.
  • Kafka consumers read the header, populate MDC, and log the ID.

Proposed Technical Details

Create a TraceIdFilter.java under src/main/java/com/xtraction/api/shared/filter/:

package com.xtraction.api.shared.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.UUID;

@Component
public class TraceIdFilter implements Filter {
    private static final String TRACE_ID_HEADER = "X-Trace-Id";
    private static final String MDC_KEY = "traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (request instanceof HttpServletRequest httpServletRequest) {
            String traceId = httpServletRequest.getHeader(TRACE_ID_HEADER);
            if (traceId == null || traceId.isBlank()) {
                traceId = UUID.randomUUID().toString();
            }
            MDC.put(MDC_KEY, traceId);
            
            if (response instanceof HttpServletResponse httpServletResponse) {
                httpServletResponse.setHeader(TRACE_ID_HEADER, traceId);
            }
        }
        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove(MDC_KEY);
        }
    }
}

Update Logback configuration or application.properties logging pattern:

logging.pattern.level=%5p [${spring.application.name:},%X{traceId:-}]

Tasks

  • Implement TraceIdFilter.java and configure it in the filter pipeline.
  • Add traceId field to the unified response object.
  • Update logging.pattern.level (or file appenders) to output %X{traceId}.
  • Write a Kafka Producer Interceptor or configure a custom KafkaTemplate that copies MDC traceId into Kafka record headers.
  • Create a Kafka Aspect or Listener Container Customizer to parse traceId and bind to consumer MDC.

Open Questions / Considerations

  • Should we use Spring Cloud Sleuth / Micrometer Tracing? For a standard Boot 3+ project, Micrometer Tracing is the modern choice. However, a custom filter is lightweight and avoids bringing in extra dependencies.

Activity

  1. added
    bug
    enhancement
    on Jun 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    apibugcidependenciesenhancementocrquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions