Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

A Spring Boot service needs protection from overload. The team wants a servlet filter that caps the number of requests in progress, keeps some room for traffic marked critical, and rejects the rest quickly when the cap is reached.

Write a OncePerRequestFilter that allows 150 concurrent normal requests plus 50 reserved for requests with the header X-Priority: critical, returns 503 with Retry-After when full, and counts rejections with Micrometer. Explain the pitfalls.

We use two semaphores, a shared one with 150 permits and a reserve with 50, and only ever call tryAcquire so the filter never blocks: a normal request takes a shared permit, a critical one tries shared first and then the reserve, and anything that gets no permit receives 503 with Retry-After and increments a Micrometer counter built once per priority. The pitfalls are releasing the permit exactly once, in a finally block or in an AsyncListener for async requests; trusting a priority header that clients can set; registering the filter too late in the chain or on health endpoints; and treating 150 as a fact rather than a guess from Little's law and load tests.

Why this question is asked

A concurrency limit is one of the simplest and most effective protections a service can have: it caps how much work is in progress at once, so overload turns into fast rejections instead of slow everything. It is also easy to get subtly wrong, and the mistakes, leaking permits or trusting a header, cause outages of their own. Interviewers ask for this filter because it combines Servlet details, concurrency and operational judgment in a few dozen lines. In this answer, we will recap the idea, write the filter, register it in the right place, and then go through each pitfall: releasing permits, async requests, the priority header, and choosing the limit.

1A Quick Recap: Capping Requests in Progress

A concurrency limit counts requests that are currently being processed, called in-flight requests, and refuses new ones when the count reaches the limit. Unlike a rate limit, it counts the work that actually consumes threads, connections and memory.

A Semaphore from java.util.concurrent is a natural fit. It holds a number of permits; tryAcquire() takes one if available and returns false immediately if not, and release() gives one back. Here we want 150 permits for any request plus 50 that only critical requests may use, so a flood of normal traffic can never take the room reserved for critical work. Two semaphores model that exactly: critical requests try the shared pool first and fall back to the reserve.

Step throughAdmission decision for one request
  1. Health or metrics endpoint?liveness must never be shed
    YesPass through, no permitNoContinue
  2. Shared permit free? (150)shared.tryAcquire()
    YesServe the requestNoContinue
  3. Critical and reserve free? (50)reserve.tryAcquire()
    YesServe the requestNo503, Retry-After: 1, count it
  4. Release the permit oncefinally, or AsyncListener for async

4 steps in order. Play them, or step through them one at a time.

2Writing the Filter

OncePerRequestFilter is Spring's base class that guarantees the filter runs once per request, even across internal forwards and async dispatches. We override doFilterInternal for the logic and shouldNotFilter to skip health and metrics endpoints.

Java
public class ConcurrencyLimitFilter extends OncePerRequestFilter {
private final Semaphore shared = new Semaphore(150);
private final Semaphore reserve = new Semaphore(50);
private final Counter shedNormal, shedCritical;
public ConcurrencyLimitFilter(MeterRegistry registry) {
shedNormal = Counter.builder("http.server.shed").tag("priority", "normal").register(registry);
shedCritical = Counter.builder("http.server.shed").tag("priority", "critical").register(registry);
}
@Override
protected boolean shouldNotFilter(HttpServletRequest req) {
String path = req.getRequestURI();
return path.startsWith("/actuator/health") || path.startsWith("/actuator/prometheus");
}
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
boolean critical = "critical".equalsIgnoreCase(req.getHeader("X-Priority")); // set by our gateway only
Semaphore taken = shared.tryAcquire() ? shared // never blocks
: (critical && reserve.tryAcquire()) ? reserve : null;
if (taken == null) {
(critical ? shedCritical : shedNormal).increment();
res.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // 503
res.setHeader("Retry-After", "1");
return; // chain.doFilter not called
}
AtomicBoolean released = new AtomicBoolean();
Runnable release = () -> { if (released.compareAndSet(false, true)) taken.release(); };
try {
chain.doFilter(req, res);
} finally {
if (req.isAsyncStarted()) req.getAsyncContext().addListener(new ReleaseOnEnd(release));
else release.run(); // normal request: release now
}
}
private record ReleaseOnEnd(Runnable release) implements AsyncListener {
public void onComplete(AsyncEvent e) { release.run(); }
public void onTimeout(AsyncEvent e) { release.run(); }
public void onError(AsyncEvent e) { release.run(); }
public void onStartAsync(AsyncEvent e) { e.getAsyncContext().addListener(this); }
}
}

Notice the shape of the try and finally. We only enter it after a permit was taken, so a rejected request never releases a permit it does not hold. The counters are built once, in the constructor, not on every rejection. Note also that OncePerRequestFilter does not filter async dispatches by default, so the second dispatch of an async request does not take a second permit.

3Registering It Early in the Chain

The filter should run before expensive work. If it runs after Spring Security, a rejected request has already parsed tokens and perhaps called an identity service, which is exactly the work we wanted to avoid. So we register it with a FilterRegistrationBean and a high precedence, instead of marking it @Component, which would register it automatically with a default order.

