Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MDC or Threadlocal

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.

like image 889
Lukas Forst Avatar asked Nov 15 '25 15:11

Lukas Forst


1 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.

like image 169
theNextBigThing Avatar answered Nov 17 '25 09:11

theNextBigThing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!