Why X-RateLimit-Remaining -1 in response header while using spring cloud api gateway ratelimit with redis?

Viewed 779

I implemented ratelimit with redis in my spring cloud api gateway. Here is part of application.yml:

spring:  
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true
      discovery:
        locator:
          enabled: true
      routes:
        - id: test-rest-service
          uri: lb://test-rest-service
          predicates:
            - Path=/test/**
          filters:
            - RewritePath=/test/(?<path>.*), /$\{path}
            - name: RequestRateLimiter
              args:
                key-resolver: "#{@userRemoteAddressResolver}"
                redis-rate-limiter.replenishRate: 2
                redis-rate-limiter.burstCapacity: 3

I called a GET API via postman and checked response header.

X-RateLimit-Remaining -1
X-RateLimit-Burst-Capacity 3
X-RateLimit-Replenish-Rate 2

The rate limit is not working. Why am I getting negative value for X-RateLimit-Remaining? What does it mean? How do I fix it?

2 Answers

This happened to me because there was no Redis instance launched. You have two options:

1) Download and run a Redis instance using docker:

docker run --name redis -d redis

2) You can use in testing an Embedded Redis Server as it is explained in the following article by adding the maven dependency:

<dependency>
  <groupId>it.ozimov</groupId>
  <artifactId>embedded-redis</artifactId>
  <version>0.7.2</version>
  <scope>test</scope>
</dependency>

And including the following snippet:

@TestConfiguration
public class TestRedisConfiguration {

    private RedisServer redisServer;

    public TestRedisConfiguration() {
        this.redisServer = new RedisServer(6379);
    }

    @PostConstruct
    public void postConstruct() {
        redisServer.start();
    }

    @PreDestroy
    public void preDestroy() {
        redisServer.stop();
    }
}

I faced the same issue recently. In my case, there was an older version of Redis installed which caused X-RateLimit-Remaining to be set to -1 constantly.

redis-cli shutdown
Related