Skip to lesson

Request ids to trace one request

A customer says "my payment failed at 10:42", but the ShopLite log holds lines from many checkouts in that same second. Which lines belong to that customer?

Many requests interleaved in one log

A request id is a unique label given to one HTTP request and printed on every log line that request writes.

A web server handles many requests at the same time. Here two checkouts write to one log, and their lines mix.

Six log lines from two checkouts are mixed in one file: request a1f3 and request b72c alternate. Searching for a1f3 keeps only its three lines, in order: placing order, calling the UPI gateway, and the failure: payment failed. The lines of b72c are left out.

Example 1 · Two checkouts, one log

InterleavedLogDemo.javaJava
import java.util.List;
/** Two customers place orders at the same moment. A server handles both at once, so their lines mix. */public class InterleavedLogDemo {    record Line(String level, String requestId, String text) {    }
    public static void main(String[] args) {        // The order in which the server happened to write the lines        List<Line> log = List.of(                new Line("INFO ", "a1f3", "POST /api/v1/me/orders started"),                new Line("INFO ", "b7c2", "POST /api/v1/me/orders started"),                new Line("INFO ", "b7c2", "Stock reserved for 2 items"),                new Line("INFO ", "a1f3", "Stock reserved for 1 item"),                new Line("INFO ", "a1f3", "Calling UPI gateway"),                new Line("INFO ", "b7c2", "Calling UPI gateway"),                new Line("INFO ", "b7c2", "Order 18 placed"),                new Line("ERROR", "a1f3", "Payment failed: gateway timed out"),                new Line("WARN ", "a1f3", "Responded 500 in 10043 ms"),                new Line("INFO ", "b7c2", "Responded 201 in 412 ms"));
        System.out.println("--- Without request ids: whose payment failed? ---");        for (Line line : log) {            System.out.println(line.level() + " " + line.text());        }
        System.out.println("--- With request ids ---");        for (Line line : log) {            System.out.println(line.level() + " [" + line.requestId() + "] " + line.text());        }
        System.out.println("--- Search for a1f3: one request's whole story ---");        log.stream()                .filter(line -> line.requestId().equals("a1f3"))                .forEach(line -> System.out.println(line.level() + " [a1f3] " + line.text()));    }}
Output
--- Without request ids: whose payment failed? ---
INFO  POST /api/v1/me/orders started
INFO  POST /api/v1/me/orders started
INFO  Stock reserved for 2 items
INFO  Stock reserved for 1 item
INFO  Calling UPI gateway
INFO  Calling UPI gateway
INFO  Order 18 placed
ERROR Payment failed: gateway timed out
WARN  Responded 500 in 10043 ms
INFO  Responded 201 in 412 ms
--- With request ids ---
INFO  [a1f3] POST /api/v1/me/orders started
INFO  [b7c2] POST /api/v1/me/orders started
INFO  [b7c2] Stock reserved for 2 items
INFO  [a1f3] Stock reserved for 1 item
INFO  [a1f3] Calling UPI gateway
INFO  [b7c2] Calling UPI gateway
INFO  [b7c2] Order 18 placed
ERROR [a1f3] Payment failed: gateway timed out
WARN  [a1f3] Responded 500 in 10043 ms
INFO  [b7c2] Responded 201 in 412 ms
--- Search for a1f3: one request's whole story ---
INFO  [a1f3] POST /api/v1/me/orders started
INFO  [a1f3] Stock reserved for 1 item
INFO  [a1f3] Calling UPI gateway
ERROR [a1f3] Payment failed: gateway timed out
WARN  [a1f3] Responded 500 in 10043 ms

What this code does

  • Without ids, the ERROR line could belong to either checkout. With ids, a1f3 failed and b7c2 got order 18.
  • Filtering by one id gives one request's whole story in order: started, stock, gateway, failure, response. That filter is what grep a1f3 shoplite.log does on a server.

Each request runs on its own thread and writes lines as things happen, so lines from different customers end up interleaved: mixed together in one file.

Without a label tying lines to a request, you cannot tell which "Calling UPI gateway" belongs to the failed checkout. With the label, grep a1f3 turns thousands of mixed lines into one story.

MDC: a request id on every line

The MDC (Mapped Diagnostic Context) is SLF4J's per-thread map of key-value pairs. A value put once can be printed on every log line written on that thread.

