Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Write a ContainerRequestFilter and ContainerResponseFilter pair that assigns a request id (from X-Request-Id or a new UUID), puts it in the MDC, and adds it to the response headers. When must the request filter be @PreMatching?

The request filter reads X-Request-Id with getHeaderString or creates a UUID, stores it with requestContext.setProperty and MDC.put, and the response filter reads the property, writes it with getHeaders().putSingle("X-Request-Id", id) and clears the MDC. The request filter only needs @PreMatching when it must change the request before resource matching, such as the URI or the HTTP method; a request id filter does not.

Why this question is asked

A request id is the thread that ties together every log line, every downstream call and the error the user reports. Without it, finding the logs for one failed request among millions is guesswork. Interviewers ask for this filter pair because it touches filter ordering, request properties, the MDC and the thread-reuse trap that makes logs lie. In this answer, we will recap filters and the MDC, write both filters, look at ordering with @Priority, explain when @PreMatching is needed, and handle the cleanup and async cases correctly.

1A Quick Recap of Filters and the MDC

A ContainerRequestFilter runs before the resource method, and a ContainerResponseFilter runs after it, with access to the status, headers and entity of the response. Both are registered as providers, usually with @Provider and package scanning or an explicit registration in the Application or ResourceConfig.

The MDC, Mapped Diagnostic Context, is a per-thread map offered by SLF4J and Logback (Log4j 2 calls it ThreadContext). Whatever we put in it can be printed by every log line on that thread, for example with %X{requestId} in the log pattern. Because it is per thread, it is only correct as long as the request stays on that thread, which is the source of the cleanup rule we will see.

2Writing the Filter Pair

One class can implement both interfaces, which keeps the property name in one place.

Java
import jakarta.annotation.Priority;
import jakarta.ws.rs.Priorities;
import jakarta.ws.rs.container.*;
import jakarta.ws.rs.ext.Provider;
import org.slf4j.MDC;
@Provider
@Priority(Priorities.USER - 500) // 4500: before ordinary user filters (5000)
public class RequestIdFilter implements ContainerRequestFilter, ContainerResponseFilter {
static final String HEADER = "X-Request-Id";
static final String PROP = "requestId";
@Override
public void filter(ContainerRequestContext req) {
String id = req.getHeaderString(HEADER);
if (id == null || !id.matches("[A-Za-z0-9-]{8,64}")) { // do not trust arbitrary input in logs
id = UUID.randomUUID().toString();
}
req.setProperty(PROP, id); // lives as long as this request
MDC.put(PROP, id); // lives on this thread
}
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext res) {
try {
Object id = req.getProperty(PROP);
if (id != null) res.getHeaders().putSingle(HEADER, id.toString());
} finally {
MDC.remove(PROP); // thread goes back to the pool clean
}
}
}
// curl -i http://localhost:8080/api/orders/42
// X-Request-Id: 3c1e9a52-6f0b-4b7e-9d2c-5e8f0a1b2c3d
// log: [requestId=3c1e9a52-...] GET /orders/42 -> 200

Notice that we keep the id in two places. The request property belongs to the request, so it survives even if the response is produced on another thread. The MDC belongs to the current thread, and logging reads it. We also validate the incoming id, because a client could send a 10 KB header or one with line breaks that forge log entries; anything odd is replaced with a fresh UUID. putSingle replaces any existing value instead of adding a second header.

3Ordering Filters With @Priority

When several filters exist, @Priority decides the order. The constants in Priorities are AUTHENTICATION (1000), AUTHORIZATION (2000), HEADER_DECORATOR (3000), ENTITY_CODER (4000) and USER (5000), the default when none is given. For request filters, lower numbers run first; for response filters, the order is reversed, so the lowest number runs last.

Where should the request id filter sit? Ideally before authentication, so that a 401 from the authentication filter is logged with an id too. That suggests a value below 1000, such as Priorities.AUTHENTICATION - 100. The example uses USER - 500 to show the arithmetic; in a real service we would choose based on which filters must see the id.

Step throughFilter order for one request
ContainerRequestIdFilter (900)AuthFilter (1000)Resource
request filter: set property and MDC
request filter: authenticate
invoke method
response entity
response filter (higher number runs first)
response filter: add header, clear MDC
done

