Go Engineer's Comprehensive Course 017: Learning Notes

Introduction to Rate Limiting, Circuit Breaking, and Degradation (with Sentinel Practical Application)
Based on the key video points from Chapter 3 (3-1 to 3-9) of the courseware, this guide compiles a service protection introduction for beginners, helping them understand "why rate limiting, circuit breaking, and degradation are needed," and how to quickly get started with Sentinel.
Learning Path at a Glance
3-1 Understanding Service Avalanche and the Background of Rate Limiting, Circuit Breaking, and Degradation
3-2 Comparing Sentinel and Hystrix to clarify technology selection
3-3 Sen...

Introduction to Rate Limiting, Circuit Breaking, and Degradation (with Sentinel Practice)

Based on the key video points from Chapter 3 (3-1 ~ 3-9) of the courseware, this guide organizes a set of service protection guidelines for beginners, helping to understand "why rate limiting, circuit breaking, and degradation are needed," and how to quickly get started with Sentinel.

Quick Overview of Learning Path

  • 3-1 Understanding the background of service avalanche, rate limiting, circuit breaking, and degradation
  • 3-2 Sentinel vs. Hystrix comparison, clarifying technology selection
  • 3-3 Sentinel QPS Rate Limiting Basics
  • 3-4 Predictive Rate Limiting and Cold Start
  • 3-5 Throttling Configuration Demo
  • 3-6 Sentinel Circuit Breaking and Degradation Strategies
  • 3-7 Circuit Breaking Strategy – Based on Error Ratio
  • 3-8 Degradation Strategy – Based on Response Time
  • 3-9 Gin + Sentinel Practical Rate Limiting

Causes of Service Avalanche

When sudden traffic exceeds the system's capacity (e.g., system capacity is 1k QPS but suddenly 2k QPS floods in), it can lead to slower responses, soaring error rates, and subsequently drag down more dependencies, forming an "avalanche." Common causes:

  • Sudden Traffic Spikes: Caused by major promotions, trending news, web crawlers, etc., leading to a surge in access volume.
  • Dependency Failures: Downstream services experience delays or crashes, leading to accumulated calls.
  • Resource Exhaustion: Threads/connections/CPU are fully occupied, causing more requests to queue up.

The three-piece strategy for handling: Rate Limiting to block the flood, Circuit Breaking to pull the circuit breaker, and Degradation to provide a fallback experience.

graph LR
    A[突发流量] --> B(限流:削峰填谷)
    B --> C{依赖正常?}
    C -->|是| D[服务稳定运行]
    C -->|否| E(熔断:暂时切断调用)
    E --> F(降级:返回备用方案)
    F --> D

Rate Limiting: Adding a 'Sluice Gate' to the Entrance

Rate Limiting controls the number of requests or concurrency within a unit of time, allowing the system to operate within a controllable range. Common strategies:

Strategy Scenario Advantages Potential Side Effects
Fixed Window QPS Simple rate limiting needed for interfaces Simple to implement Boundary instantaneous spikes
Sliding Window API Gateway, unified egress Smoother control Slightly more complex calculation
Leak Bucket Replay requests, peak shaving and valley filling Stable output Burst traffic queued
Token Bucket Allows some spikes Flexible metrics (QPS/Concurrency) Requires monitoring bucket status

Rate limiting messages should be friendly: "Currently, there are many visitors, please try again later or pay attention to notifications."

graph TD
    subgraph 限流闸门
        Tokens[令牌桶] -->|取令牌| Request[请求放行]
        Request --> Service[核心服务]
    end
    Tokens -.超限.-> Fallback[返回 429 或排队提示]

Circuit Breaking: Making the System 'Rejuvenated'

"Circuit breaking" is similar to an electrical circuit breaker – when abnormal indicators such as error rate or response time are detected, calls are temporarily cut off to prevent fault propagation. Because the system can catch its breath and recover after the 'breaker is pulled,' it's jokingly referred to in class as making the system "rejuvenated."

Sentinel supports three types of circuit breaking rules:

  • Slow Call Ratio: Triggered when the proportion of requests exceeding the configured response time threshold is too high.
  • Exception Ratio: Circuit breaking occurs when the proportion of exceptions within the statistical window exceeds the limit.
  • Exception Count: Circuit breaking occurs when the total number of exceptions within a unit of time reaches the threshold.

