Edit online

How to Enable the Rate Limit Filter

According to the Apache Tomcat Documentation, the Rate Limit Filter can help mitigate Denial of Service (DoS) and Brute Force attacks by limiting the number of a requests that are allowed from a single IP address within a time window (e.g. 300 Requests per 60 seconds). This topic explains how to enable the Rate Limit Filter.

CAUTION: If Tomcat is behind a reverse proxy then you must make sure that the Rate Limit Filter sees the client IP address. For example, if you are using the Remote IP Filter, then the filter mapping for the Rate Limit Filter must come after the mapping of the Remote IP Filter to ensure that each request has its IP address resolved before the Rate Limit Filter is applied. Failure to do so will count requests from different IPs in the same bucket and will result in a self-inflicted DoS attack.

To enable the Rate Limit Filter:

  1. Locate the web.xml file that is used by the Tomcat server.
  2. Define the Rate Limit Filter:

    You need to define the filter within the web.xml file. This involves specifying the filter name, the filter class, and any initialization parameters such as the allowed number of requests and the time period for these requests.

    The Rate Limit Filter supports the following initialization parameters (from the Apache Tomcat Documentation):

    Attribute Description
    bucketDuration The number of seconds in a time bucket. Default is 60.
    bucketRequests The number of requests that are allowed in a time bucket. Default is 300.
    enforce Set to false to allow requests through even when they exceed the maximum allowed per time window. Your application code can still inspect the Request Attribute org.apache.catalina.filters.RateLimitFilter.Count to retrieve the number of Requests made from that IP within the time window. Default is true.
    statusCode The status code to return when a request is dropped. Default is 429.
    statusMessage The status message to return when a request is dropped. Default is Too many requests.
    Code example:
    <!-- web.xml -->  
    
        <filter>
           <filter-name>RateLimitFilter Global</filter-name>
           <filter-class > org.apache.catalina.filters.RateLimitFilter</filter-class >
           <init-param>
                <param-name>bucketRequests</param-name>
                <param-value>100</param-value>
            </init-param>
    	<init-param>
                <param-name>bucketDuration</param-name>
                <param-value>60</param-value>
    	</init-param>
        </filter>
  3. Map the filter to URL patterns:

    You need to map the filter to specific URL patterns within your application. This determines which requests are subjected to rate limiting.

    Code example:
    <!-- web.xml -->
    
        <filter-mapping>
    	<filter-name>RateLimitFilter Global</filter-name>
    	<url-pattern>*</url-pattern>
        </filter-mapping>
  4. Deploy/Restart the Tomcat server.