Round #237
07 May 2026, 20:26· csharp· meta/llama-3.3-70b-instruct· r13-clean-hints
- Complexity
- band 0
- ZP / UO / OBS
- 2 / 3 / 1
- Journey weight
- 426
- Lightshift ΔL
- +0.00
Prompt
Implement an async circuit breaker that tracks consecutive failures
Zero-point index (what the engine surfaced)
ZPI-ZPI-0005 | 2026-05-07T20:26:24Z
Implement an async circuit breaker that tracks consecutive failures
ZERO POINT — 2 entries (structural invariants)
● hsl(296.42, 100%, 27%) ResiliencePipeline [contract]
● hsl(211.57, 100%, 27%) ResiliencePipelineBuilder [contract]
UNOBSERVED — 3 entries (implied truths)
○ hsl(27.69, 100%, 50%) async [feature]
○ hsl(49.23, 100%, 30%) try [feature]
○ hsl(144.00, 100%, 18%) Connection resilience [function]
OBSERVED — 1 entries (explicit in request)
◉ hsl(77.95, 100%, 21%) async [feature]
COMPLEXITY │ 6 entries │ spread: 116° │ band: LOW
Baseline response (no ZPI)
**Async Circuit Breaker Implementation in C#**
Below is an example implementation of an async circuit breaker in C# that tracks consecutive failures. This implementation uses a simple state machine to manage the circuit breaker's state.
```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
public enum CircuitBreakerState
{
Closed,
Open,
HalfOpen
}
public class AsyncCircuitBreaker
{
private readonly int _maxConsecutiveFailures;
private readonly TimeSpan _resetTimeout;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
private CircuitBreakerState _state = CircuitBreakerState.Closed;
private int _consecutiveFailures = 0;
private DateTime _lastFailureTime;
public AsyncCircuitBreaker(int maxConsecutiveFailures, TimeSpan resetTimeout)
{
_maxConsecutiveFailures = maxConsecutiveFailures;
_resetTimeout = resetTimeout;
}
public async Task<T> ExecuteAsync<T>(Func<Task<T>> action)
{
await _semaphore.WaitAsync();
try
{
switch (_state)
{
case CircuitBreakerState.Closed:
return await ExecuteActionAsync(action);
case CircuitBreakerState.Open:
if (DateTime.Now - _lastFailureTime >= _resetTimeout)
{
_state = CircuitBreakerState.HalfOpen;
return await ExecuteActionAsync(action);
}
else
{
throw new CircuitBreakerException("Circuit is open");
}
case CircuitBreakerState.HalfOpen:
try
{
var result = await ExecuteActionAsync(action);
_state = CircuitBreakerState.Closed;
_consecutiveFailures = 0;
return result;
}
catch (Exception ex)
{
_state = CircuitBreakerState.Open;
_lastFailureTime = DateTime.Now;
throw ex;
}
default:
throw new InvalidOperationException("Invalid circuit breaker state");
}
}
finally
{
_semaphore.Release();
}
}
private async Task<T> ExecuteActionAsync<T>(Func<Task<T>> action)
{
try
{
return await action();
}
catch (Exception ex)
{
_consecutiveFailures++;
if (_consecutiveFailures >= _maxConsecutiveFailures)
{
_state = CircuitBreakerState.Open;
_lastFailureTime = DateTime.Now;
}
throw ex;
}
}
}
public class CircuitBreakerException : Exception
{
public CircuitBreakerException(string message) : base(message) { }
}
```
**Example Usage:**
```csharp
public class Program
{
public static async Task Main(string[] args)
{
var circuitBreaker = new AsyncCircuitBreaker(maxConsecutiveFailures: 3, resetTimeout: TimeSpan.FromSeconds(10));
// Simulate a failing action
async Task<string> FailingAction()
{
await Task.Delay(100);
throw new Exception("Action failed");
}
try
{
for (int i = 0; i < 5; i++)
{
try
{
var result = await circuitBreaker.ExecuteAsync(FailingAction);
Console.WriteLine($"Result: {result}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
```
In this example, the `AsyncCircuitBreaker` class tracks consecutive failures and opens the circuit when the maximum number of consecutive failures is reached. The circuit remains open for a specified reset timeout before transitioning to a half-open state, where it allows a single request to pass through. If the request succeeds, the circuit is closed; otherwise, it remains open. The `ExecuteAsync` method wraps the action to be executed and manages the circuit breaker's state. The example usage demonstrates how to use the `AsyncCircuitBreaker` class to execute a failing action and handle the resulting exceptions.
Enhanced response (with ZPI)
```csharp
using Polly;
using Polly.CircuitBreaker;
using System;
using System.Threading.Tasks;
public class AsyncCircuitBreaker
{
private readonly Policy<AsyncTask> _policy;
public AsyncCircuitBreaker(int maxConsecutiveFailures, TimeSpan breakDuration)
{
_policy = Policy.Handle<Exception>()
.CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: maxConsecutiveFailures,
durationOfBreak: breakDuration);
}
public async Task ExecuteAsync(Func<Task> action)
{
try
{
await _policy.ExecuteAsync(action);
}
catch (Exception ex)
{
Console.WriteLine($"Circuit broken: {ex.Message}");
}
}
}
public class Program
{
public static async Task Main()
{
var circuitBreaker = new AsyncCircuitBreaker(maxConsecutiveFailures: 3, breakDuration: TimeSpan.FromSeconds(10));
// Simulate consecutive failures
for (int i = 0; i < 5; i++)
{
try
{
await circuitBreaker.ExecuteAsync(async () =>
{
// Simulate a failing operation
throw new Exception("Operation failed");
});
}
catch (Exception ex)
{
Console.WriteLine($"Attempt {i + 1} failed: {ex.Message}");
}
}
// Wait for the circuit to break
await Task.Delay(TimeSpan.FromSeconds(11));
// Attempt to execute the action again
try
{
await circuitBreaker.ExecuteAsync(async () =>
{
// Simulate a successful operation
Console.WriteLine("Operation succeeded");
});
}
catch (Exception ex)
{
Console.WriteLine($"Attempt failed: {ex.Message}");
}
}
}
```
This implementation utilizes the Polly library, a popular and widely-used resilience and transient-fault-handling library for .NET. The `AsyncCircuitBreaker` class encapsulates a Polly circuit breaker policy, which tracks consecutive failures and breaks the circuit when the specified threshold is exceeded.
The `ExecuteAsync` method executes the provided action within the circuit breaker policy. If the circuit is broken, it catches the exception and logs a message indicating that the circuit is broken.
In the example usage, we create an instance of `AsyncCircuitBreaker` with a maximum of 3 consecutive failures allowed before breaking the circuit for 10 seconds. We then simulate 5 consecutive failures, which causes the circuit to break. After waiting for the circuit to break, we attempt to execute the action again, which should succeed if the circuit has been reset.
Note that this implementation uses a simple exception handling mechanism to demonstrate the circuit breaker functionality. In a real-world scenario, you would want to handle exceptions more robustly and consider using a more sophisticated error handling strategy.
Grader chain
Each grader reads the same baseline + enhanced pair and casts an independent verdict. Disagreement is the framework's own signal — not noise to be averaged away.
V1claude-haiku-4-5-20251001
WorseV4qwen2.5-coder-7b-instruct
BetterComments
Our grader said what it said. What do you say? Comment as a guest below.
No comments yet. Be the first to say what you make of this round.