WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Boot & Hibernate · Expert · question 79 of 100

How can you implement rate limiting in a Spring Boot REST API to protect against excessive requests?

📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

Rate limiting is a technique used to limit the number of requests processed within a certain time frame, preventing the overloading of the server and protecting it against denial-of-service attacks. In a Spring Boot application, rate limiting can be implemented using various techniques, including:

Throttling with Interceptors: Interceptors can be used to limit the rate of incoming requests by adding a delay between requests or returning an error message if the rate exceeds a certain threshold. This can be achieved by creating a custom interceptor and registering it with the Spring MVC interceptor registry.

Example:

    @Component
    public class RateLimitInterceptor extends HandlerInterceptorAdapter {
        
        private final RateLimiter rateLimiter = RateLimiter.create(10);
        
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            if (rateLimiter.tryAcquire()) {
                return true;
            } else {
                response.setStatus(HttpStatus.TOO\_MANY\_REQUESTS.value());
                return false;
            }
        }
    }

Here, we’re using Google Guava’s RateLimiter class to limit the rate of incoming requests to 10 per second. The preHandle method checks if a request can be processed by calling tryAcquire() on the RateLimiter. If the rate exceeds the limit, it returns an HTTP status code of 429 (Too Many Requests).

Throttling with Filters: Filters can also be used to limit the rate of incoming requests by intercepting requests before they reach the controller. This can be achieved by creating a custom filter and registering it with the Spring Boot filter chain.

Example:

    @Component
    public class RateLimitFilter extends OncePerRequestFilter {
        
        private final RateLimiter rateLimiter = RateLimiter.create(10);
        
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            if (rateLimiter.tryAcquire()) {
                filterChain.doFilter(request, response);
            } else {
                response.setStatus(HttpStatus.TOO\_MANY\_REQUESTS.value());
            }
        }
    }

Here, we’re using the same RateLimiter class to limit the rate of incoming requests to 10 per second. The doFilterInternal method intercepts incoming requests and checks if they can be processed by calling tryAcquire() on the RateLimiter. If the rate exceeds the limit, it returns an HTTP status code of 429 (Too Many Requests).

Throttling with Spring Cloud Gateway: Spring Cloud Gateway is a lightweight API gateway that can be used to route requests to multiple microservices. It provides built-in support for rate limiting using the RequestRateLimiter filter.

Example:

spring:
  cloud:
    gateway:
      routes:
      - id: service-a
        uri: http://localhost:8081
        predicates:
        - Path=/service-a/**
        filters:
        - RequestRateLimiter=10,1

Here, we’re using the RequestRateLimiter filter to limit the rate of incoming requests to 10 per second with a burst capacity of 1 request. This limits the number of requests that can be processed within a certain time frame and protects the server against overloading.

In conclusion, rate limiting is an essential technique for protecting servers against denial-of-service attacks and overloading. In a Spring Boot application, it can be implemented using various techniques such as interceptors, filters, or using Spring Cloud Gateway.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Boot & Hibernate interview — then scores it.
📞 Practice Spring Boot & Hibernate — free 15 min
📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

All 100 Spring Boot & Hibernate questions · All topics