Hystrix: Latency and Fault Tolerance for Distributed Systems



com.netflix.hystrix
Class HystrixCommand<R>

java.lang.Object
  extended by com.netflix.hystrix.HystrixCommand<R>
Type Parameters:
R - the return type
All Implemented Interfaces:
HystrixExecutable<R>

@ThreadSafe
public abstract class HystrixCommand<R>
extends java.lang.Object
implements HystrixExecutable<R>

Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality.


Nested Class Summary
static class HystrixCommand.Setter
          Fluent interface for arguments to the HystrixCommand constructor.
 
Constructor Summary
protected HystrixCommand(HystrixCommand.Setter setter)
          Construct a HystrixCommand with defined HystrixCommand.Setter that allows injecting property and strategy overrides and other optional arguments.
protected HystrixCommand(HystrixCommandGroupKey group)
          Construct a HystrixCommand with defined HystrixCommandGroupKey.
 
Method Summary
protected  java.lang.RuntimeException decomposeException(java.lang.Exception e)
          Take an Exception and determine whether to throw it, its cause or a new HystrixRuntimeException.
 R execute()
          Used for synchronous execution of command.
protected  java.lang.String getCacheKey()
          Key to be used for request caching.
 HystrixCommandGroupKey getCommandGroup()
           
 HystrixCommandKey getCommandKey()
           
 java.util.List<HystrixEventType> getExecutionEvents()
          List of HystrixCommandEventType enums representing events that occurred during execution.
 int getExecutionTimeInMilliseconds()
          The execution time of this command instance in milliseconds, or -1 if not executed.
 java.lang.Throwable getFailedExecutionException()
          Get the Throwable/Exception thrown that caused the failure.
protected  R getFallback()
          If HystrixCommand.execute() or HystrixCommand.queue() fails in any way then this method will be invoked to provide an opportunity to return a fallback response.
 HystrixCommandMetrics getMetrics()
          The HystrixCommandMetrics associated with this HystrixCommand instance.
 HystrixCommandProperties getProperties()
          The HystrixCommandProperties associated with this HystrixCommand instance.
 HystrixThreadPoolKey getThreadPoolKey()
           
 boolean isCircuitBreakerOpen()
          Whether the 'circuit-breaker' is open meaning that execute() will immediately return the getFallback() response and not attempt a HystrixCommand execution.
 boolean isExecutedInThread()
          Whether the execution occurred in a separate thread.
 boolean isExecutionComplete()
          If this command has completed execution either successfully, via fallback or failure.
 boolean isFailedExecution()
          Whether the run() resulted in a failure (exception).
 boolean isResponseFromCache()
          Whether the response is from cache and run() was not invoked.
 boolean isResponseFromFallback()
          Whether the response received from was the result of some type of failure and getFallback() being called.
 boolean isResponseRejected()
          Whether the response received was a fallback as result of being rejected (from thread-pool or semaphore) and getFallback() being called.
 boolean isResponseShortCircuited()
          Whether the response received was a fallback as result of being short-circuited (meaning isCircuitBreakerOpen() == true) and getFallback() being called.
 boolean isResponseTimedOut()
          Whether the response received was the result of a timeout and getFallback() being called.
 boolean isSuccessfulExecution()
          Whether the response was returned successfully either by executing run() or from cache.
 rx.Observable<R> observe()
          Used for asynchronous execution of command with a callback by subscribing to the Observable.
 java.util.concurrent.Future<R> queue()
          Used for asynchronous execution of command.
protected abstract  R run()
          Implement this method with code to be executed when HystrixCommand.execute() or HystrixCommand.queue() are invoked.
 rx.Observable<R> toObservable()
          A lazy Observable that will execute the command when subscribed to.
 rx.Observable<R> toObservable(rx.Scheduler observeOn)
          A lazy Observable that will execute the command when subscribed to.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

HystrixCommand

protected HystrixCommand(HystrixCommandGroupKey group)
Construct a HystrixCommand with defined HystrixCommandGroupKey.

The HystrixCommandKey will be derived from the implementing class name.

Parameters:
group - HystrixCommandGroupKey used to group together multiple HystrixCommand objects.

The HystrixCommandGroupKey is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, common business purpose etc.


HystrixCommand

protected HystrixCommand(HystrixCommand.Setter setter)
Construct a HystrixCommand with defined HystrixCommand.Setter that allows injecting property and strategy overrides and other optional arguments.

NOTE: The HystrixCommandKey is used to associate a HystrixCommand with HystrixCircuitBreaker, HystrixCommandMetrics and other objects.

Do not create multiple HystrixCommand implementations with the same HystrixCommandKey but different injected default properties as the first instantiated will win.

