How to apply IP based rate-limiting in spring boot

Viewed 1737

I want to apply rate-limit on the basis of IP for each (/get)service for my project for e.g each IP can access each service for a particular no. of time i.e 5 times /10 second. I have used bucket4j rate-limiting but it's not working. Does anyone have any idea about it??

this is my application.properties

spring.cache.jcache.config=classpath:ehcache.xml
logging.level.org.ehcache=info
bucket4j.enabled=true
bucket4j.filters[0].cache-name=buckets
bucket4j.filters[0].filter-method=servlet
bucket4j.filters[0].url=.* 
bucket4j.filters[0].rate-limits[0].bandwidths[0].capacity=5
bucket4j.filters[0].rate-limits[0].bandwidths[0].time=10
bucket4j.filters[0].rate-limits[0].bandwidths[0].unit=seconds
bucket4j.filters[0].rate-limits[0].expression="getRemoteAddress()"
bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval=0
bucket4j.filters[0].rate-limits[0].bandwidths[0].fixed-refill-interval-unit=seconds

this is encache.xml

<config xmlns='http://www.ehcache.org/v3'
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
        xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
        http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
    <cache alias="buckets">
        <expiry><ttl unit="seconds">6</ttl></expiry>
        <heap unit="entries">2000</heap>
        <jsr107:mbeans enable-statistics="true"/>
    </cache>
</config>

pom.xml

<dependency>
    <groupId>com.giffing.bucket4j.spring.boot.starter</groupId>
    <artifactId>bucket4j-spring-boot-starter</artifactId>
    <version>0.2.0</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <scope>runtime</scope>
</dependency>

server Initializer

@EnableCaching
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(EwseparationApplication.class);
    }

}
1 Answers

I was having the same issue. It looks like there was an issue opened with the bucket4j spring boot starter github project about this (link).

I converted my application.properties to application.yml as the individual reported in the issue and my rate limit started working. I'm not sure what the actual issue is (why application.yml works and application.properties does not). I kindof prefer the properties format over yml.

Related