पाठ 14 / 26
Circuit Breakers और Outlier Detection
विफल होती dependency को कुछ देर बुलाना रोकें ताकि वह सुधर सके और callers जल्दी विफल हों।
Closed, open, half-open
Circuit breaker किसी dependency की calls पर नज़र रखता है। Closed स्थिति में calls सामान्य रूप से जाती हैं। पर्याप्त विफलताओं के बाद वह open होता है: calls संघर्ष कर रही service तक पहुँचे बिना तुरंत अस्वीकार हो जाती हैं (fast fail), जिससे उसे सुधरने की जगह मिलती है और callers का समय नहीं बर्बाद होता। Cool-down के बाद वह half-open होता है और एक परीक्षण call जाने देता है: सफलता circuit बंद करती है, विफलता उसे फिर खोल देती है। Meshes और gateways संबंधित सुरक्षाएँ जोड़ते हैं: outlier detection (बिगड़े instance को pool से अस्थायी रूप से निकालना), connection और अनुरोध सीमाएँ (bulkheads) और load shedding। Circuit खुला हो तब के लिए हमेशा उचित fallback (cached डेटा, डिफ़ॉल्ट, साफ़ error) रखें।
Circuit breaker की state machine, चलाकर
मैंने यह सादा-Python मॉडल चलाया। t=2 पर तीन विफलताएँ circuit खोलती हैं। t=3 और t=4 की calls तुरंत अस्वीकार हैं। 10 सेकंड के cool-down के बाद t=13 की call परीक्षण के रूप में अनुमत होती है, सफल होती है और circuit बंद करती है।
import hashlib, bisect, math, random
class Breaker:
def __init__(self, threshold=3, cooldown=10):
self.threshold, self.cooldown, self.fails, self.state, self.opened_at = threshold, cooldown, 0, "closed", None
def call(self, now, ok):
if self.state == "open":
if now - self.opened_at >= self.cooldown: self.state = "half-open"
else: return "rejected (fast fail)"
if ok:
self.fails = 0; self.state = "closed"; return "ok"
self.fails += 1
if self.state == "half-open" or self.fails >= self.threshold:
self.state, self.opened_at = "open", now
return "failed"
b = Breaker()
events = [(0, False), (1, False), (2, False), (3, True), (4, True), (13, True), (14, True)]
print([(t, b.call(t, ok), b.state) for t, ok in events])
Output:
[(0, 'failed', 'closed'), (1, 'failed', 'closed'), (2, 'failed', 'open'), (3, 'rejected (fast fail)', 'open'), (4, 'rejected (fast fail)', 'open'), (13, 'ok', 'closed'), (14, 'ok', 'closed')]
Envoy-शैली की सुरक्षाएँ (उदाहरण)
Mesh में ये कोड की जगह नीति के रूप में घोषित होती हैं। यह Istio DestinationRule connections सीमित करता है और बार-बार 5xx लौटाने वाले instances को हटाता है। Field नाम Istio के अनुसार हैं; यहाँ चलाए नहीं गए।
apiVersion: networking.istio.io/v1
kind: DestinationRule
metadata: { name: orders }
spec:
host: orders
trafficPolicy:
connectionPool:
http: { http1MaxPendingRequests: 50, maxRequestsPerConnection: 100 }
outlierDetection:
consecutive5xxErrors: 5
interval: 10s
baseEjectionTime: 30s
maxEjectionPercent: 50त्वरित जाँच: Open circuit breaker क्या करता है?
- Call encrypt करता है
- सारा traffic तेज़ भेजता है
- Service हटाता है
- विफल होती service और callers की रक्षा के लिए calls तुरंत अस्वीकार करता है
Answer
विफल होती service और callers की रक्षा के लिए calls तुरंत अस्वीकार करता है — तेज़ विफलता dependency को सुधरने का समय देती है और callers को उत्तरदायी रखती है।