'Spring boot (.2.3.0.RELEASE) with bucket4j rate limit not working

I am trying to use limit rate API for a Spring Boot Rest application, with bucket4j based on the following online resource

Please find my configuration below:

Below is maven dependency added to use 4bucketj:

...
    <dependency>
            <groupId>com.giffing.bucket4j.spring.boot.starter</groupId>
            <artifactId>bucket4j-spring-boot-starter</artifactId>
            <version>0.4.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>
..

Below is my application.yml config:

spring:
  main:
    allow-bean-definition-overriding: true
  cache:
    jcache:
      config: classpath:ehcache.xml
bucket4j:
  enabled: true
  filters:
    - cache-name: buckets
      url: .*
      http-response-body: "{ \"status\": 429, \"error\": \"Too Many Requests\", \"message\": \"You have exhausted your API Request Quota\" }"
      rate-limits:
        - bandwidths:
            - capacity: 2
              time: 1
              unit: minutes

Below I have added ehcache.xml in path src/main/resources/:

<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">3600</ttl>
        </expiry>
        <heap unit="entries">1000000</heap>
        <jsr107:mbeans enable-statistics="true"/>
    </cache>

Finally, I have added @EnableCachingin a config class which is being loaded when spring starts.

Based on the config in the application.yml file the API should not accept more than 2 request in one minute and if it is more that two requests, an error should be triggered as stated (http-response-body) in application.yml.

I have deployed the application on my PC and with Postman tool I am able to hit a Rest API more than 10 times within one minute with no error message.

Can anyone please advise why the error message is not triggered, since it should allow only 2 requests and I am sending 10 instead?



Solution 1:[1]

I got it working by following this guide from the point 6 onwards, but the only difference i can spot with your implementation is the caching system, so i can guess the problem lies there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manuel Materazzo