Sentinel Internals: Sliding Window, Leaky Bucket & Circuit Breaker State Machine
This article deep-dives into Sentinel's core mechanisms including sliding window statistics, three rate-limiting algorithms, circuit breaker state machine, Slot chain execution flow, hotspot parameter limiting, rule persistence modes, Gateway/Feign integration, threshold calculation, and common pitfalls with troubleshooting steps.
Introduction
The gateway blocks the entrance; next we must prevent downstream from being crushed. Rate limiting and circuit breaking are the only stability measures that take effect instantly during a failure — no scaling, no restart, no downstream fix required, just a single judgment: can we let this request through? Sentinel splits this into three layers: statistics (sliding window), judgment (flow control and circuit breaker strategies), and execution (Slot chain on the responsibility chain). This article traces from how a single call is counted to when the circuit breaker state machine returns to half-open.
Three Real Incidents
Incident 1: Rate limit threshold 500 QPS, database still crushed. Rule configured on a batch import interface; each request internally loops deducting 10,000 inventory items. Sentinel sees 500 calls/sec, but the database suffers 5 million updates/sec — the statistical dimension and real pressure dimension differ.
Incident 2: Circuit breaker opened, users still see 500. @SentinelResource only had value, no fallback or blockHandler. The DegradeException thrown after circuit breaking propagated to the global exception handler, returning 500 — circuit breaking took effect, but degradation was not implemented , rendering the configuration useless.
Incident 3: Restart once, all rules lost. All rules were created in the console and existed only in memory. After deployment, traffic entered unprotected; only later discovered rules were not persisted. The console is a debugging tool, not a configuration center.
Three incidents map to three requirements: statistical dimension must match (incident 1), failures must have an exit (incident 2), rules must be persistable (incident 3). None are solved by "adding an annotation"; they belong to the level of "why this protection mechanism is reliable".
Technical Analysis: Four Terms Are Not the Same
2.1 Rate Limiting, Circuit Breaking, Degradation, Isolation
Rate Limiting: Actively rejects excess traffic to protect self. Basis: inbound rate . Rejected requests never enter business logic; cost is minimal.
Circuit Breaking: Downstream is unhealthy, stop calling it. Basis: historical call results (slow call ratio, exception ratio, exception count). State machine opens/closes automatically.
Degradation: Skip real call, return fallback data directly. It is the action after circuit breaking, not an independent mechanism — circuit breaking handles "stop calling", degradation handles "what to return".
Isolation: Separate calls to different dependencies so one slow dependency doesn't drag down everything. Hystrix uses thread pool isolation; Sentinel uses concurrent thread count limiting for lightweight isolation.
One-sentence distinction: Rate limiting watches "how many come in", circuit breaking watches "how results look going out", degradation decides "what to give when not going out". Their common prerequisite is fast failure — any protection that needs 30 seconds to reject is not protection.
2.2 Sentinel vs Hystrix vs Resilience4j Trade-offs
Hystrix: Thread pool isolation, thorough but high thread-switching overhead; one pool per dependency, dozens of dependencies mean hundreds of threads; no longer maintained .
Resilience4j: Functional, lightweight, only does circuit breaking, rate limiting, retry; rules via code or config files; no console or dynamic push; suitable as a library.
Sentinel: Based on sliding window statistics; provides console, dynamic rule sources, hotspot parameter limiting, system adaptive protection, chain flow control; best integration with Spring Cloud Alibaba. Cost: many concepts, complex Slot chain, rules lost if not persisted.
Selection mnemonic: Want ecosystem and console → Sentinel; want extreme lightweight → Resilience4j; Hystrix only maintain, don't create new . They can coexist — Sentinel handles ingress flow control, Resilience4j handles per-call retry and timeout.
2.3 Five Core Concepts
Resource: Protected logic unit — an interface, code block, or remote call. Name is the rule binding key; granularity determines protection precision .
Rule: Five types (flow, degrade, hotspot, system, authority); runtime mutable, effective immediately on change.
Slot Chain: Responsibility chain; nine Slots execute sequentially, responsible for building call tree, statistics, validation, flow control, circuit breaking.
Context: Call chain context spanning the entire ingress chain, used to distinguish "which entry point the request came from".
Node: Statistics data structure; each resource has a call tree, each node holds a sliding window.
2.4 A Boundary That Must Be Clarified: Default Is Single-Machine Rate Limiting
Sentinel's QPS threshold is counted per instance independently . 10 instances, each threshold 100, cluster theoretically passes 1000 — but traffic distribution is never uniform: registry push latency, long-connection stickiness, one machine slightly faster — all cause individual instances to hit threshold early, resulting in overall only 700 throughput but already rejecting .
For global precision, use cluster flow control : introduce Token Server to issue tokens uniformly. Embedded mode picks one instance as server (saves deployment but leader election complex); Remote mode deploys separately (stable but adds one hop). Cost: each judgment adds an RPC, and must handle server unavailability — usually configured fail-open, falling back to single-machine limiting, preferring under-limiting over total rejection.
When cluster flow control is truly needed: few instances (3–5), extremely uneven traffic, threshold extremely tight (e.g., downstream can only handle 200 QPS). Otherwise, single-machine limiting divided by instance count is sufficient; the extra error is far smaller than the operational cost of Token Server.
Core Flow: Nine Slots in One Relay
When SphU.entry("createOrder") is called, Sentinel constructs a Slot chain for this call, executing in fixed order. Order is not arbitrary: build nodes first, then statistics, only after statistics can judgment happen, only after judgment can pass .
NodeSelectorSlot builds call tree (DefaultNode)
ClusterBuilderSlot builds global ClusterNode
LogSlot logs intercepted requests
StatisticSlot statistics RT / QPS / exceptions
AuthoritySlot black/white list validation
SystemSlot system adaptive Load/CPU/RT
ParamFlowSlot hotspot parameter flow control
FlowSlot flow control rule judgment
DegradeSlot circuit breaker rule judgmentTwo counter-intuitive designs: StatisticSlot is in the middle, not at the end , because it must let downstream Slots judge first, then decide whether to record "pass" or "blocked" based on result; SystemSlot before FlowSlot , meaning system-level protection takes priority over single-resource flow control — if the whole machine is about to crash, precise per-interface limiting is meaningless.
3.1 Complete Lifecycle of a Call
SphU.entry()
-> CtEntry constructed, bound to Context
-> SlotChain.entry() executes nine Slots sequentially
StatisticSlot first fireEntry passes down
Later Slots throw BlockException then rollback statistics
-> Business method executes
-> entry.exit() records RT, cleans thread counters
Exception: Tracer.trace() records business exception3.2 Three Flow Control Effects, Three Algorithms
Fast Fail (DefaultController): Exceeds threshold → throw FlowException. Simplest, most common, suitable for most interfaces.
Uniform Queueing (RateLimiterController): Leaky bucket idea; requests pass at fixed intervals, excess queued, rejected only after max wait time. Suitable for peak shaving; cost: RT stretched .
Warm-up Cold Start (WarmUpController): Threshold ramps from 1/3 to target, preventing cold system from being crushed by sudden traffic. Suitable for cache not warmed, connection pools not established.
3.3 Three Flow Control Modes
Direct: Resource itself hits threshold → limit self.
Associate: Resource A hits threshold → limit B. Typical scenario: "payment interface busy → limit order interface", sacrifice non-core to protect core.
Chain: Only count traffic from specified entry point. Same resource called by multiple entry points → can limit only one chain.
3.4 System Adaptive Protection: Last Line of Defense
Previous rules are "per resource", requiring per-interface threshold config. System rule is "per machine" — regardless of interface, if this machine can't hold, uniformly throttle. Any of four metrics exceeding threshold triggers:
LOAD load1 exceeds threshold (Linux/Mac only)
RT average RT of all entries exceeds threshold
THREAD concurrent thread count exceeds threshold
CPU CPU usage exceeds 0.8 thresholdExecution is critical: not a one-cut reject, but gradual tightening by step . Suppose current allowed concurrency 100; trigger → drop to 90, then 80, each step observes a window — traffic "smoothly converges" rather than "instantly zero". Purpose: buy system recovery time , not immediately reject all.
Two pitfalls: load1 in container reads host value — a 64-core host running twenty containers naturally has high load; not checking cgroup causes false triggers; CPU core count must use container limit , otherwise threshold calculated from physical cores never reached. These "container-unaware" issues are almost guaranteed in K8s.
3.5 Hotspot Parameter Limiting: Special Treatment for a Single Item
During big promotions, the problem is rarely overall high traffic, but a hot SKU being hammered . Overall QPS only 800, far below threshold, but 700 hits same product → cache penetration, inventory row lock queue, still drags database down. Normal flow control sees total resource quantity, cannot see "parameter distribution"; hotspot parameter rules are designed for this.
ParamFlowRule r
= new ParamFlowRule("queryItem")
.setParamIdx(0) // 0th parameter
.setCount(50) // 50 per second
.setDurationInSec(1);
// Special threshold for specific parameter value (e.g., VIP pass)
ParamFlowItem vip = new ParamFlowItem()
.setObject("10086")
.setClassType("java.lang.String")
.setCount(500);
r.setParamFlowItemList(
Collections.singletonList(vip));Three limitations to know: paramIdx starts at 0 , off-by-one means rule never matches; only supports primitive types and String , passing objects requires custom parameter parsing; maintains independent sliding window per parameter value , huge cardinality (e.g., UUID as parameter) blows memory — must limit value space.
Core Source Code: From Counting to Decision
4.1 StatisticSlot.entry: Why Statistics in the Middle
public void entry(Context ctx,
ResourceWrapper r, Object[] args,
int count, boolean prioritized,
Throwable t) throws Throwable {
try {
// First pass to downstream nine Slots for judgment
fireEntry(ctx, r, args, count,
prioritized, t);
// All passed, then record one success
recordPass(ctx, count);
} catch (BlockException e) {
recordBlock(ctx, count);
throw e;
} catch (Throwable t2) {
recordError(ctx, count);
throw t2;
} finally {
exit(ctx, r, count, args);
}
}This try-catch is the most important code in this article. It shows statistics happen after judgment : if downstream FlowSlot rejects, this call records blockCount, not passCount; if business throws exception, records errorCount. Three counts separated, so "pass rate" and "exception ratio" are meaningful — counting rate-limited requests into QPS would keep window forever full .
4.2 LeapArray: Sliding Window Is a Circular Array
All statistics finally land on a structure called LeapArray . Not a linked list or queue, but fixed-length circular array + timestamp validation : total window 1000ms, split into 2 buckets, each 500ms. Write: compute current bucket by current time, clear old data. Read: traverse all buckets, sum only non-expired ones.
intervalInMs = 1000 sampleCount = 2
Each bucket window length 500ms
+--------+--------+
| win 0 | win 1 |
+--------+--------+
Write: locate current bucket by now, clear old data
Read: traverse all buckets, skip expired
Expiration: now - windowStart >= 1000Why sliding window, not fixed window resetting every second? Because fixed window has boundary problem : 500 requests at 999ms, 500 at 1001ms → actual 1000 in 1 second, but two windows each count 500, rate limiting ineffective. Sliding window slices time into rolling buckets, worst error only one bucket (500ms) — a trade-off between precision and overhead.
// Fixed window boundary double burst
999ms |#### 500 times####|
1001ms |#### 500 times####|
Actual 1000 in 1 second, both windows not exceeded4.3 RateLimiterController: Uniform Queueing Is Leaky Bucket
public boolean canPass(Node node,
int acquireCount,
boolean prioritized) {
long now = TimeUtil.currentTimeMillis();
// Time slot needed this request = 1000ms / QPS * request count
long cost = Math.round(
acquireCount * 1000.0 / count);
long expected
= latestPassedTime.get() + cost;
if (expected < now) {
// Time since last pass exceeds one slot, pass immediately
expected = now;
} else if (expected - now
> maxQueueingTimeMs) {
// Queueing would exceed max wait, reject
return false;
}
// CAS compete for time slice, conflict → reject this request
return latestPassedTime.compareAndSet(
latestPassedTime.get(), expected);
}Three key points: No queue — so-called queueing is just "compute a future time point to pass", using CAS to compete for time slice; No thread blocking — fail immediately if cannot acquire; maxQueueingTimeMs determines RT ceiling — set to 500ms, interface slows at most 500ms; set to 5 seconds → disaster.
4.4 CircuitBreakerStateMachine: Three States and Two Counters
Circuit breaking is not "N consecutive failures then open" that crude. Sentinel uses state machine + ratio within sliding window : window request count reaches minimum sample count, and slow call ratio or exception ratio exceeds threshold, then switch state.
CLOSED --(ratio exceeds threshold)--> OPEN
OPEN --(circuit breaker duration elapsed)--> HALF_OPEN
HALF_OPEN --(probe succeeds)--> CLOSED
HALF_OPEN --(probe fails)--> OPENCLOSED: Normal pass, simultaneously statistics slow calls and exceptions.
OPEN: Directly throw DegradeException, no longer call downstream, this period gives downstream recovery chance.
HALF_OPEN: After circuit breaker duration, let one request in to probe — success → close and clear statistics, failure → reopen.
Two easily overlooked parameters: minRequestAmount (minimum request count, default 5) prevents misjudgment from one or two failures under low traffic; statIntervalMs (statistics window, default 1000ms) determines judgment time granularity. Slow call ratio also needs maxRt (slow call threshold RT), calls exceeding it count as "slow".
DegradeRule rule
= new DegradeRule("queryOrder");
// Slow call ratio mode
rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
rule.setCount(200); // Slow call threshold 200ms
rule.setSlowRatioThreshold(0.5); // Ratio threshold
rule.setMinRequestAmount(10); // Minimum sample
rule.setTimeWindow(10); // Circuit break 10 secondsNote: setCount in RT mode is RT threshold (ms), in exception ratio mode is ratio (0~1), in exception count mode is count . Same setter, three semantics; misconfiguration won't error, just silently ineffective — one of Sentinel's easiest pitfalls.
Annotation Usage: blockHandler vs fallback
@SentinelResourcetwo fallback methods have completely different responsibilities; confusing them makes circuit breaking appear "not effective".
@SentinelResource(
value = "createOrder",
blockHandler = "onBlocked",
fallback = "onFallback")
public Order create(Long skuId) { ... }
// Entered on rate limit / circuit break (add BlockException)
public Order onBlocked(Long skuId,
BlockException e) {
return Order.fail("Too many requests, try later");
}
// Entered on business exception (parameter must add Throwable)
public Order onFallback(Long skuId,
Throwable t) {
return Order.fail("Service degraded");
}Two hard rules: blockHandler handles BlockException (rate limit, circuit break, system protection, auth reject), fallback handles business exceptions ; both method signatures, besides one extra exception parameter, must exactly match original method (return type, parameter types, static or not). Signature mismatch → Sentinel won't error, just silently not call — manifests as "configured fallback but exception still propagates".
About fallback boundary: fallback only catches business exceptions, does not catch Error or BlockException . If you want circuit break and business exceptions to share same exit, use exceptionsToIgnore to exclude specific exceptions, or simply write both blockHandler and fallback. Also, don't call the same downstream again inside fallback, otherwise you're pushing failure back again.
Rule Persistence: Three Modes
Rules live in memory; process restart loses them. Official three paths, only the third is complete for production.
Original Mode: Console changes, client memory effective. Debug only, restart loses.
Pull Mode: Client periodically pulls local file or remote HTTP; simple but not real-time , and multiple instances pull independently → rules may be inconsistent.
Push Mode: Rules in Nacos / Apollo / ZK, client registers listener, changes pushed real-time. Production standard .
spring:
cloud:
sentinel:
datasource:
flow:
nacos:
server-addr: 127.0.0.1:8848
data-id: order-flow-rules
group-id: SENTINEL_GROUP
rule-type: flow
degrade:
nacos:
server-addr: 127.0.0.1:8848
data-id: order-degrade-rules
group-id: SENTINEL_GROUP
rule-type: degradeTwo practice tips: Each rule type separate data-id , mixing causes changing one to overwrite all; Console set to "push to Nacos" not "client only" , otherwise console changes disappear after restart, wasted effort.
Integration with Gateway and OpenFeign
Sentinel integrates at two positions: ingress (Gateway layer rate limiting) and egress (Feign call circuit breaking). Their resource dimensions differ, cannot be mixed.
Gateway side: Add sentinel-spring-cloud-gateway-adapter, resource name is route id , rate limiting completes at gateway, request never hits downstream. Custom GatewayFilter uses SentinelGatewayFilter + SentinelGatewayBlockExceptionHandler.
Feign side: Enable feign.sentinel.enabled=true, each Feign method automatically becomes a resource, resource name is interface fully qualified name plus method signature , fallback uses Feign's fallbackFactory. Note: enabling this replaces Feign's original Hystrix support; don't enable both simultaneously.
feign:
sentinel:
enabled: true
client:
config:
default:
connect-timeout: 1000
read-timeout: 2000One ordering issue: Gateway rate limit threshold should be greater than service's own rate limit threshold. Gateway 1000 QPS, service 500 QPS → requests above 500 already entered internal network, consuming bandwidth and connections — correct approach: service threshold slightly higher than gateway threshold divided by instance count, so rejection happens as far out as possible.
7.1 How to Derive Thresholds, Not Guess
Thresholds are not "looks about right", but calculated upstream from downstream capacity. Order always:
First stress-test downstream bottleneck capacity, then divide by instance count, finally apply safety factor .
① Stress-test downstream limit
DB single table write 3000 QPS when RT starts spiking
② Single-machine threshold = limit / instances × safety factor
3000 / 10 × 0.7 = 210
③ Gateway threshold = service total capacity × 0.9
210 × 10 × 0.9 = 1890
④ Verify: stress to 1.2× threshold
Observe if stable rejection, downstream RT stableSafety factor 0.7 is empirical, meaning "reserve 30% headroom for bursts and statistical error". Verification step cannot be skipped — truly effective rate limiting should show downstream RT remains stable when stressed to 1.2× threshold ; if downstream starts jittering, threshold set too high, go back to step ① capacity number.
One more detail: Threshold unit must align with statistical dimension . Batch interface processes 100 items per call → cannot set threshold by "calls per second", should use hotspot parameter to limit by item count, or split batch and single into two resources with separate limits — exactly the root cause of Incident 1.
7.2 Conflict Between Circuit Breaking and Retry
Classic scenario where two protection mechanisms fight: circuit breaker just opened, should "call downstream less", but upstream retry policy still runs — one failure amplified into three requests , both slowing circuit breaker recovery and pressuring the just-recovering downstream again. Worse, retry often treats DegradeException as "retryable transient fault".
// Wrong: indiscriminate retry, amplifies after circuit break opens
retryTemplate.execute(ctx -> remote.call());
// Correct: explicitly exclude rate limit and circuit break exceptions
new RetryTemplateBuilder()
.maxAttempts(3)
.notRetryOn(DegradeException.class)
.notRetryOn(FlowException.class)
.build();Principle is clear: BlockException family must never be retried — it means "system actively rejects", retry only makes rejection more determined. Only network jitter, connection timeout — potentially self-healing exceptions deserve retry, and must have backoff and total budget, not letting retry itself become a new pressure source.
Eight High-Frequency Pitfalls
Pitfall 1: Thinking QPS threshold equals business pressure. Batch interfaces, loop calls, internal retries amplify real pressure; threshold should be derived from downstream capacity , not inbound request count.
Pitfall 2: blockHandler signature mismatch. Missing BlockException parameter, or return type void → Sentinel silently doesn't call, manifests as "configured fallback but still 500".
Pitfall 3: Catching BlockException as business exception. Swallowing BlockException in try-catch(Throwable) → Sentinel's exit can't record block, monitoring data all wrong.
Pitfall 4: Rules only in console. No data source → restart loses, multi-instance rules inconsistent, stress test fine, deployment runs naked.
Pitfall 5: Circuit breaker duration too long. timeWindow set 60 seconds, downstream recovers in 3 seconds, yet wait a minute to half-open, users wait in vain. Generally start at 5–10 seconds.
Pitfall 6: Confusing slowRatioThreshold with count. RT mode: count is ms threshold; exception ratio mode: count is ratio; exception count mode: count is count. Misconfig → no error, just ineffective.
Pitfall 7: Uniform queueing maxQueueingTimeMs set too large. Queueing doesn't occupy threads but occupies connections; requests waiting 5 seconds fill upstream connection pool, amplifying failure instead.
Pitfall 8: Hotspot parameter rule missing parameter index. paramIdx starts at 0, off-by-one → rule never matches; also hotspot only supports primitives and String.
Troubleshooting Three Steps: ① Check /actuator/sentinel endpoint to confirm rules actually loaded (many stuck here); ② In console "Cluster Node Chain" find resource name, confirm call indeed counted (not found → resource name mismatch or didn't go through SphU); ③ Open csp.sentinel.log.dir sentinel-record.log , see per-second pass/block counts and BlockException stack traces. Most common causes: resource name mismatch and fallback method signature errors.
Learning Path and Interview Questions
9.1 Four-Stage Path
Beginner (3 days): Connect console, configure direct rate limiting on three core interfaces, observe QPS curve and reject counts; understand resource name and rule binding.
Intermediate (1 week): Write three @SentinelResource fallback methods correctly; persist flow rules to Nacos; integrate gateway layer and Feign layer once each, understand resource dimension differences.
Advanced (2 weeks): Read four source code sections — StatisticSlot, LeapArray, RateLimiterController, CircuitBreakerStateMachine; draw sliding window timeline.
Practice (ongoing): Conduct one fault drill: manually raise downstream RT to 2 seconds, verify circuit breaker opens as expected, half-open recovers, degradation returns as expected.
9.2 Twelve Interview Questions (with Summary Answers)
Q1 · What is Sentinel's core execution flow?
Answer: SphU.entry constructs a Slot responsibility chain, nine Slots execute sequentially: NodeSelectorSlot builds call tree, ClusterBuilderSlot builds global node, StatisticSlot statistics, AuthoritySlot validates black/white list, SystemSlot does system protection, ParamFlowSlot hotspot limiting, FlowSlot flow control, DegradeSlot circuit breaker judgment. Any Slot throwing BlockException interrupts and rolls back statistics.
Q2 · How is Sentinel's sliding window implemented?
Answer: Core is LeapArray : a fixed-length circular array with timestamp validation. Total window 1000ms split into several buckets (default 2, each 500ms). Write: compute bucket by current time, clear old value. Read: traverse all buckets, sum only non-expired. Compared to fixed window, avoids boundary double-burst; error bound is one bucket length.
Q3 · Why is statistics in the middle of Slot chain, not at the end?
Answer: Because downstream Slots (rate limiting, circuit breaking) must judge first, then decide what to record based on result. StatisticSlot first fireEntry passes down; all pass → record passCount ; blocked by BlockException → record blockCount ; business exception → record errorCount . Three counts separated, so pass rate and exception ratio are meaningful.
Q4 · Difference between rate limiting, circuit breaking, degradation?
Answer: Rate limiting watches inbound rate, exceeds threshold → direct reject, protects self; circuit breaking watches historical call results (slow call ratio, exception ratio), downstream unhealthy → stop calling, protects caller; degradation is action after circuit breaking, decides what fallback data to return when not calling. Rate limiting judges "how many in", circuit breaking judges "how results out", degradation decides "what to give when not out".
Q5 · How is uniform queueing implemented? No queue, how to queue?
Answer: Uses leaky bucket idea, no real queue needed. RateLimiterController computes time slot cost per request from QPS, uses latestPassedTime to record last pass time, calculates future time point this request should pass; if that time exceeds maxQueueingTimeMs</sub> → reject; else CAS competes for time slice. Fail to acquire → reject. No thread blocking throughout.</p> </blockquote> <p><strong>Q6 · How do circuit breaker state machine's three states transition?</strong></p> <blockquote> <p><strong>Answer:</strong> <code>CLOSED normal pass and statistics; window request count reaches minimum sample, and slow call ratio or exception ratio exceeds threshold → OPEN , directly throw DegradeException ; OPEN persists timeWindow → HALF_OPEN , let one request probe, success → back to CLOSED and clear statistics, failure → reopen.
Q7 · Does circuit breaker's count parameter mean the same in different modes?
Answer: No, this is the easiest misconfiguration. Slow call ratio mode: count is slow call threshold RT (ms); exception ratio mode: count is ratio threshold (0~1); exception count mode: count is count. Misconfig won't error, just silently ineffective.
Q8 · Difference between blockHandler and fallback?
Answer: blockHandler handles BlockException (rate limit, circuit break, system protection, auth reject); fallback handles business exceptions. Both method signatures must match original method (return type, parameter types), plus one extra BlockException or Throwable parameter. Signature mismatch → Sentinel silently doesn't call.
Q9 · How to persist rules?
Answer: Three modes: Original — only memory, restart loses; Pull — client periodically pulls file/HTTP, not real-time; Push — rules in Nacos/Apollo/ZK, client listens, changes pushed real-time. Production must use Push, and each rule type separate data-id to avoid overwriting.
Q10 · Difference between Sentinel and Hystrix?
Answer: Hystrix uses thread pool isolation, thorough but high thread overhead, one pool per dependency; Sentinel uses sliding window statistics plus semaphore-style concurrent thread count control, low overhead, high precision, also provides console, dynamic rule sources, hotspot limiting, system adaptive protection, chain flow control. Hystrix no longer maintained.
Q11 · What's the difference in resource dimensions between Sentinel at gateway layer and Feign layer?
Answer: Gateway layer resource name is route id, rate limiting at ingress, request never hits downstream; Feign layer resource name is interface fully qualified name plus method signature, targets single remote call for circuit breaking. Thresholds must coordinate: gateway threshold should be greater than service threshold, so rejection happens at outermost layer, avoiding useless traffic entering internal network.
Q12 · Sentinel appears not effective online, how to troubleshoot?
Answer: Three steps: 1) Check /actuator/sentinel endpoint to confirm rules actually loaded; 2) In console "Cluster Node Chain" find resource name, not found → resource name mismatch or call didn't go through SphU ; 3) Check sentinel-record.log for pass/block counts and BlockException stacks. Most common causes: resource name mismatch and fallback method signature errors.
9.3 One-Page Cheatsheet
Nine Slots: Build Tree / Statistics / Whitelist / System / Hotspot / Flow Control / Circuit Break<br> Statistics in middle: Judge first, then record pass/block/error<br> Sliding Window: Circular array 1000ms split 2 buckets<br> Error one bucket, avoids boundary double burst<br> Three Effects: Fast Fail / Uniform Queue / Warm-up<br> Queue uses CAS for time slice, no thread block<br> Three Modes: Direct / Associate / Chain<br> Circuit Break Three States: CLOSED-OPEN-HALF_OPEN<br> Minimum sample prevents misjudgment, circuit break 5-10s<br> Count Three Meanings: RT ms / Ratio / Count<br> blockHandler handles Block, fallback handles Business<br> Signature must match original method<br> Rules must push to Nacos, console only for debug<br> Gateway threshold > Service threshold, reject at outer layer
Summary: The value of rate limiting and circuit breaking lies not in "rules configured", but in "rules calculated accurately, judgments made fast, failures handled cleanly". Sliding window determines accurate calculation, Slot chain determines fast and extensible judgment, fallback methods determine what users see when failure occurs. Missing any one, the protection mechanism is just a few curves on a monitoring panel. Next up: Configuration Governance — Nacos Config Dynamic Refresh and Canary Release — How Configuration Changes Don't Blow Up Services .
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.
