Skip to main content
Ryan Mitchell·

Finally a Circuit Breaker impl with the UML and the thread-safety bits actually correct

Implements any Gang of Four or modern design pattern with real-world context, UML diagrams, and usage examples.

Design Pattern Implementation Factory

You are a software architect implementing a design pattern for a real-world system. Provide a complete, production-quality implementation. ## Pattern Request - Pattern: {{design_pattern}} (e.g., Strategy, Observer, Circuit Breaker, Saga) - Language: {{programming_language}} - Context: {{usage_context}} (e.g., payment processing, real-time notifications) - Framework: {{framework}} if applicable ## Deliverables 1. **Pattern Overview** - What problem it solves, when to use/when NOT to use 2. **UML Diagram** - ASCII class diagram showing all participants and relationships 3. **Implementation** - Complete code with: - All pattern participants (interfaces, abstract classes, concrete implementations) - Proper encapsulation and loose coupling - Thread-safety if applicable ({{programming_language}} concurrency model) - Generic/type-safe where appropriate 4. **Real-World Usage Example** - Concrete scenario showing the pattern in action 5. **Integration Guide** - How to adopt this pattern in an existing codebase 6. **Common Pitfalls** - Mistakes developers make with this pattern 7. **Related Patterns** - Complementary patterns that work well together 8. **Modern Alternatives** - Language features or libraries that might replace this pattern Follow idiomatic {{programming_language}} conventions. The code should compile and be ready to use.

Ergebnisse

## Circuit Breaker — overview Prevents repeated calls to a failing dependency (the payment gateway) by tripping open after N failures, giving it time to recover. Use it around unreliable network calls; don't use it for fast in-process logic where retries are cheaper. ## UML (ASCII) ``` success ≥ threshold ┌──────────────────────────┐ CLOSED ──fail≥N──▶ OPEN ──timeout──▶ HALF_OPEN ▲ │ └────────────success─────────────────┘ (one trial call) ``` ## Implementation (Go, goroutine-safe) ```go type Breaker struct { mu sync.Mutex failures int threshold int openUntil time.Time } func (b *Breaker) Call(fn func() error) error { b.mu.Lock() if time.Now().Before(b.openUntil) { b.mu.Unlock(); return ErrOpen } b.mu.Unlock() err := fn() b.mu.Lock(); defer b.mu.Unlock() if err != nil { if b.failures++; b.failures >= b.threshold { b.openUntil = time.Now().Add(30 * time.Second) } return err } b.failures = 0 return nil } ``` **Pitfall:** sharing one breaker across unrelated dependencies — give each downstream its own. **Related:** Retry + Bulkhead. **Modern alt:** `sony/gobreaker` if you'd rather not own the state machine.

Modell: Claude Sonnet 4

8 Likes2 SavesScore: 8

1 Kommentar

Daniel Cohen·

Nice. The schema validation up front prevents a whole class of bugs.