Definition
- Correlation ID is a unique string (typically a UUID) attached to a request at the API gateway or first service, propagated to every downstream service, and included in every log line for that request.
- MDC (Mapped Diagnostic Context) is a thread-local key-value store in SLF4J/Logback that automatically appends fields like correlationId to every log statement without changing the log call itself.
- X-Correlation-ID is the HTTP header used to carry the correlation ID between services.
- OpenTelemetry is a vendor-neutral observability framework that provides traceId, spanId, and parent-child span relationships for distributed tracing.
- Structured logging means outputting log lines as JSON objects instead of plain text, making fields like correlationId searchable in log aggregation tools.
Think of a wire transfer at National Bank of India. When Priya initiates a transfer from SAV2001, the teller stamps a tracking number (correlation ID) on the form. The form goes to the verification desk, then to the settlement desk, then to the notification desk. Each desk writes the tracking number on their own logbook entry. If Priya calls to ask why the transfer failed, the manager searches for one tracking number and finds every logbook entry from every desk, in order. That tracking number is the correlation ID, and the logbooks are your service logs.
Understanding the Concepts
What is distributed tracing?
Distributed tracing is the practice of tracking a single user request as it flows through multiple microservices. Each service logs its own activity, but without a shared identifier, there is no way to connect log lines from service A to log lines from service B for the same request.
A correlation ID solves this. It is a unique string (usually a UUID) that is generated when the request first enters the system. Every service that handles the request includes this ID in its log output. When something goes wrong, you search for that one ID and see the complete story across all services.
Without correlation ID:
account-service: INFO Balance check for SAV2001
transfer-service: ERROR Transfer failed: insufficient balance
notification-svc: INFO Email sent to priya@nationalbank.in
Question: Which balance check caused which failure?
Answer: You cannot tell. Hundreds of requests per second.
With correlation ID:
account-service: INFO [corr=a1b2c3d4] Balance check for SAV2001
transfer-service: ERROR [corr=a1b2c3d4] Transfer failed: insufficient balance
notification-svc: INFO [corr=a1b2c3d4] Email sent to priya@nationalbank.in
Search "a1b2c3d4" and you see the full request path.
Why do we need correlation IDs in microservices?
In a monolith, a single request produces log lines in one application. You can read the log file top to bottom and follow the flow. In a microservices architecture, a single user request might touch 5 to 10 services, each writing to its own log stream.
At National Bank of India, when Rajesh transfers money from SAV2001 to SAV3002, the request flows through:
- API Gateway (authentication, rate limiting)
- transfer-service (validates transfer, debits source)
- account-service (checks balance, updates ledger)
- notification-service (sends SMS/email to Priya)
- audit-service (records the transaction for compliance)
If the transfer fails at step 3, you need to see what happened in steps 1 through 3. Without a correlation ID, you search for "SAV2001" and get thousands of results from all requests involving that account. A correlation ID narrows it to exactly one request.
package com.bank.common;
import java.util.UUID;
public final class CorrelationId {
public static final String HEADER_NAME = "X-Correlation-ID";
public static final String MDC_KEY = "correlationId";
private CorrelationId() {}
public static String generate() {
return UUID.randomUUID().toString().replace("-", "").substring(0, 12);
}
}
Example correlation IDs:
a1b2c3d4e5f6
7f8e9d0c1b2a
3c4d5e6f7a8b
Short (12 hex chars) for readability in logs.
Full UUIDs work too but are harder to read.
How does MDC (Mapped Diagnostic Context) work?
MDC is a feature of SLF4J and Logback that stores key-value pairs in a thread-local map. Once you put a key into MDC, every log statement on that thread automatically includes it in the log output (if your log pattern references it).
This is how you avoid passing the correlation ID as a method parameter through every layer of your code. You set it once in a filter, and every logger on that thread includes it.
package com.bank.tracing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class MdcDemo {
private static final Logger log = LoggerFactory.getLogger(MdcDemo.class);
public static void main(String[] args) {
// Put correlation ID into MDC
MDC.put("correlationId", "a1b2c3d4e5f6");
// Every log call now includes correlationId automatically
log.info("Processing transfer for account SAV2001");
log.info("Balance check passed: 75000.00");
log.warn("Transfer amount exceeds daily limit");
// Always clear MDC when done (prevents leaks in thread pools)
MDC.clear();
}
}
# Logback pattern: %X{correlationId} reads from MDC
# logback-spring.xml pattern:
# %d{HH:mm:ss} [%X{correlationId}] %-5level %logger{36} - %msg%n
Output:
10:30:01 [a1b2c3d4e5f6] INFO c.b.tracing.MdcDemo - Processing transfer for account SAV2001
10:30:01 [a1b2c3d4e5f6] INFO c.b.tracing.MdcDemo - Balance check passed: 75000.00
10:30:01 [a1b2c3d4e5f6] WARN c.b.tracing.MdcDemo - Transfer amount exceeds daily limit
How do you implement a CorrelationIdFilter in Spring Boot?
The filter runs on every incoming HTTP request. It reads the X-Correlation-ID header (from an upstream service or API gateway). If the header is missing, it generates a new ID. It puts the ID into MDC, processes the request, and clears MDC afterward.
package com.bank.tracing;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorrelationIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String correlationId = request.getHeader(CorrelationId.HEADER_NAME);
if (correlationId == null || correlationId.isBlank()) {
correlationId = CorrelationId.generate();
}
// Put into MDC so every log line includes it
MDC.put(CorrelationId.MDC_KEY, correlationId);
// Add to response header so the caller can see it
response.setHeader(CorrelationId.HEADER_NAME, correlationId);
try {
filterChain.doFilter(request, response);
} finally {
// Always clear MDC to prevent leaks in thread pools
MDC.remove(CorrelationId.MDC_KEY);
}
}
}
Incoming request: POST /api/transfers
Header: X-Correlation-ID: (not present)
Filter generates: a1b2c3d4e5f6
MDC: {correlationId=a1b2c3d4e5f6}
Response header: X-Correlation-ID: a1b2c3d4e5f6
All log lines during this request:
10:30:01 [a1b2c3d4e5f6] INFO TransferController - Transfer request received
10:30:01 [a1b2c3d4e5f6] INFO TransferService - Validating transfer SAV2001 -> SAV3002
10:30:02 [a1b2c3d4e5f6] INFO TransferService - Transfer completed successfully
How do you propagate correlation IDs with RestClient?
When transfer-service calls account-service, it must pass the correlation ID in the X-Correlation-ID header. A RestClient interceptor reads the ID from MDC and adds it to every outgoing request.
package com.bank.tracing;
import org.slf4j.MDC;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
public class CorrelationIdInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(
HttpRequest request,
byte[] body,
ClientHttpRequestExecution execution) throws IOException {
String correlationId = MDC.get(CorrelationId.MDC_KEY);
if (correlationId != null) {
request.getHeaders().set(CorrelationId.HEADER_NAME, correlationId);
}
return execution.execute(request, body);
}
}
package com.bank.config;
import com.bank.tracing.CorrelationIdInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestClient;
@Configuration
public class RestClientConfig {
@Bean
public RestClient accountServiceClient() {
return RestClient.builder()
.baseUrl("http://localhost:8081")
.requestInterceptor(new CorrelationIdInterceptor())
.build();
}
}
package com.bank.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.math.BigDecimal;
@Service
public class TransferService {
private static final Logger log = LoggerFactory.getLogger(TransferService.class);
private final RestClient accountServiceClient;
public TransferService(RestClient accountServiceClient) {
this.accountServiceClient = accountServiceClient;
}
public void transfer(String fromAccount, String toAccount, BigDecimal amount) {
log.info("Starting transfer: {} -> {} amount={}", fromAccount, toAccount, amount);
// This call includes X-Correlation-ID automatically
BigDecimal balance = accountServiceClient.get()
.uri("/api/accounts/{id}/balance", fromAccount)
.retrieve()
.body(BigDecimal.class);
if (balance.compareTo(amount) < 0) {
log.error("Insufficient balance: available={} required={}", balance, amount);
throw new RuntimeException("Insufficient balance for account " + fromAccount);
}
log.info("Transfer completed successfully");
}
}
transfer-service logs:
10:30:01 [a1b2c3d4e5f6] INFO TransferService - Starting transfer: SAV2001 -> SAV3002 amount=25000
10:30:02 [a1b2c3d4e5f6] INFO TransferService - Transfer completed successfully
account-service logs (same correlation ID propagated):
10:30:01 [a1b2c3d4e5f6] INFO AccountController - Balance request for SAV2001
10:30:01 [a1b2c3d4e5f6] INFO AccountService - Balance for SAV2001: 75000.00
How do you configure structured JSON logging?
Plain text logs work for reading on a terminal. In production, log aggregation tools (Elasticsearch/Kibana, Grafana Loki) need structured JSON so they can index fields like correlationId, level, and service name.
Use the Logstash Logback encoder to output JSON logs.
<!-- pom.xml --syn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>net.logstash.logbacksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>logstash-logback-encodersyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>7.4syn-kw"></versionsyn-kw">>
syn-kw"></dependencysyn-kw">>
<!-- src/main/resources/logback-spring.xml --syn-kw">>
syn-kw"><configurationsyn-kw">>
syn-kw"><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"syn-kw">>
syn-kw"><encoder class="net.logstash.logback.encoder.LogstashEncoder"syn-kw">>
syn-kw"><includeMdcKeyNamesyn-kw">>correlationIdsyn-kw"></includeMdcKeyNamesyn-kw">>
syn-kw"><customFieldssyn-kw">>
{"service":"transfer-service","environment":"production"}
syn-kw"></customFieldssyn-kw">>
syn-kw"></encodersyn-kw">>
syn-kw"></appendersyn-kw">>
syn-kw"><root level="INFO"syn-kw">>
syn-kw"><appender-ref ref="CONSOLE" /syn-kw">>
syn-kw"></rootsyn-kw">>
syn-kw"></configurationsyn-kw">>
JSON log output (one line per log event, formatted here for readability):
{
"@timestamp": "2025-01-15T10:30:01.234Z",
"level": "INFO",
"logger_name": "com.bank.service.TransferService",
"message": "Starting transfer: SAV2001 -> SAV3002 amount=25000",
"correlationId": "a1b2c3d4e5f6",
"service": "transfer-service",
"environment": "production",
"thread_name": "http-nio-8082-exec-3"
}
{
"@timestamp": "2025-01-15T10:30:02.567Z",
"level": "ERROR",
"logger_name": "com.bank.service.TransferService",
"message": "Insufficient balance: available=3000.00 required=25000",
"correlationId": "a1b2c3d4e5f6",
"service": "transfer-service",
"environment": "production",
"thread_name": "http-nio-8082-exec-3"
}
In Kibana, you search correlationId: "a1b2c3d4e5f6" and see every log line from every service for that request.
How do you trace a failed transfer across services?
Here is a complete scenario. Priya tries to transfer 25,000 from SAV2001 to SAV3002. The transfer fails because of insufficient balance. Using the correlation ID, the support team reconstructs the full request path.
package com.bank.controller;
import com.bank.service.TransferService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
@RestController
@RequestMapping("/api/transfers")
public class TransferController {
private static final Logger log = LoggerFactory.getLogger(TransferController.class);
private final TransferService transferService;
public TransferController(TransferService transferService) {
this.transferService = transferService;
}
@PostMapping
public ResponseEntity<String> createTransfer(
@RequestParam String from,
@RequestParam String to,
@RequestParam BigDecimal amount) {
log.info("Transfer request: {} -> {} amount={}", from, to, amount);
try {
transferService.transfer(from, to, amount);
return ResponseEntity.ok("Transfer successful");
} catch (RuntimeException ex) {
log.error("Transfer failed: {}", ex.getMessage());
return ResponseEntity.badRequest().body(ex.getMessage());
}
}
}
Step-by-step trace using correlation ID a1b2c3d4e5f6:
1. transfer-service (port 8082):
10:30:01 [a1b2c3d4e5f6] INFO TransferController - Transfer request: SAV2001 -> SAV3002 amount=25000
10:30:01 [a1b2c3d4e5f6] INFO TransferService - Starting transfer: SAV2001 -> SAV3002 amount=25000
2. account-service (port 8081, called by transfer-service):
10:30:01 [a1b2c3d4e5f6] INFO AccountController - Balance request for SAV2001
10:30:01 [a1b2c3d4e5f6] INFO AccountService - Balance for SAV2001: 3000.00
3. transfer-service (continues after account-service responds):
10:30:02 [a1b2c3d4e5f6] ERROR TransferService - Insufficient balance: available=3000.00 required=25000
10:30:02 [a1b2c3d4e5f6] ERROR TransferController - Transfer failed: Insufficient balance for account SAV2001
Search "a1b2c3d4e5f6" in Kibana: 6 log lines, complete story,
from request entry to failure response.
How is MDC-based tracing different from OpenTelemetry?
| Feature | MDC + Correlation ID | OpenTelemetry |
|---|---|---|
| What it provides | One ID shared across all services for a request | traceId, spanId, parent-child span relationships |
| Dependency graph | No, flat list of log lines | Yes, visual trace showing which service called which |
| Latency breakdown | No, you see timestamps but no span durations | Yes, each span records start/end time |
| Implementation effort | Low: one filter, one interceptor, MDC | Medium: agent or SDK, collector, backend (Jaeger/Zipkin) |
| Log integration | Native (MDC keys appear in every log line) | Requires bridge (traceId/spanId injected into MDC) |
| Backend needed | Any log aggregator (ELK, Loki) | Trace backend (Jaeger, Zipkin, Tempo) |
| Spring Boot support | Manual implementation | Micrometer Tracing + OpenTelemetry auto-config |
| Best for | Simple request tracing, log correlation | Full observability with dependency graphs and latency analysis |
<!-- pom.xml: Spring Boot + OpenTelemetry auto-instrumentation --syn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.micrometersyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>micrometer-tracing-bridge-otelsyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.opentelemetrysyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>opentelemetry-exporter-otlpsyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
# application.properties for OpenTelemetry
management.tracing.sampling.probability=1.0
otel.exporter.otlp.endpoint=http://localhost:4317
otel.service.name=transfer-service
# With Micrometer Tracing, traceId and spanId are
# automatically injected into MDC. Your log pattern
# can include both:
# %d [%X{traceId}/%X{spanId}] [%X{correlationId}] %msg%n
Log output with both MDC correlation ID and OpenTelemetry traceId:
10:30:01 [abc123def456/span-001] [a1b2c3d4e5f6] INFO TransferService - Starting transfer
10:30:01 [abc123def456/span-002] [a1b2c3d4e5f6] INFO AccountService - Balance check
correlationId: your custom business ID (readable, short)
traceId: OpenTelemetry's distributed trace ID (hex, 32 chars)
spanId: identifies one unit of work within the trace
What are common mistakes?
Mistake 1: Not clearing MDC after the request
WRONG: Servlet containers reuse threads from a thread pool. If you do not clear MDC, the next request on the same thread inherits the previous correlation ID.
// WRONG: MDC not cleared
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
MDC.put("correlationId", CorrelationId.generate());
filterChain.doFilter(request, response);
// MDC.remove() missing! Next request on this thread
// gets the old correlation ID from the previous request.
}
CORRECT: Always clear MDC in a finally block.
// CORRECT: MDC cleared in finally block
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
MDC.put("correlationId", CorrelationId.generate());
try {
filterChain.doFilter(request, response);
} finally {
MDC.remove("correlationId");
}
}
Mistake 2: Losing correlation ID in async operations
WRONG: When you use @Async or CompletableFuture, the work runs on a different thread. MDC is thread-local, so the new thread has an empty MDC.
// WRONG: Async method runs on a different thread, MDC is empty
@Async
public void sendNotification(String accountId, String message) {
// MDC.get("correlationId") returns null here!
log.info("Sending notification to {}", accountId);
}
CORRECT: Copy MDC context before dispatching to another thread.
package com.bank.tracing;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import java.util.Map;
public class MdcTaskDecorator implements TaskDecorator {
@Override
public Runnable decorate(Runnable runnable) {
// Capture MDC from the calling thread
Map<String, String> contextMap = MDC.getCopyOfContextMap();
return () -> {
try {
if (contextMap != null) {
MDC.setContextMap(contextMap);
}
runnable.run();
} finally {
MDC.clear();
}
};
}
}
package com.bank.config;
import com.bank.tracing.MdcTaskDecorator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
public class AsyncConfig {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setTaskDecorator(new MdcTaskDecorator());
executor.setThreadNamePrefix("bank-async-");
executor.initialize();
return executor;
}
}
With MdcTaskDecorator:
10:30:01 [a1b2c3d4e5f6] INFO TransferService - Transfer completed
10:30:02 [a1b2c3d4e5f6] INFO NotificationService - Sending notification to SAV2001
Correlation ID preserved across threads.
What about reactive and virtual threads?
MDC relies on ThreadLocal, which does not work with reactive frameworks (WebFlux) or virtual threads (Java 21+) where a single request may hop between multiple carrier threads.
For reactive applications, use Reactor Context instead of MDC:
package com.bank.tracing;
import org.slf4j.MDC;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;
public class ReactiveCorrelationId {
public static Mono<String> getCorrelationId() {
return Mono.deferContextual(ctx ->
Mono.just(ctx.getOrDefault("correlationId", "unknown")));
}
public static Context withCorrelationId(String correlationId) {
return Context.of("correlationId", correlationId);
}
}
For virtual threads in Spring Boot 3.2+, Micrometer Tracing automatically propagates context using ScopedValue (Java 21 preview) or context propagation hooks.
# application.properties for virtual threads
spring.threads.virtual.enabled=true
# Micrometer Tracing handles MDC propagation for virtual threads
# when you add the micrometer-context-propagation dependency:
# <dependency>
# <groupId>io.micrometer</groupId>
# <artifactId>context-propagation</artifactId>
# </dependency>
What should a senior or principal engineer know?
- Context propagation across message queues. When a service publishes a Kafka message, the correlation ID must be included as a Kafka header. The consumer reads the header and puts it into MDC before processing. Without this, you lose traceability when requests cross async boundaries.
// Producer: Add correlation ID to Kafka headers
ProducerRecord<String, String> record =
new ProducerRecord<>("transfer-events", accountId, payload);
record.headers().add("X-Correlation-ID",
MDC.get("correlationId").getBytes());
kafkaTemplate.send(record);
// Consumer: Read correlation ID from Kafka headers
@KafkaListener(topics = "transfer-events")
public void onTransferEvent(
@Payload String payload,
@Header("X-Correlation-ID") String correlationId) {
MDC.put("correlationId", correlationId);
try {
log.info("Processing transfer event: {}", payload);
} finally {
MDC.remove("correlationId");
}
}
- Sampling in production. Tracing every request in a high-throughput banking system (10,000 TPS) generates enormous volumes of trace data. Use adaptive sampling: trace 100% of error requests, 100% of slow requests (latency above P95), and 1% of normal requests.
- W3C Trace Context standard. The traceparent HTTP header (00-traceId-spanId-flags) is the W3C standard for distributed tracing. OpenTelemetry uses it by default. Your custom X-Correlation-ID is a business-level ID that coexists with the trace context.
- Cost of log aggregation. Structured JSON logs are 3 to 5 times larger than plain text logs. At scale, this affects storage costs in Elasticsearch or S3. Use log levels wisely: DEBUG for development, INFO for production, and include request/response bodies only at DEBUG level.
- Correlation ID in error responses. Always include the correlation ID in error API responses so the customer or support team can reference it. "Your request failed. Reference ID: a1b2c3d4e5f6" is much more useful than a generic error message.
What are common interview follow-up questions?
- How do you propagate correlation IDs through Kafka or RabbitMQ?
- What happens to MDC when you use @Async or CompletableFuture?
- How is a correlation ID different from a traceId in OpenTelemetry?
- How do you configure structured JSON logging in Spring Boot?
- What is the W3C Trace Context standard?
- How do you handle correlation IDs with virtual threads in Java 21?
- How do you search for a specific request across 10 microservices in Kibana?
- What is the performance impact of tracing every request in production?
Visual Overview
Correlation ID Flow Across Microservices
==========================================
Client (Priya)
│
│ POST /api/transfers
│ (no X-Correlation-ID header)
▼
┌──────────────────────────────────────┐
│ transfer-service (port 8082) │
│ │
│ CorrelationIdFilter: │
│ 1. No header found │
│ 2. Generate: a1b2c3d4e5f6 │
│ 3. MDC.put("correlationId", id) │
│ 4. Response header set │
│ │
│ TransferService: │
│ log.info("Starting transfer") │
│ [a1b2c3d4e5f6] in every log line │
│ │
│ RestClient call to account-service │
│ CorrelationIdInterceptor adds │
│ X-Correlation-ID: a1b2c3d4e5f6 │
└────────────────┬─────────────────────┘
│
│ GET /api/accounts/SAV2001/balance
│ X-Correlation-ID: a1b2c3d4e5f6
▼
┌──────────────────────────────────────┐
│ account-service (port 8081) │
│ │
│ CorrelationIdFilter: │
│ 1. Header found: a1b2c3d4e5f6 │
│ 2. MDC.put("correlationId", id) │
│ │
│ AccountService: │
│ log.info("Balance check") │
│ [a1b2c3d4e5f6] in every log line │
└──────────────────────────────────────┘
MDC Thread-Local Lifecycle
===========================
Thread: http-nio-8082-exec-3
┌─────────────────────────────────────────┐
│ Request 1 arrives │
│ MDC.put("correlationId", "a1b2c3d4") │
│ ... process request ... │
│ log: [a1b2c3d4] Transfer started │
│ log: [a1b2c3d4] Transfer completed │
│ MDC.remove("correlationId") │
│ │
│ Request 2 arrives (same thread reused) │
│ MDC.put("correlationId", "e5f6a7b8") │
│ ... process request ... │
│ log: [e5f6a7b8] Balance check │
│ MDC.remove("correlationId") │
└─────────────────────────────────────────┘
Key Takeaway
In a microservices banking system, a single request from Priya touches multiple services. Without a shared identifier, connecting the log lines from transfer-service to the log lines from account-service is like finding a needle in a haystack during peak hours with thousands of requests per second.
A correlation ID solves this by stamping every log line with the same unique identifier for the duration of one request. A servlet filter generates the ID (or reads it from an incoming header), puts it into SLF4J's MDC, and clears it when the request completes. A RestClient interceptor copies the ID from MDC into the outgoing X-Correlation-ID header when calling downstream services. The downstream service's filter reads the header and puts the same ID into its own MDC.
Structured JSON logging makes the correlation ID a searchable field in log aggregation tools. Instead of grepping through plain text files on multiple servers, you search correlationId: "a1b2c3d4e5f6" in Kibana and see every log line from every service for that one request, in chronological order.
For deeper observability, OpenTelemetry adds traceId, spanId, and parent-child relationships on top of the correlation ID. This gives you visual dependency graphs and per-service latency breakdowns in tools like Jaeger or Grafana Tempo. The correlation ID remains your business-level reference that you can include in error responses and support tickets.
Remember one sentence: generate a correlation ID at the entry point, put it in MDC, propagate it in HTTP headers, and every log line across every service tells the same story.
---