Backend Development 17 min read

Mastering Sentinel: Traffic Control, Circuit Breaking, and System Protection for Microservices

This article introduces Sentinel, a Java‑based library that safeguards microservice stability through traffic shaping, circuit breaking, and system‑level protection, compares it with Hystrix and resilience4j, explains core concepts, usage patterns, annotation support, and dashboard monitoring, and provides practical code examples.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Mastering Sentinel: Traffic Control, Circuit Breaking, and System Protection for Microservices

Sentinel Overview

With the rise of microservices, service stability becomes increasingly critical. Sentinel addresses this by protecting services from traffic spikes, circuit breaking, and system overload through multiple dimensions of flow control, degradation, and load protection.

Key Features

Rich application scenarios : Handles core Alibaba traffic such as flash sales, peak shaving, cluster flow control, and real‑time circuit breaking.

Real‑time monitoring : Provides per‑machine second‑level metrics and aggregated cluster views.

Broad open‑source ecosystem : Offers out‑of‑the‑box integrations with Spring Cloud, Dubbo, gRPC, etc.

Complete SPI extension points : Allows custom rule management and dynamic data source adaptation.

Sentinel features
Sentinel features
Sentinel ecosystem
Sentinel ecosystem

Sentinel, Hystrix, resilience4j Comparison

Feature                | Sentinel                     | Hystrix                         | resilience4j
----------------------|-----------------------------|--------------------------------|-----------------
Isolation strategy    | Semaphore (concurrency)     | Thread‑pool / Semaphore         | Semaphore
Circuit‑break strategy| Slow‑call ratio, exception ratio, count | Exception ratio | Exception ratio, response time
Real‑time stats      | LeapArray (sliding window) | RxJava sliding window           | Ring Bit Buffer
Dynamic rule config  | Multiple data sources       | Multiple data sources           | Limited support
Extensibility         | Multiple extension points    | Plugin form                    | Interface form
Annotation support   | Supported                    | Supported                      | Supported
Rate limiting         | QPS‑based, supports call‑graph | Limited support                | Simple Rate Limiter
Traffic shaping      | Warm‑up & smooth queueing    | Not supported                   | Simple Rate Limiter
System adaptive protection | Supported               | Not supported                  | Not supported
Multi‑language support| Java/Go/C++                 | Java                           | Java
Service‑mesh support | Envoy/Istio                  | Not supported                  | Not supported
Dashboard             | Full‑featured console        | Simple view                     | No console

Sentinel Terminology

Resource

A resource is the fundamental concept in Sentinel. It can be any element in a Java application—services provided by the application, services called from other applications, or even a code block. Defining a resource via the Sentinel API enables protection.

Rule

Rules are defined around the real‑time state of resources and may include flow‑control rules, degradation rules, and system‑protection rules. All rules can be adjusted dynamically.

Traffic Control

What is traffic control

Traffic control adjusts the rate of incoming requests to match the system’s processing capacity, preventing overload. Sentinel reshapes random request bursts into manageable patterns.

Traffic shaping diagram
Traffic shaping diagram

Design ideas

Resource call relationships (call graph).

Runtime metrics such as QPS, thread pool size, system load.

Control effects like direct limiting, warm‑up, queuing.

Sentinel lets you combine these dimensions flexibly.

Circuit Breaking

What is circuit breaking

Beyond flow control, Sentinel also isolates unstable resources in a call chain to prevent cascading failures. When a resource shows high latency or error ratio, Sentinel limits its calls, causing fast failures.

Design ideas

Sentinel differs from Hystrix’s thread‑pool isolation. It limits the number of concurrent threads for a resource, avoiding thread‑switch overhead and pre‑allocation. When concurrency exceeds a threshold, new requests are rejected until threads finish.

Sentinel also supports response‑time based degradation: if a resource’s latency exceeds a threshold, all calls are blocked for a configured window.

System Adaptive Protection

Sentinel provides system‑level adaptive protection to prevent avalanche effects. When system load is high, it balances incoming traffic with current capacity, ensuring the cluster remains stable.

Sentinel Principles

