Microservices Logging with Correlation IDs in Spring Boot

Learn how to implement correlation IDs in Spring Boot microservices using MDC, servlet filters, Feign interceptors, and structured logging.

Reading Time: 8 min readAuthor: DeepTechHub
Microservices Logging with Correlation IDs in Spring Boot

Audio controls for Microservices Logging with Correlation IDs in Spring Boot

Listen to this article

Introduction

When a request passes through multiple microservices, investigating a failure can mean searching logs across several applications. Each service records its own events, and timestamps alone may not make it obvious which log entries belong to the same request.

A correlation ID helps solve this problem by giving related operations a shared identifier. When that identifier is included in log records across services, developers can search for it to follow a request through the application.

For example, a request handled by task-service might trigger a call to identity-service. If both services log the same correlation ID, their log entries can be connected even when they are stored separately.

task-service
correlationId=abc-123  Fetching task details
 
identity-service
correlationId=abc-123  Looking up user information

These entries are illustrative, but they show the key idea: one identifier makes related log records easier to find.

A correlation ID is not the same as distributed tracing. It helps associate log entries, but it does not automatically provide trace and span relationships, timing information, or a complete view of a request's execution.

In this tutorial, we'll examine how the DeepTechHub project implements correlation IDs using Spring Boot, SLF4J's Mapped Diagnostic Context (MDC), and Spring Cloud OpenFeign.

The project has three relevant modules:

  • task-service handles task management and makes synchronous calls to identity-service.
  • identity-service handles authentication and user management.
  • common-lib contains shared logging utilities, including the correlation ID filter and constants.

The audited repository does not contain an API Gateway, so the implementation described here focuses on the two application services.

How correlation IDs flow between services

Below diagram shows how correlation ID flows between the services to provide tracebility.

The implementation follows a simple sequence:

  1. A client sends an HTTP request to task-service, optionally including an X-Correlation-ID header.
  2. The service's servlet filter reuses a nonblank supplied ID or generates a UUID when the header is missing or blank.
  3. The filter places the ID in MDC and adds it to the HTTP response.
  4. When task-service calls identity-service through Feign, an interceptor forwards the ID if it is present in MDC.
  5. The filter in identity-service establishes the received ID in its own request-thread MDC.

Both services can then include the same identifier in their log records, provided their logging configuration includes the MDC value.

The following diagram illustrates the source-code flow; it is not a captured runtime trace.

The diagram represents the synchronous service-to-service path in this project. An API Gateway could establish or validate correlation IDs at a trusted ingress point in a different architecture, but that component is not implemented here.

Implementing correlation IDs in Spring Boot

The implementation uses three main pieces:

  • A servlet filter to establish the ID for an incoming request and expose it in the response.
  • MDC to make the ID available to logging statements on the request-handling thread.
  • A Feign interceptor and Logback configuration to forward the ID to another service and include it in structured log output.

Let's examine each part and how it works in the project.

Shared constants and dependencies

CommonApplicationConstants defines the header and MDC key used by the filter and Feign interceptor:

java
public final class CommonApplicationConstants {
    public static final String CORRELATION_ID_HEADER = "X-Correlation-ID";
    public static final String CORRELATION_ID_MDC_KEY = "correlationId";
 
    private CommonApplicationConstants() {}
}

The shared module is not Spring-free. Its POM includes Spring Context, Spring Boot Autoconfigure, Spring Web, the Jakarta Servlet API, SLF4J, and Apache Commons Lang. At the audited commit, the parent POM targets Java 21, manages Spring Boot 3.4.5 and Spring Cloud 2024.0.1, and manages the shared dependency versions. The services use Spring Boot web starters; task-service also includes Spring Cloud OpenFeign. Refer to the project POM for the complete dependency configuration.

Add the ID to the request logging context

CorrelationIdFilter extends Spring's OncePerRequestFilter. It reads X-Correlation-ID, generates a UUID when the header is missing or blank, places the selected value in MDC, and adds it to the response. The finally block removes the MDC entry after the remaining filter chain completes, including when that chain throws.

MDC is a logging context associated with the current thread. A compatible logging configuration can read the correlationId key while code handles the request, so application log statements can carry the same value without passing it through every logging call.

The core of the implementation is:

java
String correlationId = request.getHeader(
    CommonApplicationConstants.CORRELATION_ID_HEADER
);
if (StringUtils.isBlank(correlationId)) {
    correlationId = UUID.randomUUID().toString();
}
 
MDC.put(CommonApplicationConstants.CORRELATION_ID_MDC_KEY, correlationId);
response.addHeader(CommonApplicationConstants.CORRELATION_ID_HEADER, correlationId);
 
try {
    filterChain.doFilter(request, response);
} finally {
    MDC.remove(CommonApplicationConstants.CORRELATION_ID_MDC_KEY);
}