Put the id once at the start of a request. Every log line written on that thread can then show it, with no id passed to any method.

Java
MDC.put("requestId", requestId);     // at the start of the requesttry {    chain.doFilter(request, response);   // every log line in here can show the id} finally {    MDC.remove("requestId");         // always, even when the request fails}

Example 2 · A tiny MDC built on ThreadLocal

MiniMdcDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.logging.ConsoleHandler;import java.util.logging.Formatter;import java.util.logging.Handler;import java.util.logging.LogRecord;import java.util.logging.Logger;
/** A tiny MDC: one map of values per thread, like SLF4J's MDC class. */final class Mdc {    private static final ThreadLocal<Map<String, String>> CONTEXT = ThreadLocal.withInitial(HashMap::new);
    private Mdc() {    }
    static void put(String key, String value) {        CONTEXT.get().put(key, value);    }
    static String get(String key) {        return CONTEXT.get().get(key);    }
    static void remove(String key) {        CONTEXT.get().remove(key);    }}
/** Adds [requestId] to every line, the way %X{requestId} does in a Logback pattern. */class RequestIdFormatter extends Formatter {    @Override    public String format(LogRecord r) {        String id = Mdc.get("requestId");        return String.format("%-7s [%s] %s%n", r.getLevel(), id == null ? "-" : id, formatMessage(r));    }}
class OrderService {    private static final Logger log = Logger.getLogger("com.shoplite.order.OrderService");
    void place(int customerId) {        log.info("Placing order for customer " + customerId);        log.info("Order placed");    }}
public class MiniMdcDemo {    static {   // only for this page: log lines on System.out        System.setErr(System.out);    }
    static void handleRequest(String requestId, int customerId) {        Mdc.put("requestId", requestId);          // the filter's job: set at the start        try {            new OrderService().place(customerId);        } finally {            Mdc.remove("requestId");              // and always clear at the end        }    }
    public static void main(String[] args) throws InterruptedException {        Logger root = Logger.getLogger("");        for (Handler h : root.getHandlers()) {            root.removeHandler(h);        }        ConsoleHandler console = new ConsoleHandler();        console.setFormatter(new RequestIdFormatter());        root.addHandler(console);
        Thread first = new Thread(() -> handleRequest("a1f3", 1));        first.start();        first.join();        Thread second = new Thread(() -> handleRequest("b7c2", 2));        second.start();        second.join();
        Logger.getLogger("com.shoplite.App").info("Not inside a request");    }}
Output
INFO    [a1f3] Placing order for customer 1
INFO    [a1f3] Order placed
INFO    [b7c2] Placing order for customer 2
INFO    [b7c2] Order placed
INFO    [-] Not inside a request

What this code does

  • OrderService never receives the id, yet its lines show it: the formatter reads it from the per-thread map, as Logback's %X{requestId} reads SLF4J's MDC.
  • handleRequest plays the filter: put at the start, remove in finally. The last line is outside any request, so it shows -.

Inside, the MDC is a ThreadLocal: a variable that holds a separate value for each thread. That is why two requests on two threads never see each other's id.

Example 2 builds a tiny MDC from a ThreadLocal to show exactly this.

A filter that sets and clears the id

OncePerRequestFilter is Spring's base class for a servlet filter, code that runs around every HTTP request, and it runs exactly once per request.

ShopLite's RequestIdFilter sets the id on the way in and clears it on the way out. Read the whole class once.

Example 3 · src/main/java/com/shoplite/common/logging/RequestIdFilter.java

Runs in: the shoplite-api Spring Boot project

RequestIdFilter.javaJava
package com.shoplite.common.logging;
import java.io.IOException;import java.util.UUID;import java.util.regex.Pattern;
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 jakarta.servlet.FilterChain;import jakarta.servlet.ServletException;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse;
/** Gives every request an id: in the MDC (so in every log line) and in the X-Request-Id response header. */@Component@Order(Ordered.HIGHEST_PRECEDENCE)   // before Spring Security, so 401 and 403 lines carry the id toopublic class RequestIdFilter extends OncePerRequestFilter {
    public static final String HEADER = "X-Request-Id";    public static final String MDC_KEY = "requestId";    private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9-]{1,64}");
    @Override    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,                                    FilterChain chain) throws ServletException, IOException {        String requestId = idFrom(request.getHeader(HEADER));        MDC.put(MDC_KEY, requestId);        response.setHeader(HEADER, requestId);   // before the body is written        try {            chain.doFilter(request, response);        } finally {            MDC.remove(MDC_KEY);                 // the thread goes back to Tomcat's pool        }    }
    /** Reuse a caller's id only if it is short and plain; otherwise make a new one. */    static String idFrom(String incoming) {        if (incoming != null && SAFE_ID.matcher(incoming).matches()) {            return incoming;        }        return UUID.randomUUID().toString();    }}