Provides adapters or explicit APIs for mainstream frameworks to define protected resources and collect real‑time statistics.

Applies configured rules to control traffic based on real‑time metrics, with open interfaces for rule management.

Offers a real‑time monitoring console for quick status overview.

Sentinel Usage

Basic Usage

Add the core dependency to

pom.xml

:

<code>&lt;dependency&gt;
  &lt;groupId&gt;com.alibaba.csp&lt;/groupId&gt;
  &lt;artifactId&gt;sentinel-core&lt;/artifactId&gt;
  &lt;version&gt;1.8.1&lt;/version&gt;
&lt;/dependency&gt;</code>

Wrap the code you want to protect with Sentinel API calls:

<code>while (true) {
  Entry entry = null;
  try {
    entry = SphU.entry("HelloWorld");
    // business logic start
    System.out.println("hello world");
    TimeUnit.MILLISECONDS.sleep(10);
    // business logic end
  } catch (BlockException e1) {
    // flow‑control handling
    System.out.println("block!");
  } catch (InterruptedException e) {
    e.printStackTrace();
  } finally {
    if (entry != null) {
      entry.exit();
    }
  }
}</code>

Define a flow rule, e.g., limit

HelloWorld

to 20 QPS:

<code>private static void initFlowRules() {
  List<FlowRule> rules = new ArrayList<>();
  FlowRule rule = new FlowRule();
  rule.setResource("HelloWorld");
  rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
  // Set limit QPS to 20.
  rule.setCount(20);
  rules.add(rule);
  FlowRuleManager.loadRules(rules);
}</code>

Run the demo and observe logs such as:

<code>|--timestamp-|------date time----| -resource- |p |block|s |e|rt
1619954886000|2021-05-02 19:28:06|HelloWorld|20|1|20|0|12|0|0|0
1619954887000|2021-05-02 19:28:07|HelloWorld|20|3197|20|0|11|0|0|0</code>

Here

p

= passed requests,

block

= blocked,

s

= successful,

e

= custom exceptions,

rt

= average response time.

Annotation Mode

Include the annotation dependency:

<code>&lt;dependency&gt;
    &lt;groupId&gt;com.alibaba.csp&lt;/groupId&gt;
    &lt;artifactId&gt;sentinel-annotation-aspectj&lt;/artifactId&gt;
    &lt;version&gt;x.y.z&lt;/version&gt;
&lt;/dependency&gt;</code>

Example usage:

<code>// Method with @SentinelResource
@SentinelResource(value = "createOrder", blockHandler = "blockHandler", blockHandlerClass = {ExceptionUtils.class})
@GetMapping("/createOrder")
public OrderDto createOrder(OrderDto dto) {
  return new OrderDto();
}

// ExceptionUtils
public class ExceptionUtils {
  public static OrderDto blockHandler(OrderDto dto, BlockException ex) {
    ex.printStackTrace();
    return null;
  }
}</code>

@SentinelResource Annotation

The annotation defines a resource and optionally specifies block handlers, fallbacks, default fallbacks, and exceptions to ignore. Key attributes include:

value: resource name (required).

entryType: entry type (default OUT).

blockHandler / blockHandlerClass: method to handle

BlockException

.

fallback / fallbackClass: method for business exceptions.

defaultFallback: global fallback method (since 1.6.0).

exceptionsToIgnore: exceptions excluded from fallback handling.

Note: Annotation‑based entry does not support private methods.

Sentinel Dashboard

Download the dashboard from the release page.

Start it with:

<code>java -Dserver.port=8089 
     -Dcsp.sentinel.dashboard.server=127.0.0.1:8089 
     -Dproject.name=sentinel-dashboard 
     -jar sentinel-dashboard-1.8.1.jar</code>

Login with default credentials (username: sentinel, password: sentinel).

Configure services via the right‑hand menu.

Sentinel dashboard
Sentinel dashboard

References

https://github.com/alibaba/Sentinel/wiki/介绍

https://github.com/Netflix/Hystrix/wiki/How-it-Works#benefits-of-thread-pools

Javamonitoringmicroservicestraffic controlSpring BootSentinelcircuit breaking
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

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.