Using MDC or Threadlocal

Viewed 3119

I'd like to propagate X-Request-Id received from my Nginx to other services in my k8s when calling them using http.

Right now, I'm using request filters to catch that X-Request-Id header and putting it to the MDC.

        final String nginxRequestId = requestContext.getHeaderString("X-Request-Id");
        if (nginxRequestId != null) {
            MDC.put("infra_request", nginxRequestId);
        }

Now, I'm calling the endpoint of service B inside the k8s (so no Nginx in the way) and I'd like to obtain that X-Request-Id to put it into the request's header. I can see two options here:

  1. simply get that value from MDC
  2. store that header in the thread local variable (as the service is using Dropwizard) in addition to storing it in MDC

I'd probably do it using the MDC, but I'm not sure whether this is the best practice or whether there could be some catch/problems with that.

2 Answers

I have used both the MDC and ThreadLocal for the similar purpose of passing a transaction-id to the headers. Internally, MDC uses ThreadLocal and it has some predefined functionalities like adding a prefix to every log. I would suggest having ThreadLocal if the data which you are putting is of some business use, otherwise, you can go with MDC.

I think for your purpose it is good to use MDC. Internally MDC uses ThreadLocal. Even if you use ThreadLocal, for a nicer way of implementation you will wrap ThreadLocal variable in a class. MDC does the same for you.

Related