How to Integrate Sentinel with Spring Boot for Flow Control, Circuit Breaking, and Rate Limiting

This guide explains how to add Alibaba Sentinel to a Spring Boot microservice, covering core concepts, Maven dependencies, YAML configuration, dashboard startup, practical code examples for flow control and circuit breaking, and rule persistence with Nacos for robust high‑availability services.

Ray's Galactic Tech
Ray's Galactic Tech
Ray's Galactic Tech
How to Integrate Sentinel with Spring Boot for Flow Control, Circuit Breaking, and Rate Limiting

Introduction

Sentinel is an open‑source traffic‑control component for distributed microservice architectures. It provides flow control, circuit breaking with downgrade, and system adaptive protection to improve service stability.

Core Concepts

Flow Control : Monitors QPS, concurrent threads and other metrics, then limits burst traffic to avoid overload.

Circuit Breaking & Downgrade : When error rate or response latency exceeds configured thresholds, Sentinel triggers fast failure and returns a downgrade result, preventing cascade failures.

System Adaptive Protection : Protects the whole system based on overall load, ensuring stability during traffic spikes.

Integration Steps

2.1 Add Maven Dependencies

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.alibaba.cloud</groupId>
      <artifactId>spring-cloud-alibaba-dependencies</artifactId>
      <version>2022.0.0.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependencies>
  <!-- Spring Boot Web -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <!-- Sentinel Starter -->
  <dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
  </dependency>
  <!-- Sentinel + Nacos datasource (recommended for production) -->
  <dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
  </dependency>
  <!-- Actuator monitoring endpoint -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
</dependencies>

2.2 Basic Configuration (application.yml)

server:
  port: 8080
spring:
  application:
    name: demo-app
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719
      eager: true
      datasource:
        flow-rules:
          nacos:
            server-addr: localhost:8848
            data-id: demo-app-sentinel-flow
            group-id: DEFAULT_GROUP
            rule-type: flow

2.3 Start Sentinel Dashboard

Download the dashboard from the Sentinel GitHub releases page: https://github.com/alibaba/Sentinel/releases

Run the dashboard with the following command:

java -Dserver.port=8080 -jar sentinel-dashboard.jar

Access the dashboard at http://localhost:8080. Default credentials are sentinel / sentinel.

Feature Demonstrations

3.1 Flow Control (Rate Limiting)

@RestController
public class TestController {
    @GetMapping("/test")
    @SentinelResource(value = "testResource", blockHandler = "handleBlock")
    public String test() {
        return "Normal Response!";
    }
    public String handleBlock(BlockException ex) {
        return "Blocked by Sentinel: " + ex.getClass().getSimpleName();
    }
}

Set the QPS threshold to 2 in the dashboard; requests exceeding this value invoke handleBlock.

3.2 Circuit Breaking & Downgrade

@GetMapping("/slow")
@SentinelResource(value = "slowResource", blockHandler = "handleBlock", fallback = "handleFallback")
public String slow() throws InterruptedException {
    if (Math.random() > 0.5) {
        Thread.sleep(1000);
    } else if (Math.random() > 0.8) {
        throw new RuntimeException("Error occurred");
    }
    return "OK";
}
public String handleBlock(BlockException ex) {
    return "Blocked: " + ex.getMessage();
}
public String handleFallback(Throwable t) {
    return "Fallback: " + t.getMessage();
}

In the dashboard you can configure a slow‑call ratio rule, for example: if 50 % of requests take longer than 500 ms, trigger a 5‑second circuit break.

3.3 Persist Rules to Nacos

Create a Nacos Data ID demo-app-sentinel-flow with the following JSON content:

[
  {
    "resource": "testResource",
    "limitApp": "default",
    "grade": 1,
    "count": 2,
    "strategy": 0,
    "controlBehavior": 0,
    "clusterMode": false
  }
]

Sentinel loads the rules from Nacos at startup, and the rules survive both application and dashboard restarts.

Key Practices

Implement a blockHandler method to process BlockException when a rule fires.

Implement a fallback method to handle business exceptions.

Persist Sentinel rules in an external store such as Nacos or Apollo.

Determine thresholds based on load‑testing results and real traffic, and adjust them dynamically.

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.

NacosSpring BootsentinelFlow ControlCircuit Breaking
Ray's Galactic Tech
Written by

Ray's Galactic Tech

Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!

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.