Master Distributed Rate Limiting with Spring Cloud Zuul Ratelimit
This article explains how to integrate spring-cloud-zuul-ratelimit with Zuul for distributed rate limiting, covering supported granularity levels, storage back‑ends, YAML configuration examples, custom key generators, and practical demonstration using Redis and Spring Boot Actuator.
Introduction
spring-cloud-zuul-ratelimit is an extension that integrates with Zuul to provide distributed rate‑limiting strategies. By adding a few lines in the YAML configuration, an application can support rate limiting.
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit</artifactId>
<version>1.3.4.RELEASE</version>
</dependency>Supported Rate‑Limit Granularity
Service granularity (default, limits per service module)
User granularity
ORIGIN granularity (based on request origin)
API granularity (based on request path)
Combinations of the above
Custom RateLimitKeyGenerator implementation for additional keys
Supported Storage Back‑ends
InMemoryRateLimiter – uses ConcurrentHashMap as storage
ConsulRateLimiter – uses Consul
RedisRateLimiter – uses Redis
SpringDataRateLimiter – uses a database
Rate‑Limit Configuration
zuul:
ratelimit:
key-prefix: your-prefix
enabled: true
repository: REDIS
behind-proxy: true
policies:
myServiceId:
limit: 10
quota: 20
refresh-interval: 30
type:
- userThe above configuration means that within a 30‑second window, a maximum of 10 requests are allowed, or the total accumulated request time must be less than 20 seconds.
Effect Demonstration
YAML example:
zuul:
ratelimit:
key-prefix: pig-ratelimite
enabled: true
repository: REDIS
behind-proxy: true
policies:
pig-admin-service:
limit: 2
quota: 1
refresh-interval: 3Dynamic chart:
Redis data structure (red text highlights important fields):
Summary
Spring Boot Actuator can expose service status to dynamically toggle rate‑limit switches.
Source code reference: https://gitee.com/log4j/pig
If your project integrates Shiro or Spring Security, the UserPrincipal is automatically maintained; otherwise, ensure the request’s UserPrincipal is set after login to use user‑level rate limiting (default is anonymous). See DefaultRateLimitKeyGenerator for the USER type implementation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