7 messages in order. Play them, or step through them one at a time.

Request filters run in ascending priority, response filters in descending priority.

4When Does the Request Filter Need @PreMatching?

A normal request filter runs after JAX-RS has matched the request to a resource method. A filter annotated @PreMatching runs before that matching, which is the only point where changing the URI or the method still affects which method is chosen. Typical examples are a method override filter that turns POST with X-HTTP-Method-Override: PATCH into a PATCH, or a filter that rewrites /v1/ paths to the current paths.

Our filter changes nothing that matching depends on; it only reads a header and sets a property. So it does not need @PreMatching. There is one reason we might still add it: a post-matching filter does not run for requests that match no resource, so a 404 would have no request id in its logs. If we want ids on every request including 404s, @PreMatching gives that.

5Cleanup and the Async Trap

Container threads are reused. If we forget to clear the MDC, the next request served by the same thread starts with our id still in place, and if that request has no header processing, for example an early error, its log lines carry someone else's request id. That is why the removal sits in a finally block. One caution: if a request fails before our response filter runs, for example with an exception thrown in an earlier filter, the response filter may still run for the error response, but a servlet filter or the request filter itself clearing the MDC at the start is a cheap extra safeguard.

With asynchronous responses, AsyncResponse or a CompletionStage return type, the request thread returns early and the response is completed later on another thread. That thread's MDC does not have our id, so logs written while finishing the work lose it, and the response filter runs on the resuming thread. The request property still holds the id, which is why we read it from there. For the work in between, we capture the id and restore it: MDC.getCopyOfContextMap() before switching threads and MDC.setContextMap() on the new one, or a context-propagating executor. With OpenTelemetry, the trace context propagation does this for the trace id automatically.

6Follow-up questions

What is the difference between a filter and a ReaderInterceptor?

A filter works on the request or response as a whole: URI, method, headers, properties, and it can abort the request. A ReaderInterceptor wraps the reading of the entity body, it runs only when a body is read by a message body reader, and it can replace the input stream, which is how decompression or body signing checks are done. Similarly, a WriterInterceptor wraps writing the response body. So for a request id, a filter is right, because it is about headers, not the body.

Should we also send the request id to downstream services?

Yes. A ClientRequestFilter on our JAX-RS client can read the id from the MDC and add X-Request-Id to outgoing calls, so the downstream logs share it. In modern systems we often use the W3C traceparent header from OpenTelemetry for this, and log the trace id, but a simple request id is still common and useful for support tickets.

Why use a request property rather than only the MDC?

Because the property belongs to the request and the MDC belongs to the thread. The response filter, exception mappers and async completion code can always find the property, even on a different thread, while the MDC is only correct on the thread where we set it.

7Conclusion

In this answer, we wrote a request filter that takes X-Request-Id or a new UUID, validates it, stores it as a request property and in the MDC, and a response filter that copies it to the response header with putSingle and clears the MDC in a finally block. We ordered the filters with @Priority, where lower numbers run first for requests and last for responses, and saw that @PreMatching is only needed when a filter changes the URI or method, or when we want the id on unmatched requests. Clearing the MDC matters because threads are reused, and with async responses the id must be restored on the resuming thread.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write one provider class that implements both ContainerRequestFilter and ContainerResponseFilter. In the request filter I read the X-Request-Id header with getHeaderString, validate it because it is client input that ends up in logs, and generate a UUID if it is missing or invalid.

Then, if they want more

I store it twice: with requestContext.setProperty, so it belongs to the request, and with MDC.put, so every log line on this thread prints it.

In the response filter I read the property and set the response header with getHeaders().putSingle, and in a finally block I remove it from the MDC, because container threads are reused and the next request would otherwise log with a stale id.

I order it with @Priority, usually before authentication so even 401s have an id; lower numbers run first on the way in and last on the way out. It does not need @PreMatching, because PreMatching is for filters that change the URI or method before resource matching, like a method override filter.

The one reason I might add it is to get ids on 404s, since post-matching filters do not run when nothing matches. With async responses, I restore the MDC on the resuming thread from the request property.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a ContainerRequestFilter and ContainerResponseFilter pair that assigns a request...": https://scrivio-interview-library.netlify.app/java/jax-rs/f632cbf57a/