Round #212
07 May 2026, 14:09· csharp· meta/llama-3.3-70b-instruct· r12-real-contracts
- Complexity
- band 0
- ZP / UO / OBS
- 2 / 3 / 1
- Journey weight
- 433
- Lightshift ΔL
- —
Prompt
Implement an async circuit breaker that tracks consecutive failures
Zero-point index (what the engine surfaced)
ZPI-ZPI-0005 | 2026-05-07T14:09:17Z
Implement an async circuit breaker that tracks consecutive failures
ZERO POINT — 2 entries (structural invariants)
● hsl(296.42, 100%, 24%) ResiliencePipeline [contract]
● hsl(211.57, 100%, 24%) 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 ExecuteAction(action);
case CircuitBreakerState.Open:
if (DateTime.Now - _lastFailureTime >= _resetTimeout)
{
_state = CircuitBreakerState.HalfOpen;
return await ExecuteAction(action);
}
else
{
throw new CircuitBreakerException("Circuit is open");
}
case CircuitBreakerState.HalfOpen:
try
{
var result = await ExecuteAction(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> ExecuteAction<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
Func<Task<string>> failingAction = async () =>
{
await Task.Delay(100);
throw new Exception("Action failed");
};
try
{
var result = await circuitBreaker.ExecuteAsync(failingAction);
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// Simulate a successful action
Func<Task<string>> successfulAction = async () =>
{
await Task.Delay(100);
return "Action succeeded";
};
try
{
var result = await circuitBreaker.ExecuteAsync(successfulAction);
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
```
This implementation provides a basic async circuit breaker that tracks consecutive failures and opens the circuit when the maximum number of consecutive failures is reached. The circuit will remain open for a specified reset timeout before transitioning to a half-open state, where it will allow a single request to pass through. If the request succeeds, the circuit will close; otherwise, it will remain open.
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}");
throw;
}
}
}
public class Program
{
public static async Task Main(string[] args)
{
var circuitBreaker = new AsyncCircuitBreaker(maxConsecutiveFailures: 3, breakDuration: TimeSpan.FromSeconds(30));
// 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(30));
// 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 re-throws it, allowing the caller to handle the situation as needed.
In the example usage, we create an instance of `AsyncCircuitBreaker` with a maximum of 3 consecutive failures allowed before breaking the circuit for 30 seconds. We then simulate consecutive failures by attempting to execute a failing operation. After the circuit breaks, we wait for the specified break duration and attempt to execute a successful operation.
Note that this implementation uses the `Polly.CircuitBreaker` namespace, which provides a robust and configurable circuit breaker implementation. The `AsyncCircuitBreaker` class provides a simple and easy-to-use interface for working with the circuit breaker policy.
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
BetterV4qwen2.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.