返回题库

熔断器模式

Circuit Breaker Pattern

专题
Systems & Architecture / 系统与架构
难度
L3
来源
MyntBit

题目详情

在量化交易系统中,熔断器保护交易所网关,在连续拒绝(因连接断裂或无效参数)时临时停止订单流。将此逻辑实现为有限状态机防止洪泛交易所,避免严重处罚。

任务:实现 CircuitBreaker 类,维护状态机(CLOSED/OPEN/HALF_OPEN)。CLOSED 正常发送订单;连续 N 次拒绝后切换 OPEN,停止发送;OPEN 超时后切换 HALF_OPEN,允许试探发送;试探成功切换 CLOSED,失败切换 OPEN。

英文原题

In quantitative trading systems, a circuit breaker protects the exchange gateway by temporarily halting order flow when consecutive rejections occur due to broken connections or invalid parameters. Implementing this logic as a finite state machine prevents flooding the venue, avoiding severe exchange penalties and ensuring controlled recovery through test orders.
Task
Implement the CircuitBreaker class to manage order flow state using a Finite State Machine with three states: CLOSED, OPEN, and HALF_OPEN (testing recovery).

解析

问题分析

熔断器模式防止级联故障:当错误率超过阈值时,自动停止调用外部服务,经过冷却期后尝试半开状态探测恢复。

解法

class CircuitBreaker {
    enum State { CLOSED, OPEN, HALF_OPEN };
    State state_{CLOSED}; int failures_{0}, successes_{0};
    const int threshold_, timeout_ms_;
    std::chrono::steady_clock::time_point opened_at_;
public:
    bool allowRequest() {
        if (state_ == OPEN && std::chrono::steady_clock::now() - opened_at_ > std::chrono::milliseconds(timeout_ms_))
        { state_ = HALF_OPEN; successes_ = 0; }
        return state_ != OPEN;
    }
    void recordSuccess() { if (state_ == HALF_OPEN && ++successes_ >= 3) { state_ = CLOSED; failures_ = 0; } }
    void recordFailure() { if (++failures_ >= threshold_) { state_ = OPEN; opened_at_ = std::chrono::steady_clock::now(); } }
};

复杂度与边界

  • 时间复杂度:所有操作 O(1)
  • 边界条件:(1) CLOSED→OPEN 瞬间切换 (2) HALF_OPEN 需连续成功才恢复 (3) 超时后首次请求触发 HALF_OPEN

英文解析

Analysis

The circuit breaker pattern prevents cascading failures: when the error rate exceeds a threshold, calls to the external service are automatically stopped. After a cooldown period, a half-open state probes for recovery.

Solution

class CircuitBreaker {
    enum State { CLOSED, OPEN, HALF_OPEN };
    State state_{CLOSED}; int failures_{0}, successes_{0};
    const int threshold_, timeout_ms_;
    std::chrono::steady_clock::time_point opened_at_;
public:
    bool allowRequest() {
        if (state_ == OPEN && std::chrono::steady_clock::now() - opened_at_ > std::chrono::milliseconds(timeout_ms_))
        { state_ = HALF_OPEN; successes_ = 0; }
        return state_ != OPEN;
    }
    void recordSuccess() { if (state_ == HALF_OPEN && ++successes_ >= 3) { state_ = CLOSED; failures_ = 0; } }
    void recordFailure() { if (++failures_ >= threshold_) { state_ = OPEN; opened_at_ = std::chrono::steady_clock::now(); } }
};

Complexity & Edge Cases

  • Time complexity: All operations O(1)
  • Edge cases: (1) CLOSED to OPEN transition is instant (2) HALF_OPEN requires consecutive successes to recover (3) Timeout triggers HALF_OPEN on first subsequent request

Key Considerations

  1. Threshold calibration: Circuit breaker trip threshold must exceed normal volatility but catch genuine anomalies — too sensitive causes false trips, too tolerant misses real failures
  2. Half-open state: After cooldown, allow limited probe requests through; if probes succeed, close circuit; if probes fail, re-open — prevents premature recovery
  3. Cascading breakers: Multiple breakers in a pipeline can cascade trip; coordinate cooldown periods to avoid synchronized re-opening that overloads recovered service
  4. Metric selection: Trip condition can be error rate, latency threshold, or throughput drop — choose metric matching the failure mode the breaker protects against