Spring Boot Service Circuit Breaking and Degradation with Sentinel: A Practical Guide

This article explains how microservice architectures suffer from cascading failures and demonstrates how to use Sentinel for rate limiting, circuit breaking, and degradation—including architecture, configuration, code examples, and best‑practice tips—to achieve high‑availability Spring Boot services.

Java Tech Workshop
Java Tech Workshop
Java Tech Workshop
Spring Boot Service Circuit Breaking and Degradation with Sentinel: A Practical Guide

1. Service Avalanche and Fault‑Tolerance Basics

In a microservice chain (gateway → business service → downstream service), a downstream timeout, database stall, or third‑party outage blocks upstream threads, fills the thread pool, spikes CPU usage, and can cause a full cluster collapse—known as a service avalanche.

The three core fault‑tolerance mechanisms are rate limiting, circuit breaking, and degradation. Hystrix is no longer maintained; Sentinel, an Alibaba open‑source project, offers lightweight performance, visual control, dynamic rule updates, and comprehensive coverage, making it the de‑facto standard in Chinese enterprises.

2. Three Core Mechanisms

Rate limiting acts as the first line of defense at the entry point, capping request volume to prevent traffic spikes or malicious floods from overwhelming a service.

Circuit breaking is a passive safeguard that detects downstream error or timeout rates exceeding thresholds and cuts off calls to prevent fault propagation.

Degradation is an active safeguard triggered by high own‑service load or business‑priority rules; it shuts down non‑critical interfaces and returns fallback data to preserve core functionality.

3. Circuit Breaker vs. Degradation

Circuit breaking reacts to downstream failures (“don’t be dragged down”), using three states (closed, open, half‑open) and automatic recovery detection. Degradation reacts to own load or priority (“reduce burden”), invoking fallback methods only for business exceptions, timeouts, or circuit‑break events.

4. Sentinel Architecture

Sentinel uses a lightweight responsibility‑chain slot mechanism where each request passes through a fixed verification chain: request → node selection → cluster statistics → rate‑limit check → circuit‑break/degrade check → system load protection → business logic. Its core capabilities include sliding‑window QPS/exception‑rate statistics, semaphore‑based concurrency isolation, second‑level real‑time metrics, and multi‑channel dynamic rule configuration (memory, Nacos, Apollo) without service restarts.

5. Sentinel vs. Hystrix

Compared with Hystrix, Sentinel is actively maintained, uses a thread‑free semaphore model for superior performance, provides an integrated visual dashboard, supports hot‑reloading of rules, and covers all scenarios (rate limiting, circuit breaking, degradation, hotspot parameter limiting, system protection).

6. Production Setup

Compatible versions: Spring Boot 2.7.15, Spring Cloud 2021.0.5, Spring Cloud Alibaba 2021.0.5.0. Maven dependencies include spring‑boot‑starter‑web, spring‑cloud‑starter‑alibaba‑nacos‑discovery, spring‑cloud‑starter‑alibaba‑sentinel, and spring‑boot‑starter‑actuator.

<dependencies>
    <!-- Web service core -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Nacos service discovery -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

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

    <!-- Actuator for monitoring -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

Application.yml configures server port, Nacos address, Sentinel dashboard (127.0.0.1:8080, port 8719), heartbeat interval, and exposes all actuator endpoints.

Start the Sentinel dashboard with java -jar sentinel-dashboard-1.8.6.jar and access it at http://localhost:8080 (default credentials: sentinel/sentinel).

7. @SentinelResource Annotation

The annotation marks a method as a Sentinel resource and binds fallback and block‑handler methods. Key attributes: value: unique resource name used in the dashboard. blockHandler: handles rate‑limit or blacklist interceptions. fallback: handles business exceptions, timeouts, or circuit‑break triggers. exceptionsToIgnore: exceptions that should bypass degradation.

