Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Register two filters so that a correlation id filter runs before Spring Security and a metrics filter runs after it. Show how ordering works.

Spring Boot registers Spring Security's filter chain with the order from spring.security.filter.order, which is -100 by default, and filters run in ascending order. So we register the correlation id filter with a FilterRegistrationBean and an order lower than -100, for example -200, and the metrics filter with an order higher than -100, for example 10; @Order on the filter bean also works. Both should extend OncePerRequestFilter so they do not run twice on error and async dispatches.

Why this question is asked

Filter order sounds like a detail until it bites. If the correlation id filter runs after Spring Security, every log line Security writes for a rejected login has no correlation id, which is exactly the request we most want to trace. If a metrics filter runs before Security, it counts and times requests that never reach the application. Interviewers ask this because it tests whether we know how Boot registers filters and where Security sits among them. In this answer, we will recap how filter order works, write both filters, register them with explicit order values, see what happens to the metrics filter when Security rejects a request, and handle repeated dispatches.

1A Quick Recap of Filter Order

In Spring Boot, every servlet filter is registered with the embedded container with an order number. Lower numbers run earlier on the way in and, because filters call each other in a chain, later on the way out. A filter with order -200 wraps a filter with order -100, which wraps one with order 10, which wraps DispatcherServlet.

Spring Security is not one filter but a chain of them. Boot registers a single DelegatingFilterProxy that hands each request to Security's FilterChainProxy, and that registration gets the order from the property spring.security.filter.order, -100 by default. Some of Boot's own filters run even earlier: the character encoding filter, for example, is registered with the highest precedence so that the body is decoded correctly by everything after it. Filters without an explicit order get the lowest precedence and run last.

2Writing the Two Filters

Both filters extend OncePerRequestFilter, Spring's base class that guarantees the filter body runs once per request. The correlation filter sets the MDC, and the metrics filter times the request and records it with Micrometer.

Java
public class CorrelationIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
String id = Optional.ofNullable(req.getHeader("X-Correlation-Id")).orElse(UUID.randomUUID().toString());
MDC.put("correlationId", id);
res.setHeader("X-Correlation-Id", id);
try { chain.doFilter(req, res); } finally { MDC.remove("correlationId"); }
}
}
public class RequestMetricsFilter extends OncePerRequestFilter {
private final MeterRegistry registry;
public RequestMetricsFilter(MeterRegistry registry) { this.registry = registry; }
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
long start = System.nanoTime();
try { chain.doFilter(req, res); }
finally {
registry.timer("app.requests", "status", String.valueOf(res.getStatus()))
.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
}
}

Notice that neither class is annotated @Component. If they were components and we also registered them with a FilterRegistrationBean, we would have to be careful which registration wins. Creating them only inside the registration beans keeps a single, explicit registration.

3Registering Them With Explicit Order Values

FilterRegistrationBean lets us set the order, the URL patterns and the dispatcher types of a filter. We pick numbers around Security's -100 and write them down as constants so other filters can be placed relative to them.

Java
@Configuration
class FilterConfig {
static final int CORRELATION_ORDER = -200; // before Spring Security (-100)
static final int METRICS_ORDER = 10; // after Spring Security
@Bean
FilterRegistrationBean<CorrelationIdFilter> correlationFilter() {
var reg = new FilterRegistrationBean<>(new CorrelationIdFilter());
reg.setOrder(CORRELATION_ORDER);
reg.addUrlPatterns("/*");
return reg;
}
@Bean
FilterRegistrationBean<RequestMetricsFilter> metricsFilter(MeterRegistry registry) {
var reg = new FilterRegistrationBean<>(new RequestMetricsFilter(registry));
reg.setOrder(METRICS_ORDER);
return reg;
}
}
// Order of execution for GET /api/orders:
// CorrelationIdFilter (-200) -> Spring Security (-100) -> RequestMetricsFilter (10) -> DispatcherServlet
Step throughWhere each filter runs
TomcatCorrelation (-200)Security (-100)Metrics (10)DispatcherServlet
GET /api/orders
MDC correlationId = abc
chain.doFilter
authenticate, logs carry abc
chain.doFilter
chain.doFilter, timer starts
200 OK
timer recorded
return
MDC cleared

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

The alternative is @Order(-200) on a filter bean, or implementing Ordered. Both work, and Boot reads the order when it registers the bean. FilterRegistrationBean is more explicit and also lets us restrict URL patterns, which is why it is usually preferred for anything order-sensitive. If someone changes spring.security.filter.order, our constants must be reviewed too, which is a good reason to reference them in a test.

