Spring Boot app serving only fixed number of customers for a specific endpoint
Problem Scenario: -
I have a spring boot application that acts as the backend for a frontned application that many users use. it has many rest controllers and hence many end points.
One of the endpoints is an excel generation endpoint. But, since I use a library that consumes lot of RAM to generate and build the excel, I cannot allow more than 3 excel generation concurrent requests to be processed by my spring boot application, else the app will crash with out of memory exception. Write a program to achieve this.
Answer:-
We can achieve this in Spring Boot by implementing a custom HandlerInterceptor along with a Semaphore to limit concurrent access to the Excel generation endpoint.
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.Semaphore;
@Component
public class ExcelGenerationInterceptor implements HandlerInterceptor {
private final Semaphore semaphore;
public ExcelGenerationInterceptor() {
this.semaphore = new Semaphore(3); // Limiting to 3 concurrent requests
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if ("/generateExcel".equals(request.getRequestURI())) {
try {
semaphore.acquire(); // Acquire a permit
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
if ("/generateExcel".equals(request.getRequestURI())) {
semaphore.release(); // Release the permit after request completion
}
}
}
This interceptor limits access to the /generateExcel endpoint by allowing only 3 concurrent requests to proceed at a time. Requests to other endpoints are not affected.
You need to register this interceptor in your Spring Boot application. You can do this by adding it to your WebMvcConfigurer configuration:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ExcelGenerationInterceptor()).addPathPatterns("/**");
}
}
With this setup, your Spring Boot application will only allow a maximum of 3 concurrent requests to the Excel generation endpoint while allowing other endpoints to function normally.