8. Example Controller

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SentinelDegradeController {

    // Core business API with limit and degrade handlers
    @GetMapping("/order/get/{id}")
    @SentinelResource(
            value = "orderGetResource",
            fallback = "fallbackHandler",
            blockHandler = "blockHandler"
    )
    public String getOrder(@PathVariable Integer id) {
        // Simulate business exception
        if (id == 0) {
            throw new RuntimeException("业务参数异常");
        }
        // Simulate timeout (uncomment to trigger circuit break)
        // try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
        return "查询订单成功,ID:" + id;
    }

    // Degrade fallback for business exception / timeout / circuit break
    public String fallbackHandler(Integer id, Throwable e) {
        return "【服务降级】订单服务暂时不可用,请稍后重试!异常:" + e.getMessage();
    }

    // Rate‑limit block handler
    public String blockHandler(Integer id, BlockException e) {
        return "【请求限流】访问过于频繁,请稍后再试!";
    }
}

9. Circuit‑Break Strategies

Sentinel provides three strategies:

Slow‑call ratio : triggers when the proportion of calls exceeding a latency threshold (e.g., 500 ms) reaches a configured percentage (e.g., 50 % over 10 s with a minimum of 5 requests).

Exception ratio : triggers when the error‑rate exceeds a threshold.

Exception count : triggers when the absolute number of errors reaches a fixed limit.

10. Multi‑Dimensional Rate Limiting

Sentinel supports QPS limiting, thread‑count limiting, and intelligent modes (direct,关联,链路) to protect core interfaces when associated non‑core traffic spikes.

11. Hot‑Parameter Protection

For flash‑sale or hot‑item scenarios, Sentinel can limit a single request parameter (e.g., product ID) without affecting other traffic. Example:

@GetMapping("/goods/hot")
@SentinelResource(value = "hotGoodsResource")
public String hotGoods(Integer goodsId) {
    return "查询热门商品成功:" + goodsId;
}

12. System‑Wide Adaptive Protection

Beyond interface‑level rules, Sentinel can protect the whole machine by setting maximum QPS, max concurrent threads, CPU usage, and system load thresholds; excess requests are rejected when any limit is reached.

13. Persistence with Nacos

Persist flow and degrade rules in Nacos to survive restarts and enable real‑time rule refresh in a clustered deployment.

spring:
  cloud:
    sentinel:
      datasource:
        flow:
          nacos:
            server-addr: 127.0.0.1:8848
            data-id: sentinel-flow-rule.json
            group-id: DEFAULT_GROUP
            rule-type: flow
        degrade:
          nacos:
            server-addr: 127.0.0.1:8848
            data-id: sentinel-degrade-rule.json
            group-id: DEFAULT_GROUP
            rule-type: degrade

14. Gateway + Sentinel Global Protection

Instead of configuring each service separately, integrate Sentinel at the gateway layer to apply unified rate‑limit, circuit‑break, and degradation rules across all microservices.

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>

15. Common Pitfalls

Fallback methods ineffective if @SentinelResource is missing, parameters mismatch, or degradation/limit handlers are confused.

Rules disappear on restart when only in‑memory storage is used; enable Nacos persistence.

Circuit‑break may not fire if request count is below the minimum threshold, timeout is too large, or resource name mismatches.

No monitoring data appears when the service cannot reach the dashboard, heartbeat is misconfigured, or registration to Nacos fails.

Mixing degradation and limit logic leads to unexpected behavior; keep fallback for business errors and blockHandler for rate‑limit events.

16. Final Thoughts

Circuit breaking, degradation, and traffic control form the core of microservice high‑availability. Most production outages stem from missing or mis‑configured fault‑tolerance. Sentinel, with its lightweight design, visual dashboard, and dynamic rule capabilities, has become the preferred replacement for Hystrix in enterprise Spring Boot ecosystems.

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.

Spring BootFault ToleranceSentinelRate LimitingCircuit Breaking
Java Tech Workshop
Written by

Java Tech Workshop

Focused on Java backend technologies, sharing fundamentals, multithreading, JVM, the Spring ecosystem, microservices, distributed systems, high concurrency, source‑code analysis, and practical experience. Continuously delivers high‑quality original content, interview guides, and learning roadmaps to help Java developers progress from beginner to advanced, enhancing technical skills and core competitiveness.

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.