Demonstrates the circuit breaker resilience pattern.
Demonstrates the circuit breaker resilience pattern.Shows state transitions (CLOSED → OPEN → HALF_OPEN → CLOSED), RAII guards, configuration, and stats reporting.
#include <chrono>
#include <iostream>
#include <string>
#include <thread>
{
switch (s)
{
case circuit_state::CLOSED:
return "CLOSED";
case circuit_state::OPEN:
return "OPEN";
case circuit_state::HALF_OPEN:
return "HALF_OPEN";
default:
return "UNKNOWN";
}
}
{
if (should_fail)
{
throw std::runtime_error("Service unavailable");
}
return true;
}
{
std::cout << "=== Circuit Breaker Example ===\n\n";
config.
timeout = std::chrono::seconds(1);
std::cout <<
"Initial state: " <<
state_name(breaker.get_state()) <<
"\n\n";
std::cout << "1. Simulating failures...\n";
for (int i = 0; i < 4; ++i)
{
if (!breaker.allow_request())
{
std::cout << " Request " << i << ": REJECTED (circuit open)\n";
continue;
}
try
{
auto guard = breaker.make_guard();
guard.record_success();
}
catch (const std::exception& e)
{
std::cout << " Request " << i << ": FAILED (" << e.what() << ")\n";
}
std::cout <<
" State: " <<
state_name(breaker.get_state()) <<
"\n";
}
std::cout << "\n2. Waiting for timeout (1s)...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1100));
std::cout <<
" State after timeout: " <<
state_name(breaker.get_state()) <<
"\n";
std::cout << "\n3. Recovering with successful requests...\n";
for (int i = 0; i < 3; ++i)
{
if (!breaker.allow_request())
{
std::cout << " Recovery " << i << ": REJECTED\n";
continue;
}
auto guard = breaker.make_guard();
guard.record_success();
std::cout <<
" Recovery " << i <<
": SUCCESS, state=" <<
state_name(breaker.get_state())
<< "\n";
}
std::cout << "\n4. Circuit breaker stats:\n";
auto stats = breaker.get_stats();
for (auto it = stats.begin(); it != stats.end(); ++it)
{
const auto& name = it->first;
const auto& val = it->second;
std::visit(
[&name](const auto& v) { std::cout << " " << name << ": " << v << "\n"; },
val);
}
std::cout << "\nDone.\n";
return 0;
}
Circuit breaker pattern for fault tolerance and resilience.
std::string state_name(circuit_state s)
bool call_external_service(bool should_fail)
Thread-safe circuit breaker for fault tolerance.
circuit_state
Represents the current state of a circuit breaker.
Configuration parameters for circuit breaker.
std::chrono::milliseconds timeout
Timeout before transitioning from OPEN to HALF_OPEN. Default: 30 seconds.
std::size_t failure_threshold
Number of failures required to trip the circuit (CLOSED -> OPEN). Default: 5 failures.
std::size_t success_threshold
Number of successful requests required to close the circuit (HALF_OPEN -> CLOSED)....