Implement Rate Limiting in Spring Cloud Zuul Using Spring Cloud Zuul‑RateLimit
This tutorial explains how to add request rate limiting to Spring Cloud Netflix Zuul by integrating the spring‑cloud‑zuul‑ratelimit library, configuring Maven dependencies, defining controller endpoints, setting up Zuul and rate‑limit policies in application.yml, and customizing key generators and error handling.
1. Introduction
Spring Cloud Netflix Zuul is an open‑source gateway that adds special features to Spring Boot applications, but it does not provide rate limiting out of the box. This tutorial explores how to add request rate limiting using Spring Cloud Zuul RateLimit.
2. Maven Configuration
In addition to the Spring Cloud Netflix Zuul dependency, add the Spring Cloud Zuul RateLimit dependency to pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
<dependency>
<groupId>com.marcosbarbero.cloud</groupId>
<artifactId>spring-cloud-zuul-ratelimit</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>3. Controller Example
Create REST endpoints that will be rate‑limited. No special code is required in the controller itself.
@Controller
@RequestMapping("/greeting")
public class GreetingController {
@GetMapping("/simple")
public ResponseEntity<String> getSimple() {
return ResponseEntity.ok("Hi!");
}
@GetMapping("/advanced")
public ResponseEntity<String> getAdvanced() {
return ResponseEntity.ok("Hello, how you doing?");
}
}The rate‑limit logic will be applied via configuration, keeping the code decoupled.
4. Zuul Configuration
Add the following configuration to application.yml:
zuul:
routes:
serviceSimple:
path: /greeting/simple
url: forward:/
serviceAdvanced:
path: /greeting/advanced
url: forward:/
ratelimit:
enabled: true
repository: JPA
policy-list:
serviceSimple:
- limit: 5
refresh-interval: 60
type:
- origin
serviceAdvanced:
- limit: 1
refresh-interval: 2
type:
- origin
strip-prefix: trueUnder zuul.routes the endpoint details are defined, while zuul.ratelimit.policy-list specifies the rate‑limit settings. The limit attribute defines how many requests are allowed within the refresh-interval window.
In this example, serviceSimple is limited to 5 requests per 60 seconds, whereas serviceAdvanced is limited to 1 request per 2 seconds.
The type property determines the rate‑limit strategy. Possible values are:
origin – limit based on the original client request
url – limit based on the downstream service path
user – limit based on authenticated or anonymous user
(empty) – global configuration for the service when type is omitted
5. Testing Rate Limiting
5.1 Requests Within the Limit
Send a request to /greeting/simple. The response includes rate‑limit headers:
X-RateLimit-Limit-rate-limit-application_serviceSimple_127.0.0.1: 5
X-RateLimit-Remaining-rate-limit-application_serviceSimple_127.0.0.1: 4
X-RateLimit-Reset-rate-limit-application_serviceSimple_127.0.0.1: 60000These headers indicate the configured limit, the remaining calls, and the remaining time in milliseconds until the window resets.
5.2 Requests Exceeding the Limit
Calling /greeting/advanced twice in quick succession (limit 1 per 2 seconds) results in a 429 TOO_MANY_REQUESTS response. The headers show the exhausted limit:
X-RateLimit-Limit-rate-limit-application_serviceAdvanced_127.0.0.1: 1
X-RateLimit-Remaining-rate-limit-application_serviceAdvanced_127.0.0.1: 0
X-RateLimit-Reset-rate-limit-application_serviceAdvanced_127.0.0.1: 268After waiting for the refresh interval (2 seconds), the endpoint can be called successfully again.
6. Custom Key Generator
A custom RateLimitKeyGenerator can be defined to modify the key used for rate limiting, for example by appending the HTTP method:
@Bean
public RateLimitKeyGenerator rateLimitKeyGenerator(RateLimitProperties properties, RateLimitUtils utils) {
return new DefaultRateLimitKeyGenerator(properties, utils) {
@Override
public String key(HttpServletRequest request, Route route, RateLimitProperties.Policy policy) {
return super.key(request, route, policy) + "_" + request.getMethod();
}
};
}This will produce keys such as
X-RateLimit-Limit-rate-limit-application_serviceSimple_127.0.0.1_GET.
7. Personalized Error Handling
The library supports different storage implementations (e.g., Spring Data JPA, Redis). By default, failures are logged via DefaultRateLimiterErrorHandler. To customize error handling, provide a bean implementing RateLimiterErrorHandler:
@Bean
public RateLimiterErrorHandler rateLimitErrorHandler() {
return new DefaultRateLimiterErrorHandler() {
@Override
public void handleSaveError(String key, Exception e) {
// custom implementation
}
@Override
public void handleFetchError(String key, Exception e) {
// custom implementation
}
@Override
public void handleError(String msg, Exception e) {
// custom implementation
}
};
}Both the custom key generator and error handler are automatically picked up by Spring Cloud Zuul RateLimit.
8. Conclusion
This article demonstrated how to integrate request rate limiting into Spring Cloud Netflix Zuul using the spring‑cloud‑zuul‑ratelimit library, covering dependency setup, controller definition, configuration, testing, and customization options. The full source code is available on GitHub.
Original article: https://www.baeldung.com/spring-cloud-zuul-rate-limit Author: Ganesh Pagade Translator: shirehappy
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.
