THN Interview Prep

Circuit Breaker (Concurrency / Resilience)

Intent / problem it solves

Stop calling a failing dependency after errors exceed a threshold (open circuit), periodically probe recovery (half-open), and resume traffic when healthy (closed). Prevents retry storms and thread starvation.

When to use / when NOT

Use for remote services, databases showing timeouts, or flaky partners.

Avoid hiding systemic overload—combine with timeouts, bulkheads, and rate limits; tune thresholds from SLOs.

Structure

Breaker wraps calls; tracks failures/successes in sliding windows; states gate execution.

Loading diagram…

Go example

package main

import (
	"errors"
	"fmt"
)

type CircuitBreaker struct {
	failures int
	threshold int
	open bool
}

func (breaker *CircuitBreaker) Call(work func() error) error {
	if breaker.open {
		return errors.New("circuit open")
	}
	err := work()
	if err != nil {
		breaker.failures++
		if breaker.failures >= breaker.threshold {
			breaker.open = true
		}
		return err
	}
	breaker.failures = 0
	return nil
}

func main() {
	breaker := &CircuitBreaker{threshold: 2}
	fmt.Println(breaker.Call(func() error { return errors.New("bad") }))
	fmt.Println(breaker.Call(func() error { return errors.New("bad") }))
	fmt.Println(breaker.Call(func() error { return nil }))
}

JavaScript example

class CircuitBreaker {
  constructor({ threshold }) {
    this.threshold = threshold;
    this.failures = 0;
    this.open = false;
  }

  async run(task) {
    if (this.open) {
      throw new Error('circuit open');
    }
    try {
      const result = await task();
      this.failures = 0;
      return result;
    } catch (error) {
      this.failures += 1;
      if (this.failures >= this.threshold) {
        this.open = true;
      }
      throw error;
    }
  }
}

const breaker = new CircuitBreaker({ threshold: 1 });
breaker.run(async () => {
  throw new Error('down');
}).catch(() => console.log('expected fail'));

Interview phrase

“Circuit breaker fails fast when a dependency is unhealthy, giving it time to recover and protecting our thread pool from hammering a dead endpoint.”

Map to LLD for HTTP clients, payment gateways, or external CRM adapters in LLD case studies. See caching for stale fallbacks.

Last updated on

Spotted something unclear or wrong on this page?

On this page