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?
3
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:
2) You can use in testing an Embedded Redis Server as it is explained in the following article by adding the maven dependency:
And including the following snippet:
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.
Cause: SCG (Spring Cloud Gateway) is not able to connect with redis server
Fix: Connect SCG to redis server to get correct headers
Details
Check debug logs to verify the issue
You may check logs by adding the following property in application.yml
You will see the following logs when you will execute a request (and that request response will come with X-RateLimit-Remaining -1).
Spin Up Redis Server
Spin up a Redis server by executing the following docker-compose script using
docker compose -f {file-name} up -d
Add redis props in spring application
Add the following props in application.yml to connect with redis server (I deliberately changed the default port of redis to 50988)
Now, restart your application. SCG should be able to connect with redis server.
Thanks