Backend Development 10 min read

Integrating Alibaba Sentinel for Rate Limiting in Spring Cloud Gateway

This article explains how to integrate Alibaba Sentinel with Spring Cloud Gateway to configure rate‑limiting and circuit‑breaker rules, covering Maven dependencies, Java configuration classes, Sentinel rule definitions, and optional console‑based management for robust backend API protection.

Architect's Tech Stack
Architect's Tech Stack
Architect's Tech Stack
Integrating Alibaba Sentinel for Rate Limiting in Spring Cloud Gateway

Alibaba Sentinel supports rate limiting and circuit breaking for popular API gateways such as Spring Cloud Gateway and Netflix Zuul. This guide shows how to replace Hystrix with Sentinel in a Spring Cloud Gateway project.

1. Introduction

Sentinel can be used to limit traffic and handle fallback in Spring Cloud Gateway.

2. Integration Steps

2.1 Add Maven dependencies

Two options are provided:

Only include sentinel-spring-cloud-gateway-adapter :

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
    <version>x.y.z</version>
</dependency>

Or, if you need console management, replace the adapter with spring-cloud-starter-alibaba-sentinel and spring-cloud-alibaba-sentinel-gateway :

<!-- Add these dependencies for console management -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

2.2 Register Sentinel filter beans

Inject SentinelGatewayFilter and SentinelGatewayBlockExceptionHandler in a configuration class:

@Configuration
public class GatewayConfiguration {
    private final List
viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfiguration(ObjectProvider
> viewResolversProvider,
                               ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }
}

2.3 Configure rate‑limiting rules

You can either use the Sentinel console or define rules directly in Java. Example of a console‑based configuration in application.yml :

spring:
  cloud:
    sentinel:
      transport:
        port: 8739
        dashboard: 10.1.3.77:9090
      eager: true
      datasource:
        ds:
          nacos:
            server-addr: 10.1.3.76:8848
            dataId: ${spring.application.name}-sentinel
            groupId: DEFAULT_GROUP
            namespace: sms-dev
            rule-type: flow
sentinel:
  dashboard:
    auth:
      username: sentinel
      password: sentinel

Or define rules programmatically:

@Configuration
public class GatewaySentinelConfiguration {
    // ... same bean definitions as above ...

    @PostConstruct
    public void doInit() {
        initGatewayRules();
        initBlockHandler();
    }

    private void initGatewayRules() {
        Set
rules = new HashSet<>();
        rules.add(new GatewayFlowRule("url-proxy-1").setCount(1).setIntervalSec(60));
        rules.add(new GatewayFlowRule("api-service").setCount(5).setIntervalSec(60));
        GatewayRuleManager.loadRules(rules);
        initCustomizedApis();
        DegradeRule degradeRule = new DegradeRule("api-service")
                .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO)
                .setCount(0.5)
                .setTimeWindow(10);
        DegradeRuleManager.loadRules(Collections.singletonList(degradeRule));
    }

    private void initBlockHandler() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono
handleRequest(ServerWebExchange exchange, Throwable throwable) {
                Map
result = new HashMap<>(3);
                result.put("code", String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value()));
                result.put("message", HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
                result.put("x", "xx");
                return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromObject(result));
            }
        };
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }

    private void initCustomizedApis() {
        Set
definitions = new HashSet<>();
        ApiDefinition api1 = new ApiDefinition("product-api")
                .setPredicateItems(new HashSet
() {{
                    add(new ApiPathPredicateItem()
                        .setPattern("/product-service/product/**")
                        .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});
        ApiDefinition api2 = new ApiDefinition("order-api")
                .setPredicateItems(new HashSet
() {{
                    add(new ApiPathPredicateItem().setPattern("/order-service/order/index"));
                }});
        definitions.add(api1);
        definitions.add(api2);
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }
}

3. Summary

If you use Sentinel with Gateway, it is recommended to configure detailed rate‑limiting and circuit‑breaker rules through the Sentinel console. Otherwise, the built‑in RequestRateLimiter or Hystrix can be used. Since version 1.6.0, Sentinel provides a dedicated Spring Cloud Gateway adapter supporting both route‑level and custom API‑level limiting.

backendJavamicroservicesrate limitingSpring Cloud GatewayAlibaba Sentinel
Architect's Tech Stack
Written by

Architect's Tech Stack

Java backend, microservices, distributed systems, containerized programming, and more.

0 followers
Reader feedback

How this landed with the community

login 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.