Sub topic 10
Adding Request Context with MDC
This chapter assumes basic Java classes, try/catch, and Maven or Gradle dependency management. It also assumes that you have seen SLF4J loggers and a backend such as Logback.
What MDC provides
MDC, or mapped diagnostic context, stores small pieces of context for the current execution thread. A logging backend can add those values to every log event without requiring each method to receive and print them.
A request identifier is a common example. Instead of writing the identifier in every message, add it once when handling the request. A Logback pattern can then include the value:
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread] request=%X{requestId} %logger{36} - %msg%n</pattern>The %X{requestId} expression reads the requestId value from MDC.
| Context value | Useful for | Caution |
|---|---|---|
| `requestId` | Connecting messages from one request | Generate or validate it at the trust boundary |
| `userId` | Finding activity for a user | Do not log sensitive identity data without a reason |
| `jobId` | Following a background job | Remove it when the job finishes |
MDC is usually implemented with thread-local storage. Thread-local storage associates data with one thread. A logger on that thread can read the data while the context is active.
Setting and clearing a request ID
Use a bounded scope for MDC values. MDC.putCloseable returns an object that removes the value when the try block ends.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class RequestHandler {
private static final Logger log =
LoggerFactory.getLogger(RequestHandler.class);
public void handle(String requestId) {
try (MDC.MDCCloseable ignored =
MDC.putCloseable("requestId", requestId)) {
log.info("Request started");
validate();
log.info("Request completed");
}
}
private void validate() {
log.debug("Validating request");
}
public static void main(String[] args) {
new RequestHandler().handle("req-7f31");
}
}With a suitable Logback configuration, the messages contain request=req-7f31. The methods do not need a requestId parameter merely to make logging possible.
You can also manage the scope explicitly:
MDC.put("requestId", requestId);
try {
process();
} finally {
MDC.remove("requestId");
}The finally block is essential. It runs when process returns normally and when it throws an exception.
Thread pools and asynchronous work
MDC does not automatically follow work to another thread. This matters for executors, futures, reactive pipelines, and many web frameworks. If a request starts on one thread and the application queues work for another, the worker may see no context.
Thread pools create another danger: threads are reused. If code leaves an old value behind, a later request can log the wrong request ID. Always establish and clear context inside the unit of work.
flowchart TD
A[Receive request] --> B[Put requestId in MDC]
B --> C[Log and process on current thread]
C --> D{Submit work to another thread?}
D -- No --> E[Remove requestId]
D -- Yes --> F[Copy context explicitly]
F --> G[Worker sets its own MDC]
G --> H[Worker clears MDC]
E --> I[Request ends]
H --> Icaption: MDC context must be scoped to each thread alt: A request places an ID in MDC, optionally copies it to a worker, and clears it before the thread is reused
Choosing context carefully
MDC is best for stable values that should appear on many related events. It is not a replacement for event-specific fields. For example, an order status belongs in the message or in SLF4J's structured key-value API, while the request ID can remain in MDC.
Never place passwords, access tokens, session secrets, or full payment data in MDC. MDC values can appear on many lines and may be retained by diagnostic systems.
Practical checks
When adding MDC, verify these points:
- The value is inserted at the start of the request or job.
- The backend pattern actually prints the key.
- The value is removed in every exit path.
- Context is copied deliberately across thread boundaries.
- The value contains no secret or unnecessary personal data.
- Tests do not leave MDC values behind for later tests.
Exercise
Why can a request ID from one request appear in a later request when a thread pool is used, and how do you prevent it?
Show answer
The worker thread is reused and the old thread-local value remains. Set the new request ID at the start of the task and remove it in a finally block or with MDC.MDCCloseable.