Sample output (your UUID will differ)
$ curl -i http://localhost:8080/api/v1/products/99
HTTP/1.1 404
X-Request-Id: 3b0f6c1e-9a4d-4f2e-8c7b-5d1e2f3a4b6c
Content-Type: application/problem+json
...

$ curl -s -o /dev/null -D - -H "X-Request-Id: web-7f3a9c" http://localhost:8080/api/v1/products/1
HTTP/1.1 200
X-Request-Id: web-7f3a9c
Content-Type: application/json
...

What this code does

  • @Order(Ordered.HIGHEST_PRECEDENCE) runs the filter before Spring Security's filters, so even a 401 or 403 is logged with an id. The header is set before doFilter, because headers cannot be added once the body is sent.
  • The first call sent no header and got a fresh UUID; the second sent web-7f3a9c and the API kept it, so the web app's logs and ShopLite's logs share one id.

Example 4 · Which incoming ids are reused

RequestIdChoiceDemo.javaJava
import java.util.UUID;import java.util.regex.Pattern;
public class RequestIdChoiceDemo {    private static final Pattern SAFE_ID = Pattern.compile("[A-Za-z0-9-]{1,64}");
    /** The same rule as RequestIdFilter.idFrom: reuse a plain id, otherwise make a new one. */    static String idFrom(String incoming) {        if (incoming != null && SAFE_ID.matcher(incoming).matches()) {            return incoming;        }        return UUID.randomUUID().toString();    }
    static String describe(String incoming) {        String id = idFrom(incoming);        boolean reused = id.equals(incoming);        String shown = incoming == null ? "(no header)" : incoming.replace("\n", "\\n");        if (shown.length() > 38) {            shown = shown.substring(0, 20) + "... (" + incoming.length() + " chars)";        }        return String.format("%-38s -> %s", shown, reused ? "reused" : "new UUID, " + id.length() + " characters");    }
    public static void main(String[] args) {        System.out.println(describe(null));        System.out.println(describe("web-7f3a9c"));        System.out.println(describe("b2c1d0e4-5a6b-4c7d-8e9f-0a1b2c3d4e5f"));        System.out.println(describe("abc\nINFO Order 99 refunded"));        System.out.println(describe("x".repeat(100)));    }}
Output
(no header)                            -> new UUID, 36 characters
web-7f3a9c                             -> reused
b2c1d0e4-5a6b-4c7d-8e9f-0a1b2c3d4e5f   -> reused
abc\nINFO Order 99 refunded            -> new UUID, 36 characters
xxxxxxxxxxxxxxxxxxxx... (100 chars)    -> new UUID, 36 characters

What this code does

  • Plain ids up to 64 characters (including a UUID's 36) are reused; a missing header gets a new UUID.
  • An id with a line break or 100 characters is replaced. Otherwise a caller could add a fake INFO Order 99 refunded line to your log, a trick called log injection.

The filter reuses an id the caller sent in the X-Request-Id header, if it is short and plain; otherwise it creates a UUID. The id also goes into the response header, so a customer or the web app can quote it in a complaint.

The filter clears the MDC in finally, because Tomcat reuses its threads: a forgotten id would stick to the next, unrelated work on that thread.

Order of execution

Order the filter's steps

Tap the steps in the order the filter runs them.

Never trust the incoming header blindly. A 5,000-character id or one containing a line break would end up in every log line; the filter only reuses ids of up to 64 letters, digits and dashes.

%X{requestId} in the log pattern

A log pattern is the template Logback uses to turn an event into a line of text. %X{key} prints a value from the MDC.

One property tells Logback to print the request id on every console line.

Example 5 · src/main/resources/application.properties (pattern with the request id)

Runs in: the shoplite-api Spring Boot project

Properties
logging.pattern.console=%d{HH:mm:ss.SSS} %-5level [%X{requestId:-none}] %logger{30} - %msg%nlogging.pattern.file=%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%X{requestId:-none}] [%thread] %logger{40} - %msg%n
Sample output
10:42:00.512 INFO  [none] c.shoplite.ShopliteApiApplication - Started ShopliteApiApplication in 3.214 seconds
10:42:01.206 INFO  [f2b8] c.s.order.OrderService - Placing order for customer 7 with 2 item(s)
10:42:01.207 INFO  [a1f3] c.s.order.OrderService - Placing order for customer 1 with 1 item(s)
10:42:01.250 WARN  [f2b8] c.s.product.ProductService - Low stock: MOB-IP15 has 2 left
10:42:11.249 ERROR [a1f3] c.s.payment.PaymentService - Payment failed for order 17 (Rs 499.00)

