Sobes.tech
Senior

Tell me about the Circuit Breaker you implemented for integration with an external system.

sobes.tech AI

Answer from AI

Circuit Breaker is a pattern that helps protect a system from repeated failed calls to external services, thereby preventing cascading failures and increasing application resilience.

In one of my Java projects, I implemented a Circuit Breaker for integrating with an external API, which sometimes became unavailable or responded with errors.

Main implementation points:

  • States:

    • Closed — all requests pass until an error threshold is exceeded.
    • Open — requests are blocked, and an error is returned immediately.
    • Half-Open — after a timeout, a few requests are attempted to check if recovery has occurred.
  • Logic:

    • Count the number of failed calls over a certain period.
    • If the error count exceeds the threshold, switch to the Open state.
    • After a specified timeout, transition to Half-Open and attempt a request.
    • If the request succeeds, return to Closed; otherwise, switch back to Open.

An example of a simplified Java implementation using AtomicInteger and enum for states:

public class CircuitBreaker {
    private enum State { CLOSED, OPEN, HALF_OPEN }

    private State state = State.CLOSED;
    private int failureCount = 0;
    private final int failureThreshold = 5;
    private long lastFailureTime = 0;
    private final long retryTimePeriod = 10000; // 10 seconds

    public synchronized boolean allowRequest() {
        if (state == State.OPEN) {
            if (System.currentTimeMillis() - lastFailureTime > retryTimePeriod) {
                state = State.HALF_OPEN;
                return true;
            }
            return false;
        }
        return true;
    }

    public synchronized void recordSuccess() {
        failureCount = 0;
        state = State.CLOSED;
    }

    public synchronized void recordFailure() {
        failureCount++;
        lastFailureTime = System.currentTimeMillis();
        if (failureCount >= failureThreshold) {
            state = State.OPEN;
        }
    }
}

This Circuit Breaker was integrated into the layer calling the external API: before a request, allowRequest() was checked; after a response, either recordSuccess() or recordFailure() was called.

This significantly reduced system load during external service issues and improved user experience through quick failure and subsequent recovery.