Circuit breaking typically goes through three stages:
Open(全阻断) -> Half-Open(少量探测) -> Closed(恢复正常)

Degradation: Providing an Alternative Experience

When the core process is under too much pressure or a dependency is circuit-broken, degradation strategies provide users with "simplified but usable" results:

  • Return cached or fallback data (e.g., display yesterday's inventory).
  • Prompt for later processing, asynchronous callback (order queuing, ticket handling).
  • Temporarily disable high-cost features (e.g., turn off recommendation lists, only retain basic search).

The key to degradation is preparation in advance: copy, fallback interfaces, and frontend placeholders must all be ready.

Sentinel Quick Overview

Sentinel is an open-source high-availability protection framework from Alibaba, with core values:

  • Unified console for managing rules such as rate limiting, circuit breaking, degradation, and system protection.
  • Supports Java and Go, providing rich ecosystem adaptations (Dubbo, Spring Cloud, Gin, etc.).
  • Possesses capabilities such as real-time monitoring, link aggregation, and rule pushing.

Sentinel Architecture Diagram:

graph LR
    subgraph 控制台
        Dashboard[Dashboard 控制台]
    end
    Dashboard -- 推送规则 --> DataSource[数据源/配置中心]
    DataSource -- 动态规则 --> Sentinel[Sentinel 客户端]
    Sentinel -- 上报指标 --> Dashboard
    Sentinel --> App[业务应用]

Getting Started Quickly with Go Language (Taking Gin Project as an Example)

  1. Install Dependencies

bash
go get github.com/alibaba/sentinel-golang@latest
go get github.com/alibaba/sentinel-golang/pkg/adapters/gin

  1. Initialize Sentinel

```go
package main

import (
"log"
"github.com/alibaba/sentinel-golang/api"
"github.com/alibaba/sentinel-golang/core/flow"
)

func initSentinel() {
if err := api.InitDefault(); err != nil {
log.Fatalf("init sentinel: %v", err)
}
_, err := flow.LoadRules([]*flow.Rule{
{
Resource: "GET:/api/orders",
MetricType: flow.QPS,
Count: 200,
ControlBehavior: flow.WarmUp,
WarmUpPeriodSec: 10,
WarmUpColdFactor: 3,
},
})
if err != nil {
log.Fatalf("load flow rules: %v", err)
}
}
<code>

<ol>
<li><strong>Integrate Gin Middleware</strong></li>
</ol>

</code>go
r := gin.Default()
r.Use(sgin.SentinelMiddleware())

r.GET("/api/orders", func(c *gin.Context) {
if entry, blockErr := api.Entry("GET:/api/orders"); blockErr != nil {
c.JSON(429, gin.H{"code": 429, "msg": "拥挤,请稍后重试"})
return
} else {
defer entry.Exit()
}
c.JSON(200, gin.H{"orders": []string{"#1201", "#1202"}})
})
```

  1. Local Debugging Suggestions
  2. Use ab/wrk for stress testing to verify if rate limiting takes effect.
  3. Observe real-time QPS and Block metrics in logs and Dashboard.

Key Points for Java Environment Integration

<!-- Maven -->
<dependency>
  <groupId>com.alibaba.csp</groupId>
  <artifactId>sentinel-core</artifactId>
  <version>1.8.6</version>
</dependency>
@Configuration
public class SentinelConfig {
    @PostConstruct
    public void init() throws Exception {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule("product_list");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(1000);
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
        rule.setMaxQueueingTimeMs(500);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}

Combined with Spring Cloud Alibaba, degradation callback methods can be annotated with @SentinelResource.

Dashboard Startup Guide

  1. Download the console:

bash
wget https://github.com/alibaba/Sentinel/releases/download/1.8.6/sentinel-dashboard-1.8.6.jar

  1. Start:

bash
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 \
-Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.6.jar

  1. Client parameters (Java example):

bash
-Dcsp.sentinel.dashboard.server=localhost:8080 \
-Dcsp.sentinel.api.port=8719 \
-Dproject.name=demo-service

  1. Log in to the console (default username and password are both sentinel), create flow control/circuit breaking/system protection rules in the interface, and push them in real-time.

Formulating Your Own Protection 'Battle Plan'

  • Observation Metrics: QPS, average response time, error rate, downstream dependency health.
  • Threshold Setting: Based on capacity assessment and stress test data; set differentiated rules for different interfaces.
  • Circuit Breaking Recovery: Configure Half-Open probing logic to ensure the service can automatically close the circuit after recovery.
  • Degradation Copy: Confirm fallback pages and prompts with product/frontend teams in advance.
  • Post-mortem Review: After each rate limiting / circuit breaking trigger, record the cause, adjust thresholds, or scale up.
sequenceDiagram
    participant User
    participant Gateway as API 网关
    participant Service as 核心服务
    participant Fallback as 降级/缓存

    User-->>Gateway: 请求下单
    Gateway-->>Service: 令牌校验
    alt QPS 超限
        Gateway-->>User: 429 拥堵提示
    else 调用异常
        Service-->>Gateway: 熔断触发
        Gateway-->>Fallback: 查询兜底方案
        Fallback-->>User: 排队中,请稍后
    end

Quick Review Checklist

  • Rate limiting controls inbound traffic within the system's capacity, prioritizing the protection of core capabilities.
  • Circuit breaking actively cuts off calls when dependencies are abnormal, allowing the system to 'recover' quickly.
  • Degradation is a fallback solution, allowing users to perceive the service as 'still alive' even during failures.
  • Sentinel covers rate limiting, circuit breaking, degradation, and system protection, with visual configuration and real-time monitoring via the console.
  • Preparing thresholds, copy, monitoring, and drills in advance is essential to 'rejuvenate' and cope before a real avalanche strikes.

主题测试文章,只做测试使用。发布者:Walker,转转请注明出处:https://walker-learn.xyz/archives/4788

(0)
Walker的头像Walker
上一篇 Mar 10, 2026 00:00
下一篇 Mar 8, 2026 15:40

Related Posts

  • In-depth Understanding of ES6 002 [Study Notes]

    Strings and Regular Expressions. Strings and Regular Expressions. JavaScript strings have always been built based on 16-bit character encoding (UTF-16). Each 16-bit sequence is a code unit, representing a character. String properties and methods like `length` and `charAt()` are all constructed based on these code units. The goal of Unicode is to provide a globally unique identifier for every character in the world. If we limit the character length to 16 bits, the number of code points will not...

    Personal Mar 8, 2025
    1.9K00
  • In-depth Understanding of ES6 012 [Study Notes]

    Proxy and Reflection API
    A Proxy is a wrapper that can intercept and modify underlying JavaScript engine operations. It exposes internal operational objects, enabling developers to create custom built-in objects.

    Proxy Traps
    Overridden Features | Default Behavior
    get Reads a property value | Reflect.get()
    set Writes a property value | Reflect.set()
    has `in` operator | Reflect...

    Personal Mar 8, 2025
    1.2K00
  • In-depth Understanding of ES6 011 [Learning Notes]

    Promises and Asynchronous Programming

    Because the execution engine is single-threaded, it needs to track the code that is about to run. This code is placed in a task queue. Whenever a piece of code is ready to execute, it is added to the task queue, and whenever a piece of code in the engine finishes execution, the event loop executes the next task in the queue. A Promise acts as a placeholder for the result of an asynchronous operation. It doesn't subscribe to an event or pass a callback function to the target function. Instead, it allows the function to return a Promise, like this...

    Personal Mar 8, 2025
    1.2K00
  • Deep Dive into ES6 010 [Study Notes]

    Improved array functionality. The peculiar behavior of `new Array()`: when a single numeric value is passed to the constructor, the array's `length` property is set to that value; if multiple values are passed, regardless of whether they are numeric or not, they all become elements of the array. This behavior is confusing, as it's not always possible to pay attention to the type of data passed in, thus posing a certain risk. `Array.of()`, regardless of how many arguments are passed, has no special case for a single numeric value (one argument and numeric type); it always returns an array containing all arguments...

    Personal Mar 8, 2025
    1.3K00
  • Go Engineer System Course 006 [Study Notes]

    Project Structure Description: The user-web module is the user service Web layer module within the joyshop_api project, responsible for handling user-related HTTP requests, parameter validation, business routing, and calling backend interfaces. Below is the directory structure description: user-web/ ├── api/ # Controller layer, defines business interface processing logic ├── config/ # Configuration module, contains system configuration structs and reading logic ...

    Personal Nov 25, 2025
    28700
EN
简体中文 繁體中文 English