= Vert.x Circuit Breaker

Vert.x Circuit Breaker is an implementation of the Circuit Breaker _pattern_ for Vert.x. It keeps track of the
number of failures and _opens the circuit_ when a threshold is reached. Optionally, a fallback is executed.

Supported failures are:

* failures reported by your code in a {@link io.vertx.core.Future}
* exception thrown by your code
* uncompleted futures (timeout)

Operations guarded by a circuit breaker are intended to be non-blocking and asynchronous in order to benefit from
the Vert.x execution model.

== Using the vert.x circuit breaker

To use the Vert.x Circuit Breaker, add the following dependency to the _dependencies_ section of your build
descriptor:

* Maven (in your `pom.xml`):

[source,xml,subs="+attributes"]
----
<dependency>
  <groupId>io.vertx</groupId>
  <artifactId>vertx-circuit-breaker</artifactId>
  <version>${maven.version}</version>
</dependency>
----

* Gradle (in your `build.gradle` file):

[source,groovy,subs="+attributes"]
----
compile 'io.vertx:vertx-circuit-breaker:${maven.version}'
----

== Using the circuit breaker

To use the circuit breaker you need to:

1. Create a circuit breaker, with the configuration you want (timeout, number of failure before opening the circuit)
2. Execute some code using the breaker

**Important**: Don't recreate a circuit breaker on every call. A circuit breaker is a staful entity. It is recommended
to store the circuit breaker instance in a field.

Here is an example:

[source,$lang]
----
{@link examples.CircuitBreakerExamples#example1(io.vertx.core.Vertx)}
----

The executed block receives a {@link io.vertx.core.Future} object as parameter, to denote the
success or failure of the operation as well as the result. For example in the following example, the result is the
output of a REST endpoint invocation:

[source,$lang]
----
{@link examples.CircuitBreakerExamples#example2(io.vertx.core.Vertx)}
----

The result of the operation is provided using the:

* returned {@link io.vertx.core.Future} when calling `execute` methods
* provided {@link io.vertx.core.Future} when calling the `executeAndReport` methods

Optionally, you can provide a fallback which is executed when the circuit is open:

[source,$lang]
----
{@link examples.CircuitBreakerExamples#example3(io.vertx.core.Vertx)}
----

The fallback is called whenever the circuit is open, or if the
{@link io.vertx.circuitbreaker.CircuitBreakerOptions#isFallbackOnFailure()} is enabled. When a fallback is
set, the result is using the output of the fallback function. The fallback function takes as parameter a
{@link java.lang.Throwable} object and returns an object of the expected type.

The fallback can also be set on the {@link io.vertx.circuitbreaker.CircuitBreaker} object directly:

[source,$lang]
----
{@link examples.CircuitBreakerExamples#example4(io.vertx.core.Vertx)}
----

== Retries

You can also specify how often the circuit breaker should try your code before failing with
{@link io.vertx.circuitbreaker.CircuitBreakerOptions#setMaxRetries(int)}.
If you set this to something higher than 0 your code gets executed several times before finally failing
in the last execution. If the code succeeded in one of the retries your handler gets notified and any
retries left are skipped. Retries are only supported when the circuit is closed.

Notice that if you set `maxRetries` to 2 for instance, your operation may be called 3 times: the initial attempt
and 2 retries.

By default the timeout between retries is set to 0 which means that retries will be executed one after another without
any delay. This, however, will result in increased load on the called service and may delay it's recovery.
In order to mitigate this problem it is recommended to execute retries with delays. {@link io.vertx.circuitbreaker.CircuitBreaker#retryPolicy(java.util.function.Function)}
method can be used to specify retry policy. Retry policy is a function which receives retry count as single argument
and returns timeout in milliseconds before retry is executed and allows to implement a more complex policy, e.g.
exponential backoff with jitter. Below is an example of retry timeout which grows linearly with each retry count:

[source,$lang]
----
{@link examples.CircuitBreakerExamples#example8(io.vertx.core.Vertx)}
----

== Callbacks

You can also configures callbacks invoked when the circuit is opened or closed:

[source,$lang]
----
{@link examples.CircuitBreakerExamples#example5(io.vertx.core.Vertx)}
----

You can also be notified when the circuit breaker decides to attempt to reset (half-open state). You can register
such a callback with {@link io.vertx.circuitbreaker.CircuitBreaker#halfOpenHandler(io.vertx.core.Handler)}.

== Event bus notification

Every time the circuit state changes, an event can be published on the event bus.

To enable this feature, set the {@link io.vertx.circuitbreaker.CircuitBreakerOptions#setNotificationAddress(java.lang.String) notification address} to a value that is not `null`:

[source,$lang]
----
{@link examples.CircuitBreakerExamples#enableNotifications}
----

NOTE: When enabled, notifications are, by default, delivered only to local consumers.
If the notification must be sent to all consumers in a cluster, you can change this behavior with {@link io.vertx.circuitbreaker.CircuitBreakerOptions#setNotificationLocalOnly}.

Each event contains a Json Object with:

* `state` : the new circuit breaker state (`OPEN`, `CLOSED`, `HALF_OPEN`)
* `name` : the name of the circuit breaker
* `failures` : the number of failures
* `node` : the identifier of the node (`local` if Vert.x is not running in cluster mode)

== The half-open state

When the circuit is "open", calls to the circuit breaker fail immediately, without any attempt to execute the real
operation. After a suitable amount of time (configured from
{@link io.vertx.circuitbreaker.CircuitBreakerOptions#setResetTimeout(long)}, the circuit breaker decides that the
operation has a chance of succeeding, so it goes into the `half-open` state. In this state, the next call to the
circuit breaker is allowed to execute the dangerous operation. Should the call succeed, the circuit breaker resets
and returns to the `closed` state, ready for more routine operation. If this trial call fails, however, the circuit
breaker returns to the `open` state until another timeout elapses.

== Reported exceptions

The fallback receives a:

* {@link io.vertx.circuitbreaker.OpenCircuitException} when the circuit breaker is opened
* {@link io.vertx.circuitbreaker.TimeoutException} when the operation timed out

== Pushing circuit breaker metrics to the Hystrix Dashboard

Netflix Hystrix comes with a dashboard to present the current state of the circuit breakers. The Vert.x circuit
breakers can publish their metrics in order to be consumed by this Hystrix Dashboard. The Hystrix dashboard requires
a SSE stream sending the metrics. This stream is provided by the
{@link io.vertx.circuitbreaker.HystrixMetricHandler} Vert.x Web Handler:


[source,$lang]
----
{@link examples.CircuitBreakerExamples#example7(io.vertx.core.Vertx)}
----

In the Hystrix Dashboard, configure the stream url like: `http://localhost:8080/metrics`. The dashboard now consumes
the metrics from the Vert.x circuit breakers.

IMPORTANT: The metrics are collected by the Vert.x Web handler using <<Event bus notification>>.
The feature must be enabled and, if you don't use the default notification address, you need to pass it when creating the metrics handler.

[language, java]
----
== Using Netflix Hystrix

https://github.com/Netflix/Hystrix[Hystrix] provides an implementation of the circuit breaker pattern. You can use
Hystrix with Vert.x instead of this circuit breaker or in combination of. This section describes the tricks
to use Hystrix in a vert.x application.

First you would need to add the Hystrix dependency to your classpath or build descriptor. Refer to the Hystrix
page for details. Then, you need to isolate the "protected" call in a `Command`. Once you have your command, you
can execute it:

[source, $lang]
\----
{@link examples.hystrix.HystrixExamples#exampleHystrix1()}
\----

However, the command execution is blocking, so have to call the command execution either in an `executeBlocking`
block or in a worker verticle:

[source, $lang]
\----
{@link examples.hystrix.HystrixExamples#exampleHystrix2(io.vertx.core.Vertx)}
\----

If you use the async support of Hystrix, be careful that callbacks are not called in a vert.x thread and you have
to keep a reference on the context before the execution (with {@link io.vertx.core.Vertx#getOrCreateContext()},
and in the callback, switch back to the event loop using
{@link io.vertx.core.Vertx#runOnContext(io.vertx.core.Handler)}. Without this, you are loosing the Vert.x
concurrency model and have to manage the synchronization and ordering yourself:

[source, $lang]
\----
{@link examples.hystrix.HystrixExamples#exampleHystrix3(io.vertx.core.Vertx)}
\----
----
