Round #307
08 May 2026, 13:14· csharp· llama-3.3-70b-versatile· r13-clean-hints
- Complexity
- band 0
- ZP / UO / OBS
- 2 / 3 / 1
- Journey weight
- 362
- 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-08T13:14:49Z
Implement an async circuit breaker that tracks consecutive failures
ZERO POINT — 2 entries (structural invariants)
● hsl(296.42, 100%, 39%) ResiliencePipeline [contract]
● hsl(211.57, 100%, 39%) ResiliencePipelineBuilder [contract]
UNOBSERVED — 3 entries (implied truths)
○ hsl(27.69, 100%, 50%) async [feature]
○ hsl(49.23, 100%, 50%) try [feature]
○ hsl(144.00, 100%, 30%) Connection resilience [function]
OBSERVED — 1 entries (explicit in request)
◉ hsl(77.95, 100%, 30%) async [feature]
COMPLEXITY │ 6 entries │ spread: 116° │ band: LOW
Baseline response (no ZPI)
**Async Circuit Breaker Implementation in C#**
Below is a simple implementation of an async circuit breaker in C# that tracks consecutive failures. This implementation uses a 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<bool> IsClosedAsync()
{
await _semaphore.WaitAsync();
try
{
return _state == CircuitBreakerState.Closed;
}
finally
{
_semaphore.Release();
}
}
public async Task ExecuteAsync(Func<Task> action)
{
await _semaphore.WaitAsync();
try
{
if (_state == CircuitBreakerState.Open)
{
if (DateTime.Now - _lastFailureTime > _resetTimeout)
{
_state = CircuitBreakerState.HalfOpen;
}
else
{
throw new CircuitBreakerException("Circuit is open");
}
}
if (_state == CircuitBreakerState.HalfOpen)
{
try
{
await action();
_state = CircuitBreakerState.Closed;
_consecutiveFailures = 0;
}
catch (Exception ex)
{
_state = CircuitBreakerState.Open;
_lastFailureTime = DateTime.Now;
_consecutiveFailures++;
throw;
}
}
if (_state == CircuitBreakerState.Closed)
{
try
{
await action();
}
catch (Exception ex)
{
_consecutiveFailures++;
if (_consecutiveFailures >= _maxConsecutiveFailures)
{
_state = CircuitBreakerState.Open;
_lastFailureTime = DateTime.Now;
}
throw;
}
}
}
finally
{
_semaphore.Release();
}
}
}
public class CircuitBreakerException : Exception
{
public CircuitBreakerException(string message) : base(message) { }
}
class Program
{
static async Task Main(string[] args)
{
var circuitBreaker = new AsyncCircuitBreaker(3, TimeSpan.FromSeconds(10));
// Simulate a failing action
Func<Task> failingAction = async () =>
{
await Task.Delay(100);
throw new Exception("Simulated failure");
};
// Test the circuit breaker
for (int i = 0; i < 10; i++)
{
try
{
await circuitBreaker.ExecuteAsync(failingAction);
}
catch (Exception ex)
{
Console.WriteLine($"Iteration {i + 1}: {ex.Message}");
}
await Task.Delay(100);
}
}
}
```
**Explanation**
* The `AsyncCircuitBreaker` class implements the circuit breaker pattern.
* It has three states: `Closed`, `Open`, and `HalfOpen`.
* When the circuit is `Closed`, it allows actions to be executed.
* If the number of consecutive failures exceeds the specified threshold (`_maxConsecutiveFailures`), the circuit opens.
* When the circuit is `Open`, it prevents actions from being executed for a specified period (`_resetTimeout`).
* After the timeout, the circuit transitions to the `HalfOpen` state, allowing a single action to be executed.
* If the action succeeds, the circuit closes; otherwise, it opens again.
* The `ExecuteAsync` method executes the provided action while considering the circuit breaker's state.
* The `IsClosedAsync` method checks whether the circuit is currently closed.
**Example Usage**
The example usage demonstrates how to create an instance of the `AsyncCircuitBreaker` class and use it to execute a failing action. The circuit breaker opens after three consecutive failures and remains open for 10 seconds before transitioning to the half-open state.
Enhanced response (with ZPI)
```csharp
using Polly;
using Polly.CircuitBreaker;
using System;
using System.Threading.Tasks;
public class CircuitBreaker
{
private readonly Policy<HttpResponseMessage> _policy;
public CircuitBreaker(int maxConsecutiveFailures, TimeSpan durationOfBreak)
{
_policy = Policy.Handle<HttpRequestException>()
.CircuitBreakerAsync(
exceptionsAllowedBeforeBreaking: maxConsecutiveFailures,
durationOfBreak: durationOfBreak);
}
public async Task<HttpResponseMessage> ExecuteAsync(Func<Task<HttpResponseMessage>> action)
{
return await _policy.ExecuteAsync(action);
}
}
public class Program
{
public static async Task Main(string[] args)
{
var circuitBreaker = new CircuitBreaker(maxConsecutiveFailures: 3, durationOfBreak: TimeSpan.FromSeconds(30));
// Simulate a failing HTTP request
Func<Task<HttpResponseMessage>> failingRequest = async () =>
{
await Task.Delay(100);
throw new HttpRequestException("Request failed");
};
try
{
var response = await circuitBreaker.ExecuteAsync(failingRequest);
Console.WriteLine($"Response: {response}");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
}
catch (BrokenCircuitException ex)
{
Console.WriteLine($"Circuit broken: {ex.Message}");
}
}
}
```
This implementation utilizes the Polly library, a popular and widely-used resilience and transient-fault-handling library for .NET. The `CircuitBreaker` class encapsulates a Polly circuit breaker policy, which tracks consecutive failures and breaks the circuit when the specified threshold is exceeded.
In the example, a `CircuitBreaker` instance is created with a maximum of 3 consecutive failures allowed before the circuit is broken for 30 seconds. The `ExecuteAsync` method wraps the execution of a given action (in this case, a failing HTTP request) with the circuit breaker policy.
When the circuit is broken, a `BrokenCircuitException` is thrown, indicating that the circuit is currently open and requests should not be attempted. Once the break duration has expired, the circuit will automatically reset, allowing requests to be attempted again.
Note that this implementation uses `HttpRequestException` as the exception type to handle, but you can modify this to handle other types of exceptions as needed. Additionally, you can adjust the `maxConsecutiveFailures` and `durationOfBreak` parameters to suit your specific requirements.
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-sonnet-4-6
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.