惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
G
Google Developers Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
S
SegmentFault 最新的问题
宝玉的分享
宝玉的分享
博客园 - Franky
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
月光博客
月光博客
博客园 - 聂微东
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
小众软件
小众软件
Microsoft Security Blog
Microsoft Security Blog
Last Week in AI
Last Week in AI
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
爱范儿
爱范儿
J
Java Code Geeks
博客园 - 叶小钗
Engineering at Meta
Engineering at Meta
阮一峰的网络日志
阮一峰的网络日志

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Circuit Breakers: The Unsung Heroes of Resilient Microser...
Manoir Yantai · 2026-05-29 · via DEV Community

Manoir Yantai

When you’re running multiple services in production, failures are unavoidable. A downstream service might spike latency, return 500s, or disappear entirely. Without protection, a single fault can cascade across your system, wasting threads, exhausting connection pools, and eventually taking down dependent services. This is where circuit breakers shine—they degrade gracefully instead of amplifying failure.

You’ve probably used timeouts and retries, but those alone aren’t enough. Retries exacerbate overload, and timeouts still waste resources waiting. A circuit breaker monitors failures, and when they cross a threshold, it short-circuits the call, returning a predefined fallback immediately. This stops your service from burning CPU on doomed requests and lets downstream recover under reduced load.

The state machine is simple: closed (normal operation), open (rejecting requests), and half-open (probing for recovery). In closed state, every call is passed through; failures increment a counter. If the failure ratio exceeds your threshold (e.g., 50% of the last 10 calls), it trips to open. In open state, calls fail fast without reaching the remote service. After a configurable timeout, it moves to half-open and allows a few probes—if they succeed, it resets to closed; if not, it goes back to open.

Implementing this isn’t rocket science. Libraries like gobreaker in Go or resilience4j in Java abstract the boilerplate. Here’s a concise example in Go:

import (
 "fmt"
 "github.com/sony/gobreaker"
)

var cb *gobreaker.CircuitBreaker

func init() {
 cb = gobreaker.NewCircuitBreaker(gobreaker.Settings{
  Name:        "user-svc",
  MaxRequests: 3,
  Interval:    30 * time.Second,
  Timeout:     10 * time.Second,
  ReadyToTrip: func(c gobreaker.Counts) bool {
   return c.Requests >= 5 && float64(c.TotalFailures)/float64(c.Requests) > 0.5
  },
 })
}

func FetchUser(id string) (string, error) {
 result, err := cb.Execute(func() (interface{}, error) {
  resp, err := http.Get("http://user-service/" + id)
  if err != nil {
   return nil, err
  }
  defer resp.Body.Close()
  if resp.StatusCode >= 500 {
   return nil, fmt.Errorf("upstream error: %d", resp.StatusCode)
  }
  return readBody(resp)
 })
 if err != nil {
  return "", err // caller can choose fallback
 }
 return result.(string), nil
}

This snippet tracks failures over 30-second windows. After 5 requests with a 50% failure rate, it opens for 10 seconds. During that window, Execute returns immediately, preserving your resources. The half-open probe allows 3 requests to verify recovery.

Now, don’t stop at basic implementation. Combine circuit breakers with other resilience patterns. Use a bulkhead to limit threads per breaker so one misbehaving service doesn’t exhaust your entire thread pool. Pair it with retries only for transient errors (e.g., 429 or 503) but cap retries and keep them out of the breaker’s failure count to avoid premature trips.

Monitoring is critical. Every state change should emit logs and metrics. Track trip rates, operation latency, and fallback invocations. If your breaker trips too often, your threshold might be too low—or the upstream is genuinely broken. Use separate settings per dependency; a critical user service can tolerate more failures than a logging endpoint.

Beware of common pitfalls. Don’t

Diagram