Where to close micrometer baggage for a request to a reactive endpoint in a Spring Boot app?

421 Views Asked by At

In my Spring Boot 3.1+ application I have a reactive endpoint that looks like this:

@PostMapping
public Mono<Result> doStuff(@RequestBody String body) {
    // ...
}

This call triggers my reactive code flow, within which I want to have the MDC context set. I also have a filter that is responsible for setting the MDC context that looks like this:

public class MyFilter extends OncePerRequestFilter {

    private final Tracer tracer;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

            var baggage = tracer.createBaggageInScope(getBaggageName(), getBaggageValue())
            try {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } finally {
                baggage.close();
            }
    }

    // ...

}

but this seems to close the baggage prematurely, before the reactive flow is complete (resulting in MDC being gone in some places).

On the other hand, setting the baggage in my endpoint's code (in the reactive flow in the doStuff method) and closing it on doFinally will make the baggage not available in exception handlers.

The Spring team seems to achieve this similarly e.g. in: ServerHttpObservationFilter however in their case they do not close the observation for async processing. I also considered just not closing the baggage (this seems to work just fine), but Micrometer Tracing docs tell me that "baggage must be closed so that the scope does not leak".

Any ideas on how to solve this? Where to best close this baggage so that it is available in the whole reactive flow (if necessary at all)?

By the way I am already using Reactor's Hooks.enableAutomaticContextPropagation() and contextWrite where applicable.

0

There are 0 best solutions below