This excerpt assumes the servlet request, response, filter chain, and imports from the project class. The current filter accepts any nonblank caller-supplied value without application-level character or length validation. A supplied value is reused, so it is not guaranteed to be unique. Also, response.addHeader occurs before the try block in the source; cleanup is therefore not guaranteed if adding the response header itself throws. These are implementation details, not guarantees of the MDC API.

In a deployment that accepts IDs from outside a trusted network boundary, decide whether to validate their length and characters or replace them at a trusted ingress point. This project does not implement such a trust policy.

Register the filter in each service

Each service has a LoggingConfig that registers the filter for /*:

java
FilterRegistrationBean<CorrelationIdFilter> registration =
    new FilterRegistrationBean<>();
registration.setFilter(new CorrelationIdFilter());
registration.addUrlPatterns("/*");
registration.setOrder(1);

This shows the registration settings used by both services. Although the filter class also has @Order(Ordered.HIGHEST_PRECEDENCE), the service configurations manually instantiate the filter and set the registration order to 1; the class annotation does not set the order of that registration. The source therefore does not establish that the filter runs before Spring Security filters.

The filter class also has @Component. The services' default component-scan roots are their own service packages, not com.deeptechhub.common, so the audit found no second component registration in this setup. Avoid broadening scanning without reviewing filter registration, since Spring Boot can automatically register servlet Filter beans as well as explicitly configured registrations.

Forward the ID through Feign

task-service defines a RequestInterceptor that reads the current MDC value and adds it to outbound Feign requests when it is present:

java
@Bean
public RequestInterceptor correlationInterceptor() {
    return template -> {
        String correlationId = MDC.get(
            CommonApplicationConstants.CORRELATION_ID_MDC_KEY
        );
        if (correlationId != null) {
            template.header(
                CommonApplicationConstants.CORRELATION_ID_HEADER,
                correlationId
            );
        }
    };
}

The constants class is CommonApplicationConstants. If the MDC value is absent, this interceptor does not add the header. This code reads MDC on the calling thread; it does not propagate context automatically to asynchronous executors, message consumers, or other threads.

Include MDC in Logback output

Each service has a logback-spring.xml with a LogstashEncoder. The configuration enables MDC inclusion and adds the service name as a custom JSON field:

xml
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
    <includeContext>false</includeContext>
    <includeMdc>true</includeMdc>
    <customFields>{"service":"${appName}"}</customFields>
</encoder>

With the encoder's default field names, an illustrative log event can include fields such as:

json
{
  "@timestamp": "illustrative timestamp",
  "level": "INFO",
  "service": "task-service",
  "correlationId": "illustrative-id",
  "message": "Handling request"
}

This payload is illustrative, not captured output; the encoder may emit additional fields. Its default timestamp field is @timestamp. The source config also has profile-specific root logger declarations alongside an unconditional root declaration in both services' files. Validate the active profile configuration by starting the application before relying on its logging behavior; the services were not started for this article audit.

Tests to add

The audited repository did not contain correlation-specific tests for the filter, response header, cleanup, or Feign propagation. The following are useful cases to add; they are test scenarios, not existing or passing tests:

  • Send a request with X-Correlation-ID and assert that the response contains the same value.
  • Send a request without the header and assert that the response contains a generated, nonblank value.
  • Verify that a log event emitted during request handling has the expected correlationId MDC value.
  • Verify that the MDC key is removed after both normal completion and an exception from the downstream filter chain.
  • Invoke the Feign interceptor with an ID in MDC and assert that it adds the header; invoke it without the MDC value and assert that it does not add one.

The original article's MockMvc example is a suggested test shape, not a test found in the project. A separate test should cover Feign request-template behavior rather than inferring downstream propagation from a response-header assertion.

Limitations and next steps

Correlation IDs connect log records that share an identifier. Distributed tracing adds separate trace and span context, timing, and relationships between operations; a correlation ID alone does not provide those capabilities. The current repository also does not show automatic MDC propagation to asynchronous work.

For a production system, define which boundary is trusted to supply IDs, validate or regenerate external values according to that policy, and explicitly propagate logging context across thread boundaries where needed. A gateway or tracing instrumentation could be added as the architecture evolves, but neither is implemented by this project. Review the profile-specific Logback setup at application startup and add focused tests for the filter and Feign interceptor before relying on those behaviors.

Conclusion

This implementation uses a servlet filter to establish a per-request MDC value, returns the value in a response header, and forwards it through synchronous Feign calls when it is present on the task-service request thread. Shared constants keep the header and MDC key consistent across the filter and interceptor. Correlation IDs make related log records easier to find, while validation, trust boundaries, asynchronous context propagation, and full distributed tracing require additional design and verification.

The source reviewed for this tutorial is available at commit 084db27.

Did you find this article useful?