Java
@Bean
FilterRegistrationBean<ConcurrencyLimitFilter> concurrencyLimit(MeterRegistry registry) {
var bean = new FilterRegistrationBean<>(new ConcurrencyLimitFilter(registry));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE + 10); // before Spring Security (order -100 by default)
bean.addUrlPatterns("/*");
return bean;
}
// 151 normal requests in flight: the 151st gets 503, Retry-After: 1
// 150 normal + 50 critical in flight: the next critical request gets 503 too

It still runs after the observation filter, so shed requests appear in http.server.requests as 503s. Check your version's filter orders if the exact position matters.

4Pitfall 1: Leaked Permits and Async Requests

Every permit taken must be released exactly once. If an exception escapes chain.doFilter and we release only on success, each failure leaks a permit. After 150 leaks, every normal request is rejected forever, and the service looks overloaded while doing nothing. The finally block prevents this.

Async requests are the subtle case. With DeferredResult, Callable or Servlet async, chain.doFilter returns while the request is still being processed on another thread. Releasing in finally would free the permit too early, so the limit would not count async work at all. Instead, when request.isAsyncStarted() is true, we register an AsyncListener and release when the request completes, errors or times out, guarded by an AtomicBoolean so the permit is released only once even if several events fire.

5Pitfall 2: Trusting the Priority Header

If any client can send X-Priority: critical, then under load everyone will, either on purpose or because someone copied a code sample, and the reserve stops meaning anything. The header must come from our own infrastructure. The gateway should remove any incoming X-Priority and set it itself, based on the route or the authenticated client, for example checkout and login routes are critical.

Health and metrics endpoints need the opposite treatment: they must never be shed. If the liveness probe gets a 503 under load, Kubernetes restarts the pod, which removes capacity at the worst moment and makes the overload worse. That is why shouldNotFilter exempts them.

6Pitfall 3: A Fixed Limit Is a Guess

Where do 150 and 50 come from? Little's law gives a starting point: in-flight requests equal throughput times latency. If the service handles 2,000 requests per second at a healthy 50 ms, about 2,000 x 0.05 = 100 requests are in flight on average, so a limit of 150 leaves headroom for bursts. Load tests then show where latency starts to climb, and the limit goes just below that point.

But the right number changes when a dependency slows down, when the code changes, or when instances get different hardware. An adaptive limiter, such as Netflix's concurrency-limits library, measures latency continuously and raises or lowers the limit automatically, which removes the guesswork.

7Follow-up questions

How would you make the limit adapt to latency instead of being fixed?

Use an algorithm that treats rising latency as a sign of queueing. AIMD increases the limit by one after successful requests and cuts it by a fraction when latency exceeds a target or requests time out, like TCP congestion control. Gradient-style algorithms, such as Gradient2 in Netflix's concurrency-limits library, compare current latency with a long-term baseline and shrink the limit as the ratio grows. In the filter, the library's limiter replaces the shared semaphore, acquired and released in the same places.

Why not block with acquire() and a timeout instead of tryAcquire()?

Blocking holds a Tomcat worker thread while waiting, which is exactly the resource we are trying to protect, and it adds queueing delay. Rejecting immediately is cheaper and gives the client a clear signal.

8Conclusion

In this answer, we built a concurrency-limiting filter with two semaphores and tryAcquire, so normal requests share 150 permits and critical requests can also use a reserve of 50, with 503, Retry-After and a per-priority Micrometer counter for rejections. We registered it early, exempted health endpoints, released permits exactly once including for async requests, refused to trust a client-set priority header, and treated the limit as a starting estimate for an adaptive limiter.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use two semaphores, a shared one with 150 permits and a reserve with 50, and only call tryAcquire, so the filter never blocks a Tomcat thread.

Then, if they want more

A normal request tries the shared pool. A critical one tries shared first and then the reserve, so normal traffic can never consume the critical headroom. If no permit is available, I set status 503, add Retry-After of one second, increment a Micrometer counter tagged with the priority, built once in the constructor, and return without calling chain.doFilter.

If a permit was taken, I call the chain inside try and release in finally. The pitfalls are where the real answer is.

First, leaks: any path that skips the release eventually rejects everything, and for async requests the finally block runs too early, so when request.isAsyncStarted is true I register an AsyncListener that releases on complete, error or timeout, guarded so it releases exactly once.

Second, the X-Priority header must not be trusted from outside; the gateway should overwrite it or we derive priority from the route and authenticated client. Third, registration: I would use a FilterRegistrationBean with high precedence so rejected requests skip security and parsing, and exempt liveness and metrics endpoints so an overloaded pod is not restarted.

Finally, 150 is a guess; I would start from Little's law and load tests and move to an adaptive limiter such as Netflix concurrency-limits.

About this answer

Last updated
13 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 official documentation for the version you use. 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 "Write a OncePerRequestFilter that allows 150 concurrent normal requests plus 50 reserved...": https://scrivio-interview-library.netlify.app/architecture/high-availability/5b3504e693/