Properties passed in via HystrixCommand.Setter.andCommandPropertiesDefaults(com.netflix.hystrix.HystrixCommandProperties.Setter) or HystrixCommand.Setter.andThreadPoolPropertiesDefaults(com.netflix.hystrix.HystrixThreadPoolProperties.Setter) are cached for the given HystrixCommandKey for the life of the JVM or until Hystrix.reset() is called. Dynamic properties allow runtime changes. Read more on the Hystrix Wiki.

Parameters:
setter - Fluent interface for constructor arguments
Method Detail

run

protected abstract R run()
                  throws java.lang.Exception
Implement this method with code to be executed when HystrixCommand.execute() or HystrixCommand.queue() are invoked.

Returns:
R response type
Throws:
java.lang.Exception - if command execution fails

getFallback

protected R getFallback()
If HystrixCommand.execute() or HystrixCommand.queue() fails in any way then this method will be invoked to provide an opportunity to return a fallback response.

This should do work that does not require network transport to produce.

In other words, this should be a static or cached result that can immediately be returned upon failure.

If network traffic is wanted for fallback (such as going to MemCache) then the fallback implementation should invoke another HystrixCommand instance that protects against that network access and possibly has another level of fallback that does not involve network access.

DEFAULT BEHAVIOR: It throws UnsupportedOperationException.

Returns:
R or throw UnsupportedOperationException if not implemented

getCommandGroup

public HystrixCommandGroupKey getCommandGroup()
Returns:
HystrixCommandGroupKey used to group together multiple HystrixCommand objects.

The HystrixCommandGroupKey is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace with, common business purpose etc.


getCommandKey

public HystrixCommandKey getCommandKey()
Returns:
HystrixCommandKey identifying this command instance for statistics, circuit-breaker, properties, etc.

getThreadPoolKey

public HystrixThreadPoolKey getThreadPoolKey()
Returns:
HystrixThreadPoolKey identifying which thread-pool this command uses (when configured to run on separate threads via HystrixCommandProperties.executionIsolationStrategy()).

getMetrics

public HystrixCommandMetrics getMetrics()
The HystrixCommandMetrics associated with this HystrixCommand instance.

Returns:
HystrixCommandMetrics

getProperties

public HystrixCommandProperties getProperties()
The HystrixCommandProperties associated with this HystrixCommand instance.

Returns:
HystrixCommandProperties

execute

public R execute()
Used for synchronous execution of command.

Specified by:
execute in interface HystrixExecutable<R>
Returns:
R Result of HystrixCommand.run() execution or a fallback from HystrixCommand.getFallback() if the command fails for any reason.
Throws:
HystrixRuntimeException - if a failure occurs and a fallback cannot be retrieved
HystrixBadRequestException - if invalid arguments or state were used representing a user failure, not a system failure
java.lang.IllegalStateException - if invoked more than once

queue

public java.util.concurrent.Future<R> queue()
Used for asynchronous execution of command.

This will queue up the command on the thread pool and return an Future to get the result once it completes.

NOTE: If configured to not run in a separate thread, this will have the same effect as HystrixCommand.execute() and will block.

We don't throw an exception but just flip to synchronous execution so code doesn't need to change in order to switch a command from running on a separate thread to the calling thread.

Specified by:
queue in interface HystrixExecutable<R>
Returns:
Future<R> Result of HystrixCommand.run() execution or a fallback from HystrixCommand.getFallback() if the command fails for any reason.
Throws:
HystrixRuntimeException - if a fallback does not exist

  • via Future.get() in Throwable.getCause() if a failure occurs
  • or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)
HystrixBadRequestException - via Future.get() in Throwable.getCause() if invalid arguments or state were used representing a user failure, not a system failure
java.lang.IllegalStateException - if invoked more than once

decomposeException

protected java.lang.RuntimeException decomposeException(java.lang.Exception e)
Take an Exception and determine whether to throw it, its cause or a new HystrixRuntimeException.

This will only throw an HystrixRuntimeException, HystrixBadRequestException or IllegalStateException

Parameters:
e -
Returns:
HystrixRuntimeException, HystrixBadRequestException or IllegalStateException

observe

public rx.Observable<R> observe()
Used for asynchronous execution of command with a callback by subscribing to the Observable.

This eagerly starts execution of the command the same as HystrixCommand.queue() and HystrixCommand.execute(). A lazy Observable can be obtained from HystrixCommand.toObservable().

Callback Scheduling

Use HystrixCommand.toObservable(rx.Scheduler) to schedule the callback differently.

See https://github.com/Netflix/RxJava/wiki for more information.

