在分布式系统中,一切最终都会失败。弹性模式阻止单个故障级联成完全宕机。
const breaker = new CircuitBreaker(callPaymentService, {
timeout: 3000, // fail the call after 3s
errorThresholdPercentage: 50, // open if >50% of calls fail
resetTimeout: 10000 // after 10s, try one request (half-open)
});
breaker.fallback(() => ({ status: 'queued' })); // graceful degradation
CLOSED ──(failures exceed threshold)──▶ OPEN
▲ │ (after resetTimeout)
│ (trial succeeds) ▼
└────────────── HALF-OPEN ◀──────────────┘
(one trial request)
[ pool A: 10 threads ] → payment calls
[ pool B: 10 threads ] → search calls
If search hangs, it drains pool B only — payments keep working.
没有 backoff 的重试会放大已经困难的服务上的负载(重试风暴)。始终添加 backoff、jitter 和重试上限。
这些模式将不可避免的单个服务故障转变为功能降级,而不是网站范围的宕机。
它们协同工作:timeout 限制等待时间,circuit breaker 停止对死服务的轰击,bulkhead 限制影响范围,重试从小故障恢复——少了任何一个,故障仍然会级联。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