4What the Metrics Filter Does Not See

Because the metrics filter runs after Security, it never sees requests that Security rejects. An unauthenticated call returns 401 from Security's entry point and never reaches order 10. That is often what we want, since application latency should not be mixed with rejected requests, but it means our metric does not count attacks or misconfigured clients.

If we need both, we keep this filter for application metrics and rely on Spring Boot's built-in server observation, which is registered very early in the chain, for the overall request count including rejections. The important thing is to choose deliberately and name the metric so readers know what it covers.

Java
// curl -i /api/orders (no credentials)
// HTTP/1.1 401, X-Correlation-Id: 5f1c... -> correlation filter ran, metrics filter did not
// curl -i -u ana:secret /api/orders
// HTTP/1.1 200, X-Correlation-Id: 9a2e... -> both filters ran, app.requests{status=200} incremented

5Why OncePerRequestFilter Matters

A single HTTP request can pass through the filter chain more than once. When a controller throws and the container forwards to /error, that is an ERROR dispatch. When a controller returns a CompletableFuture or DeferredResult, the request is dispatched again to write the result, an ASYNC dispatch. A plain Filter registered for those dispatch types would run again: our metrics filter would record two timings, and the correlation filter might generate a second id.

OncePerRequestFilter marks the request with an attribute the first time it runs and skips the body on later dispatches of the same request. By default it also skips async and error dispatches entirely, with shouldNotFilterAsyncDispatch() and shouldNotFilterErrorDispatch() returning true. So each request gets exactly one correlation id and one timing. For async requests, the metrics filter's finally block runs when the first thread returns, not when the async result is written, so for those endpoints we either time with Boot's observation support or override shouldNotFilterAsyncDispatch() carefully; check your version's behaviour before relying on either.

6Follow-up questions

What if two filters have the same order?

Their relative order is then not guaranteed in a way we should rely on; it depends on bean registration order. Give every order-sensitive filter its own value and keep the values as named constants, ideally in a shared starter, so teams do not accidentally collide.

Can I put a filter inside Spring Security's chain instead?

Yes, with http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class) or addFilterAfter in the SecurityFilterChain configuration. That is right when the filter needs to run between specific security filters, for example after authentication so it can read the user. A filter added that way should not also be registered with the container, or it runs twice.

How do you test the order?

A @SpringBootTest with MockMvc that sends an unauthenticated request and asserts that the X-Correlation-Id header is present proves the correlation filter runs before Security. A second test can assert that the metrics timer count did not change for that request, proving the metrics filter runs after Security.

7Conclusion

In this answer, we saw that Boot orders servlet filters by number, with Spring Security's chain at spring.security.filter.order, -100 by default. We registered the correlation id filter at -200 so Security's own log lines carry the id, and the metrics filter at 10 so it measures only requests Security lets through, using FilterRegistrationBean.setOrder, with @Order as an alternative. Both filters extend OncePerRequestFilter so error and async dispatches do not run them twice.

What to say in the interviewAbout 100 seconds aloud

Open with

Filters in Spring Boot run in ascending order, and Spring Security is registered as one DelegatingFilterProxy with the order from spring.security.filter.order, which defaults to -100. So I'd register the correlation id filter with a FilterRegistrationBean and setOrder(-200), so it runs before Security and even Security's own log lines for a rejected request have the id in the MDC.

Then, if they want more

The metrics filter gets something like 10, so it runs after Security and only measures requests that actually reach the application. I'd keep those values as named constants next to a comment about the -100, because if someone changes the security order, our filters need to move too.

Using @Order on the filter bean works as well, but the registration bean is more explicit and lets me set URL patterns, and I'd avoid also making the filters @Component so they're not registered twice. Both filters extend OncePerRequestFilter.

That matters because a request can go through the chain again on an error dispatch to /error or an async dispatch, and a plain filter would then create a second correlation id or record two timings.

One consequence worth saying out loud: a 401 from Security never reaches the metrics filter, which is fine if the metric is meant to be application latency, but if we need counts of rejected requests we use Boot's server observation, which sits at the front of the chain.

And I'd test the order with MockMvc: an unauthenticated request should still carry the correlation header.

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.
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 "Register two filters so that a correlation id filter runs before Spring Security and a...": https://scrivio-interview-library.netlify.app/spring-boot/mvc-architecture/b42735c121/