Specified by:
observe in interface HystrixExecutable<R>
Returns:
Observable<R> that executes and calls back with the result of HystrixCommand.run() execution or a fallback from HystrixCommand.getFallback() if the command fails for any reason.
Throws:
HystrixRuntimeException - if a fallback does not exist

  • via Observer#onError if a failure occurs
  • or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)
HystrixBadRequestException - via Observer#onError if invalid arguments or state were used representing a user failure, not a system failure
java.lang.IllegalStateException - if invoked more than once

toObservable

public rx.Observable<R> toObservable()
A lazy Observable that will execute the command when subscribed to.

Callback Scheduling

See https://github.com/Netflix/RxJava/wiki for more information.

Returns:
Observable<R> that lazily executes and calls back with the result of HystrixCommand.run() execution or a fallback from HystrixCommand.getFallback() if the command fails for any reason.
Throws:
HystrixRuntimeException - if a fallback does not exist

  • via Observer#onError if a failure occurs
  • or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)
HystrixBadRequestException - via Observer#onError if invalid arguments or state were used representing a user failure, not a system failure
java.lang.IllegalStateException - if invoked more than once

toObservable

public rx.Observable<R> toObservable(rx.Scheduler observeOn)
A lazy Observable that will execute the command when subscribed to.

See https://github.com/Netflix/RxJava/wiki for more information.

Parameters:
observeOn - The Scheduler to execute callbacks on.
Returns:
Observable<R> that lazily executes and calls back with the result of HystrixCommand.run() execution or a fallback from HystrixCommand.getFallback() if the command fails for any reason.
Throws:
HystrixRuntimeException - if a fallback does not exist

  • via Observer#onError if a failure occurs
  • or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)
HystrixBadRequestException - via Observer#onError if invalid arguments or state were used representing a user failure, not a system failure
java.lang.IllegalStateException - if invoked more than once

isCircuitBreakerOpen

public boolean isCircuitBreakerOpen()
Whether the 'circuit-breaker' is open meaning that execute() will immediately return the getFallback() response and not attempt a HystrixCommand execution.

Returns:
boolean

isExecutionComplete

public boolean isExecutionComplete()
If this command has completed execution either successfully, via fallback or failure.

Returns:
boolean

isExecutedInThread

public boolean isExecutedInThread()
Whether the execution occurred in a separate thread.

This should be called only once execute()/queue()/fireOrForget() are called otherwise it will always return false.

This specifies if a thread execution actually occurred, not just if it is configured to be executed in a thread.

Returns:
boolean

isSuccessfulExecution

public boolean isSuccessfulExecution()
Whether the response was returned successfully either by executing run() or from cache.

Returns:
boolean

isFailedExecution

public boolean isFailedExecution()
Whether the run() resulted in a failure (exception).

Returns:
boolean

getFailedExecutionException

public java.lang.Throwable getFailedExecutionException()
Get the Throwable/Exception thrown that caused the failure.

If isFailedExecution() == true then this would represent the Exception thrown by the run() method.

If isFailedExecution() == false then this would return null.

Returns:
Throwable or null

isResponseFromFallback

public boolean isResponseFromFallback()
Whether the response received from was the result of some type of failure and getFallback() being called.

Returns:
boolean

isResponseTimedOut

public boolean isResponseTimedOut()
Whether the response received was the result of a timeout and getFallback() being called.

Returns:
boolean

isResponseShortCircuited

public boolean isResponseShortCircuited()
Whether the response received was a fallback as result of being short-circuited (meaning isCircuitBreakerOpen() == true) and getFallback() being called.

Returns:
boolean

isResponseFromCache

public boolean isResponseFromCache()
Whether the response is from cache and run() was not invoked.

Returns:
boolean

isResponseRejected

public boolean isResponseRejected()
Whether the response received was a fallback as result of being rejected (from thread-pool or semaphore) and getFallback() being called.

Returns:
boolean

getExecutionEvents

public java.util.List<HystrixEventType> getExecutionEvents()
List of HystrixCommandEventType enums representing events that occurred during execution.

Examples of events are SUCCESS, FAILURE, TIMEOUT, and SHORT_CIRCUITED

Returns:
List<HystrixEventType>

getExecutionTimeInMilliseconds

public int getExecutionTimeInMilliseconds()
The execution time of this command instance in milliseconds, or -1 if not executed.

Returns:
int

getCacheKey

protected java.lang.String getCacheKey()
Key to be used for request caching.

By default this returns null which means "do not cache".

To enable caching override this method and return a string key uniquely representing the state of a command instance.

If multiple command instances in the same request scope match keys then only the first will be executed and all others returned from cache.

Returns:
cacheKey