What this code does

  • %X{requestId:-none} prints the MDC value, or none for the startup line, which runs outside any request.
  • %logger{30} shortens package names to fit about 30 characters (c.s.order.OrderService). The file pattern keeps the full date, the thread and a longer logger name, because files are read later and by tools.

%X{requestId} reads the requestId key from the MDC; %X{requestId:-none} prints none when the key is missing, for lines outside any request such as startup.

Set the console pattern with logging.pattern.console and the file pattern with logging.pattern.file. JSON (structured) logs include MDC values as fields automatically, which the next lesson covers.

MDC and new threads

A TaskDecorator is a Spring wrapper around tasks given to an executor. It is used to copy the MDC from the request thread into the worker thread.

A task handed to another thread starts with an empty MDC. Watch the id vanish, then copy it over.

Example 6 · The id is lost in another thread, then copied over

MdcThreadsDemo.javaJava
import java.util.HashMap;import java.util.Map;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
/** The same idea as SLF4J's MDC: a per-thread map, NOT inherited by other threads. */final class Context {    private static final ThreadLocal<Map<String, String>> MAP = ThreadLocal.withInitial(HashMap::new);
    private Context() {    }
    static void put(String key, String value) {        MAP.get().put(key, value);    }
    static String get(String key) {        return MAP.get().get(key);    }
    static Map<String, String> copy() {        return new HashMap<>(MAP.get());    }
    static void set(Map<String, String> values) {        MAP.set(new HashMap<>(values));    }
    static void clear() {        MAP.get().clear();    }
    /** Wraps a task so it runs with the caller's context, then cleans up (Spring calls this a TaskDecorator). */    static Runnable withCurrentContext(Runnable task) {        Map<String, String> captured = copy();        return () -> {            set(captured);            try {                task.run();            } finally {                clear();            }        };    }}
public class MdcThreadsDemo {    static void log(String message) {        System.out.println("[" + Context.get("requestId") + "] " + message);    }
    public static void main(String[] args) throws InterruptedException {        ExecutorService pool = Executors.newSingleThreadExecutor();        Context.put("requestId", "a1f3");        log("Order 17 placed, sending e-mail in the background");
        pool.submit(() -> log("E-mail for order 17 sent"));                           // id lost        pool.submit(Context.withCurrentContext(() -> log("SMS for order 17 sent")));  // id copied        pool.submit(() -> log("Next task on the same worker"));                       // cleaned up
        pool.shutdown();        pool.awaitTermination(5, TimeUnit.SECONDS);        Context.clear();    }}
Output
[a1f3] Order 17 placed, sending e-mail in the background
[null] E-mail for order 17 sent
[a1f3] SMS for order 17 sent
[null] Next task on the same worker

What this code does

  • The plain task ran on the pool's worker thread, whose context was empty, so the e-mail line shows null and cannot be linked to the order's request.
  • withCurrentContext copies the map on the request thread and sets it on the worker, then clears it, so the task after it is clean again. With SLF4J the same wrapper uses MDC.getCopyOfContextMap() and MDC.setContextMap(...).

Work you hand to an ExecutorService, an @Async method or CompletableFuture.supplyAsync logs without the request id unless you carry it over.

Copy the map on the request thread with MDC.getCopyOfContextMap(), set it inside the task with MDC.setContextMap(...) and clear it when the task ends. Spring Boot applies a TaskDecorator bean to its auto-configured task executor.

Predict the output

Where did the id go?

The console pattern is [%X{requestId:-none}] %msg.

Round 1 of 2

What does the e-mail line print?

MDC.put("requestId", "a1f3");
executor.submit(() -> log.info("E-mail sent"));

Next step

Check your understanding

10 quick questions