Integrating Alibaba Sentinel with Spring Cloud Gateway for Rate Limiting

This article demonstrates how to integrate Alibaba Sentinel into Spring Cloud Gateway to implement both route‑level and custom API‑level rate limiting, covering project setup, Maven dependencies, configuration files, custom block responses, and the importance of combining gateway and service‑side throttling for robust microservice protection.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Integrating Alibaba Sentinel with Spring Cloud Gateway for Rate Limiting

The author introduces a tutorial on applying rate limiting to Spring Cloud Gateway using Alibaba Sentinel, starting with a brief overview of the built‑in RequestRateLimiterGatewayFilterFactory and then focusing on Sentinel integration.

Two limiting dimensions are described: route dimension , which limits traffic per route ID, and custom API dimension , which allows fine‑grained control over specific URI patterns across services.

Project Setup

A new module named gateway-sentinel9026 is created, and the following Maven dependencies are added:

<!--nacos注册中心-->
<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<!--spring cloud gateway-->
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

<!--spring cloud gateway integration with sentinel-->
<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

<!--sentinel core dependency-->
<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

A note reminds that the project should remain a gateway service and not include web dependencies.

Configuration File

The application.yml config defines Sentinel dashboard address, Nacos discovery settings, and a sample route:

spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
        - id: gateway-provider
          uri: lb://gateway-provider
          predicates:
            - Path=/gateway/provider/**

This route will be monitored by Sentinel, and the author shows screenshots of the Sentinel console where the route appears.

Rate‑Limiting Configuration

Using the Sentinel console, a route‑level rule is added with a QPS threshold of 1, demonstrating that subsequent rapid requests are blocked.

For API‑level limiting, an API group is created (exact match on http://xxxx/gateway/provider/port) and a flow‑control rule is attached, enabling fine‑grained throttling across multiple services.

Customizing Block Responses

Two approaches are presented:

Configuration‑based : Define spring.cloud.sentinel.scg.fallback with mode: response and a custom JSON body, or mode: redirect with a target URL.

Code‑based : Implement a BlockRequestHandler bean that returns a custom JSON payload.

Example configuration for a JSON response:

spring:
  cloud:
    sentinel:
      scg:
        fallback:
          mode: response
          response-status: 200
          response-body: '{"code": 200,"message": "请求失败,稍后重试!"}'

Example Java code for a custom handler:

@Configuration
public class GatewayConfig {
    @PostConstruct
    public void initBlockHandlers() {
        BlockRequestHandler blockHandler = (exchange, throwable) -> {
            Map map = new HashMap();
            map.put("code", 200);
            map.put("message", "请求失败,稍后重试!");
            return ServerResponse.status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(BodyInserters.fromObject(map));
        };
        GatewayCallbackManager.setBlockHandler(blockHandler);
    }
}

Why Gateway Limiting Alone Is Not Sufficient

The author explains that in a microservice architecture, services can be invoked directly by other services (e.g., order service calling product service). Therefore, internal services also need their own throttling mechanisms in addition to gateway limits.

Conclusion

The article summarizes the steps to integrate Sentinel with Spring Cloud Gateway for rate limiting, discusses customization options, and emphasizes the need for both gateway‑level and service‑level protection in complex microservice systems.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javasentinelrate limitingSpring Cloud Gateway
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.