A Scala implementation of Circuit Breaker

In this post I’ll describe how to use sse-breaker, a small library that implements the Circuit Breaker stability design pattern in Scala.

Before mentioning any sse-breaker specifics lets quickly define what is a Circuit Breaker. A Circuit Breaker is a software component that keeps track of the error rate of various operations and when the rate is high it prevents those operation from executing by failing-fast.

In sse-breaker the Circuit Breaker is implemented as an executor. To use it you create a CircuitExecutor instance and call its apply[T](op: =>T):T method passing the code that you would like to execute in the closure. Depending on the Circuit Breaker’s state (if errors have occurred recently) the executor will execute the requested operation or it will throw an OpenCircuitException.

For example lets say that we are developing a web application that uses the Twitter API. Obviously we wouldn’t want any capacity problems at Twitter (or any other site) to prevent our pages from rendering fast. To protect our application we could wrap any calls to the Twitter API with a Circuit Breaker.

To do this in sse-breaker we could use the following code:

class TwitterGateway(twitter: Twitter) {

  private val failfast = new CircuitExecutor("twitter-breaker")

  def getTimeline: List[Status] = failfast {

  def search(q: Query): QueryResult = failfast {

In the above code we’ve created a CircuitExecutor, named twitter-breaker, with the default configuration and wrapped the calls to the Twitter API. By default if five exceptions are thrown within a minute the Circuit Breaker will go into the open state and further requests to execute any operation, for the next 10 minutes, will throw an OpenCircuitException instead of executing the operation.

For more information see the homepage of sse-breaker.