circuit - Circuit Breaker for Scala Maven Central

The CircuitBreaker is used to provide stability and prevent cascading failures in distributed systems.

Quick Start

To use circuit in an existing SBT project with Scala 2.11 or a later version, add the following dependencies to your build.sbt depending on your needs:

libraryDependencies ++= Seq(
  "io.chrisdavenport" %% "circuit" % "<version>"
)

Purpose

As an example, we have a web application interacting with a remote third party web service. Let's say the third party has oversold their capacity and their database melts down under load. Assume that the database fails in such a way that it takes a very long time to hand back an error to the third party web service. This in turn makes calls fail after a long period of time. Back to our web application, the users have noticed that their form submissions take much longer seeming to hang. Well the users do what they know to do which is use the refresh button, adding more requests to their already running requests. This eventually causes the failure of the web application due to resource exhaustion. This will affect all users, even those who are not using functionality dependent on this third party web service.

Introducing circuit breakers on the web service call would cause the requests to begin to fail-fast, letting the user know that something is wrong and that they need not refresh their request. This also confines the failure behavior to only those users that are using functionality dependent on the third party, other users are no longer affected as there is no resource exhaustion. Circuit breakers can also allow savvy developers to mark portions of the site that use the functionality unavailable, or perhaps show some cached content as appropriate while the breaker is open.

How It Works

The circuit breaker models a concurrent state machine that can be in any of these 3 states:

Closed: During normal operations or when the CircuitBreaker starts

Open: The circuit breaker rejects all tasks with an RejectedExecution

HalfOpen: The circuit breaker has already allowed a task to go through, as a reset attempt, in order to test the connection

Usage

First some imports.

import cats.effect._
import io.chrisdavenport.circuit.{Backoff, CircuitBreaker}
import scala.concurrent.duration._

Then we construct the circuit breaker.

val circuitBreaker = CircuitBreaker.of[IO](
  maxFailures = 5,
  resetTimeout = 10.seconds
)
// circuitBreaker: IO[CircuitBreaker[IO]] = Map(
//   ioe = Delay(
//     thunk = cats.effect.IO$$$Lambda$10718/1161340161@214a0f6d,
//     event = cats.effect.tracing.TracingEvent$StackTrace
//   ),
//   f = io.chrisdavenport.circuit.CircuitBreaker$Builder$$Lambda$10720/1116675173@1ea9bc31,
//   event = cats.effect.tracing.TracingEvent$StackTrace
// )

//...
val problematic = IO {
  val nr = scala.util.Random.nextInt()
  if (nr % 2 == 0) nr else
    throw new RuntimeException("dummy")
}
// problematic: IO[Int] = Delay(
//   thunk = <function0>,
//   event = cats.effect.tracing.TracingEvent$StackTrace
// )

val task = circuitBreaker.flatMap(
  _.protect(problematic) // Circuit Breaker Shared State Location
)
// task: IO[Int] = FlatMap(
//   ioe = Map(
//     ioe = Delay(
//       thunk = cats.effect.IO$$$Lambda$10718/1161340161@214a0f6d,
//       event = cats.effect.tracing.TracingEvent$StackTrace
//     ),
//     f = io.chrisdavenport.circuit.CircuitBreaker$Builder$$Lambda$10720/1116675173@1ea9bc31,
//     event = cats.effect.tracing.TracingEvent$StackTrace
//   ),
//   f = <function1>,
//   event = cats.effect.tracing.TracingEvent$StackTrace
// )

When attempting to close the circuit breaker and resume normal operations, we can also apply an exponential backoff for repeated failed attempts, like so:

val exponential = CircuitBreaker.of[IO](
  maxFailures = 5,
  resetTimeout = 10.seconds,
  backoff = Backoff.exponential,
  maxResetTimeout = 10.minutes
)
// exponential: IO[CircuitBreaker[IO]] = Map(
//   ioe = Delay(
//     thunk = cats.effect.IO$$$Lambda$10718/1161340161@17969a2,
//     event = cats.effect.tracing.TracingEvent$StackTrace
//   ),
//   f = io.chrisdavenport.circuit.CircuitBreaker$Builder$$Lambda$10720/1116675173@24d482e,
//   event = cats.effect.tracing.TracingEvent$StackTrace
// )

In this sample we attempt to reconnect after 10 seconds, then after 20, 40 and so on, a delay that keeps increasing up to a configurable maximum of 10 minutes.

Credits

This data type was inspired by the availability of Akka's Circuit Breaker and ported to cats-effect from Monix and when its merger halted there, it was moved to circuit. The initial implementation and port by Alexandru Nedelcu and Oleg Pyzhcov was what enabled this ref based version to exist.