Mastering Alibaba Sentinel: Flow Control, Circuit Breaking, and Hotspot Rules in Production
This guide walks through Alibaba Sentinel's core protection strategies—flow‑control rules (including QPS and concurrency limits, modes, and effects), circuit‑breaker mechanisms (principles and three strategies), and hotspot parameter limiting—providing detailed configuration steps, code samples, and visual illustrations for real‑world microservice environments.
1. Flow‑Control Rules
Flow control protects system resources by limiting excess requests. Sentinel offers several rule types, each with specific configuration items:
Resource Name : the target of the flow‑control rule.
Origin : the call source; using default means no source distinction.
Threshold Type : either QPS (queries per second) or concurrent thread count.
Single‑Machine Threshold : the limit for QPS or concurrent threads.
Cluster Mode : when enabled, you can choose between per‑instance averaging or a global threshold.
Flow‑Control Mode : Direct , Associated , or Link .
Flow‑Control Effect : Fast Fail , Warm Up, or Queueing .
1.1 Threshold Types
Sentinel supports two threshold types: QPS for request rate and concurrent thread count. Concurrency control prevents thread‑pool exhaustion by rejecting new requests when the active thread count exceeds the configured limit.
@Component
public class OrderBlockExceptionHandler implements BlockExceptionHandler {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, String resourceName, BlockException e) throws Exception {
response.setStatus(429);
response.setContentType("application/json;charset=utf-8");
PrintWriter writer = response.getWriter();
R error = R.error(500, resourceName + " was rate‑limited by Sentinel, reason: " + e.getClass());
String json = objectMapper.writeValueAsString(error);
writer.write(json);
writer.flush();
writer.close();
}
}1.2 Flow‑Control Modes
Direct Mode applies a rule to a single resource without considering call paths. Link Mode targets a specific call chain, e.g., limiting /order/seckill while allowing normal /order/create traffic. Associated Mode lets the traffic of one link affect another, such as restricting reads when writes become too frequent.
Example of adding a new seckill endpoint:
// OrderController.java
@GetMapping("/order/seckill")
@SentinelResource(value = "seckill-order", blockHandler = "seckillFallback")
public Order secKillOrder(@RequestParam("userId") Long userId, @RequestParam("productId") Long productId) {
return orderService.createOrder(userId, productId);
}
public Order seckillFallback(Long userId, Long productId, BlockException e) {
Order order = new Order();
order.setId(productId);
order.setTotalAmount(BigDecimal.ZERO);
order.setUserId(userId);
order.setNickName("Fallback User");
order.setAddress("Blocked by Sentinel: " + e.getClass());
return order;
}1.3 Flow‑Control Effects
Fast Fail : Requests exceeding the threshold are immediately rejected, throwing a BlockException. Warm Up: The allowed QPS gradually ramps up over a configured period. Queueing (rate‑limiter): Excess requests wait in a queue; if they exceed a timeout they are dropped, implementing a leaky‑bucket algorithm.
Warm‑up example configuration (single‑machine threshold 10, warm‑up period 5 s):
spring:
cloud:
sentinel:
web-context-unify: false2. Circuit‑Breaker Rules
Circuit breaking prevents cascading failures in microservice call chains. Sentinel’s circuit‑breaker monitors metrics over a statistical window and opens the circuit when thresholds are exceeded, then enters a half‑open state after a configurable break‑time to probe the downstream service.
2.1 Principle
The circuit breaker stays closed (normal) until the slow‑call ratio, exception ratio, or exception count exceeds configured limits, at which point it opens and redirects calls to a fallback.
2.2 Strategies
Slow‑Call Ratio : Counts calls whose response time exceeds a max RT (e.g., 1000 ms). If the ratio of slow calls over the window exceeds 0.8, the circuit opens.
Exception Ratio : Similar to slow‑call ratio but based on exception occurrences.
Exception Count : Triggers when the absolute number of exceptions in the window exceeds a threshold (e.g., 5 exceptions in 5 s).
Example of configuring a slow‑call ratio rule in the Sentinel console:
Corresponding Java code to simulate a slow call:
// ProductServiceImpl.java
public Product getProductById(Long productId) {
Product product = new Product();
product.setId(productId);
product.setPrice(new BigDecimal("9.9"));
product.setProductName("Apple-" + productId);
product.setNum(100);
try {
Thread.sleep(2000); // simulate slow response
} catch (InterruptedException e) {
e.printStackTrace();
}
return product;
}3. Hotspot (Parameter) Limiting Rules
Hotspot rules limit the access frequency of frequently used parameter values (e.g., user IDs or product IDs). Sentinel tracks the top‑K hot parameters using an LRU cache and applies token‑bucket throttling per parameter.
3.1 Basic Functionality
Example: limit each user to 1 QPS on the seckill interface, but exempt user 10085. Configure a hotspot rule on the userId argument (index 0) with a single‑machine threshold of 1 and a statistical window of 1 s.
3.2 Parameter Exception Items
To exempt a specific user, add an exception entry for userId = 10085 with a very high threshold (e.g., 10 000 000), effectively disabling throttling for that user.
3.3 Additional Hotspot Rules
To block a discontinued product (ID 3544), add a hotspot rule on the productId argument (index 1) with a threshold of 0, preventing any access.
When the rule is active, requests for product 3544 are routed to the fallback logic, returning a blocked response.
With these configurations, Sentinel provides comprehensive protection for microservice resources through flow control, circuit breaking, and hotspot parameter limiting.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
