SlideShare a Scribd company logo
Micha Kops
www.hascode.com
1
Article on hasCode.com
Circuit Breakers for Java: Failsafe,
Javaslang-CB, Hystrix and Vert.x
Resilient Architecture in Practice
Micha Kops
www.hascode.com
2
Article on hasCode.com
Why?
● Remote-APIs might hang / have latency
issues / throw exceptions / behave
unresponsive
● Our application blocks resources, allocates
memory for threads and bound objects
● Spamming requests to an overloaded remote
API might prevent its recovery
Micha Kops
www.hascode.com
3
Article on hasCode.com
States
Micha Kops
www.hascode.com
4
Article on hasCode.com
Closed-State
● The circuit-breaker executes operations as
usual
● If a failure occurs, the circuit-breaker writes it
down
● If a specified error threshold (number of failures
or frequency of failures) is reached, it trips and
opens the circuit (transitions to the open-state)
Micha Kops
www.hascode.com
5
Article on hasCode.com
Open-State
● Calls to the circuit-breaker in the open state fail
immediately
● No call to the underlying operation is executed
● After a specified timeout is reached, the circuit-
breaker transitions to the half-open state.
Micha Kops
www.hascode.com
6
Article on hasCode.com
Half-Open-State
● In this state, one call is allowed to call the
underlying operation
● If this call fails, the circuit-breaker transitions to
the open-state again until another timeout is
reached
● If it succeeds, the circuit-breaker resets and
transitions to the closed-state.
Micha Kops
www.hascode.com
7
Article on hasCode.com
Implementations for Java
● Failsafe
● Javaslang-Circuitbreaker
● Netflix Hystrix
● Vert.x Circuitbreaker
Micha Kops
www.hascode.com
8
Article on hasCode.com
Failsafe - Example
UnstableApplication app = new UnstableApplication();
CircuitBreaker breaker = new CircuitBreaker().withFailureThreshold(2).withSuccessThreshold(5).withDelay(1,
TimeUnit.SECONDS);
RetryPolicy retryPolicy = new RetryPolicy().withDelay(2, TimeUnit.SECONDS).withMaxDuration(60,
TimeUnit.SECONDS)
.withBackoff(4, 40, TimeUnit.SECONDS);
System.out.printf("circuit-breaker state is: %sn", breaker.getState());
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
try {
String id = Failsafe.with(breaker).with(retryPolicy)
.onFailedAttempt((a, b) -> System.err.printf(
"failed with exception: '%s' at '%s', circuit-breaker state is: '%s'n", b,
ZonedDateTime.now(), breaker.getState()))
.onSuccess((a, b) -> System.out.printf("call succeeded, circuit-breaker state is: '%s'n",
breaker.getState()))
.get(app::generateId);
System.out.printf("FailsafeExample: id '%s' received at '%s'n", id, ZonedDateTime.now());
} catch (CircuitBreakerOpenException e) {
System.out.printf("circuit-breaker is open (state %s), time is '%s'n", breaker.getState(),
ZonedDateTime.now());
}
}
Micha Kops
www.hascode.com
9
Article on hasCode.com
Javaslang ExampleUnstableApplication app = new UnstableApplication();
CircuitBreakerConfig breakerConfig =
CircuitBreakerConfig.custom().ringBufferSizeInClosedState(2)
.ringBufferSizeInHalfOpenState(2).failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(1000)).build();
CircuitBreaker breaker = CircuitBreaker.of("unstableAppBreaker",
breakerConfig);
Try.CheckedSupplier<String> decoratedSupplier =
Decorators.ofCheckedSupplier(app::generateId)
.withCircuitBreaker(breaker).decorate();
System.out.printf("circuit-breaker state is: %sn", breaker.getState());
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
Try<String> result = Try.of(decoratedSupplier)
.onSuccess((a) -> System.out.printf("call succeeded, circuit-
breaker state is: '%s'n",
breaker.getState()))
.onFailure(e -> System.err.printf(
"failed with exception: '%s' at '%s', circuit-breaker
state is: '%s'n", e,
ZonedDateTime.now(), breaker.getState()));
if (!result.isEmpty()) {
System.out.printf("JavaslangExample: id '%s' received at '%s'n",
result.get(), ZonedDateTime.now());
}
}
Micha Kops
www.hascode.com
10
Article on hasCode.com
Hystrix Example (I)
class IdGeneratingCommand extends HystrixObservableCommand<String> {
private final UnstableApplication app;
public IdGeneratingCommand(HystrixObservableCommand.Setter setter,
UnstableApplication app) {
super(setter);
this.app = app;
}
@Override
protected Observable<String> construct() {
return Observable.create(observer -> {
try {
if (!observer.isUnsubscribed()) {
observer.onNext(app.generateId());
observer.onCompleted();
}
} catch (SampleException e) {
observer.onError(e);
}
});
}
};
Micha Kops
www.hascode.com
11
Article on hasCode.com
Hystrix Example (II)UnstableApplication app = new UnstableApplication();
HystrixObservableCommand.Setter setter = HystrixObservableCommand.Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("unstableAppCmdGroup"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withCircuitBreakerEnabled(t
rue)
.withCircuitBreakerErrorThresholdPercentage(50)
.withCircuitBreakerSleepWindowInMilliseconds(1000).withCircuitBreakerRequestVolumeThreshold
(1));
for (int i = 0; i < 10; i++) {
CountDownLatch l = new CountDownLatch(1);
IdGeneratingCommand cmd = new IdGeneratingCommand(setter, app);
final HealthCounts healthCounts = cmd.getMetrics().getHealthCounts();
System.out.printf("circuit-breaker state is open: %s, %d errors of %d
requestsn",
cmd.isCircuitBreakerOpen(), healthCounts.getErrorCount(),
healthCounts.getTotalRequests());
Observable<String> observable = cmd.observe();
observable.subscribe(s -> {
System.out.printf("HystrixExample: id '%s' received at '%s'n", s,
ZonedDateTime.now());
} , t -> {
System.err.printf("HystrixExample: error %s, circuit-breaker state is open:
%sn", t,
cmd.isCircuitBreakerOpen());
} , () -> {
l.countDown();
});
l.await(4, TimeUnit.SECONDS);
}
Micha Kops
www.hascode.com
12
Article on hasCode.com
Vert.x ExampleUnstableApplication app = new UnstableApplication();
Vertx vertx = Vertx.vertx();
CircuitBreaker breaker = CircuitBreaker
.create("unstableAppBreaker", vertx,
new
CircuitBreakerOptions().setMaxFailures(2).setTimeout(2000).setFallbackOnFailure(true)
.setResetTimeout(2000))
.openHandler(h -> System.err.println("circuit-breaker opened"))
.closeHandler(h -> System.out.println("circuit-breaker closed"))
.halfOpenHandler(h -> System.err.println("circuit-breaker half-opened"));
System.out.printf("circuit-breaker state is: %sn", breaker.state());
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
breaker.<String> execute(future -> {
try {
final String id = app.generateId();
future.complete(id);
} catch (SampleException e) {
future.fail(e);
}
if (future.failed()) {
System.err.printf("failed with exception: '%s' at '%s', circuit-breaker
state is: '%s'n",
future.cause(), ZonedDateTime.now(), breaker.state());
}
}).setHandler(id -> {
if (id.succeeded())
System.out.printf("VertxExample: id '%s' received at '%s'n", id,
ZonedDateTime.now());
});
}
vertx.close();
Micha Kops
www.hascode.com
13
Article on hasCode.com
The End
Thanks for your audience

More Related Content

PPT
Test innode
PDF
Hunting for malicious modules in npm - NodeSummit
PPT
Find bottleneck and tuning in Java Application
PDF
Real World Mocking In Swift
PDF
Robust and Scalable Concurrent Programming: Lesson from the Trenches
PDF
Checking Bitcoin
PDF
Errors detected in C++Builder
PPTX
Security testing of YUI powered applications
Test innode
Hunting for malicious modules in npm - NodeSummit
Find bottleneck and tuning in Java Application
Real World Mocking In Swift
Robust and Scalable Concurrent Programming: Lesson from the Trenches
Checking Bitcoin
Errors detected in C++Builder
Security testing of YUI powered applications

What's hot (17)

PDF
Thread dumps
PPTX
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
ODP
Test antipatterns
PPTX
SAST and Application Security: how to fight vulnerabilities in the code
PDF
Ajax World Comet Talk
PDF
Pre New Year Check of PostgreSQL
PPT
TestNG & JPA Validation
PDF
So You Want To Write Your Own Benchmark
PDF
Verifikation - Metoder og Libraries
PDF
Whatever it takes - Fixing SQLIA and XSS in the process
PDF
Unit Testing: Special Cases
PDF
performance optimization: UI
PDF
DataStax: Making Cassandra Fail (for effective testing)
PPTX
Java concurrency in practice
PPT
Introduction to Drools
PDF
Non-blocking synchronization — what is it and why we (don't?) need it
PDF
Zuul's Journey to Non-Blocking
Thread dumps
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
Test antipatterns
SAST and Application Security: how to fight vulnerabilities in the code
Ajax World Comet Talk
Pre New Year Check of PostgreSQL
TestNG & JPA Validation
So You Want To Write Your Own Benchmark
Verifikation - Metoder og Libraries
Whatever it takes - Fixing SQLIA and XSS in the process
Unit Testing: Special Cases
performance optimization: UI
DataStax: Making Cassandra Fail (for effective testing)
Java concurrency in practice
Introduction to Drools
Non-blocking synchronization — what is it and why we (don't?) need it
Zuul's Journey to Non-Blocking
Ad

Similar to Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Vert.x (20)

PPTX
자바 성능 강의
PDF
Jvm operation casual talks
PPT
Java util concurrent
PDF
Introduction of failsafe
PPTX
Concurrency in Eclipse: Best Practices and Gotchas
PDF
Native Java with GraalVM
KEY
Curator intro
PPTX
Introduction to aop
PPT
Server side JavaScript: going all the way
PDF
Towards a Scalable Non-Blocking Coding Style
PDF
Oracle Drivers configuration for High Availability
PPTX
Java Concurrency and Asynchronous
PDF
Cache is King: Get the Most Bang for Your Buck From Ruby
PPT
JS everywhere 2011
PDF
[CB20] Vulnerabilities of Machine Learning Infrastructure by Sergey Gordeychik
PDF
ChatOps with Icinga and StackStorm
PPT
bluespec talk
PDF
手把手教你如何串接 Log 到各種網路服務
PDF
Spark 2.x Troubleshooting Guide
 
PPTX
Solving anything in VCL
자바 성능 강의
Jvm operation casual talks
Java util concurrent
Introduction of failsafe
Concurrency in Eclipse: Best Practices and Gotchas
Native Java with GraalVM
Curator intro
Introduction to aop
Server side JavaScript: going all the way
Towards a Scalable Non-Blocking Coding Style
Oracle Drivers configuration for High Availability
Java Concurrency and Asynchronous
Cache is King: Get the Most Bang for Your Buck From Ruby
JS everywhere 2011
[CB20] Vulnerabilities of Machine Learning Infrastructure by Sergey Gordeychik
ChatOps with Icinga and StackStorm
bluespec talk
手把手教你如何串接 Log 到各種網路服務
Spark 2.x Troubleshooting Guide
 
Solving anything in VCL
Ad

Recently uploaded (20)

PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Transform Your Business with a Software ERP System
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
System and Network Administraation Chapter 3
PDF
How Creative Agencies Leverage Project Management Software.pdf
PDF
Digital Strategies for Manufacturing Companies
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
history of c programming in notes for students .pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Understanding Forklifts - TECH EHS Solution
Operating system designcfffgfgggggggvggggggggg
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Wondershare Filmora 15 Crack With Activation Key [2025
VVF-Customer-Presentation2025-Ver1.9.pptx
Transform Your Business with a Software ERP System
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
System and Network Administraation Chapter 3
How Creative Agencies Leverage Project Management Software.pdf
Digital Strategies for Manufacturing Companies
CHAPTER 2 - PM Management and IT Context
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Which alternative to Crystal Reports is best for small or large businesses.pdf
PTS Company Brochure 2025 (1).pdf.......
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
history of c programming in notes for students .pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Understanding Forklifts - TECH EHS Solution

Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Vert.x

  • 1. Micha Kops www.hascode.com 1 Article on hasCode.com Circuit Breakers for Java: Failsafe, Javaslang-CB, Hystrix and Vert.x Resilient Architecture in Practice
  • 2. Micha Kops www.hascode.com 2 Article on hasCode.com Why? ● Remote-APIs might hang / have latency issues / throw exceptions / behave unresponsive ● Our application blocks resources, allocates memory for threads and bound objects ● Spamming requests to an overloaded remote API might prevent its recovery
  • 4. Micha Kops www.hascode.com 4 Article on hasCode.com Closed-State ● The circuit-breaker executes operations as usual ● If a failure occurs, the circuit-breaker writes it down ● If a specified error threshold (number of failures or frequency of failures) is reached, it trips and opens the circuit (transitions to the open-state)
  • 5. Micha Kops www.hascode.com 5 Article on hasCode.com Open-State ● Calls to the circuit-breaker in the open state fail immediately ● No call to the underlying operation is executed ● After a specified timeout is reached, the circuit- breaker transitions to the half-open state.
  • 6. Micha Kops www.hascode.com 6 Article on hasCode.com Half-Open-State ● In this state, one call is allowed to call the underlying operation ● If this call fails, the circuit-breaker transitions to the open-state again until another timeout is reached ● If it succeeds, the circuit-breaker resets and transitions to the closed-state.
  • 7. Micha Kops www.hascode.com 7 Article on hasCode.com Implementations for Java ● Failsafe ● Javaslang-Circuitbreaker ● Netflix Hystrix ● Vert.x Circuitbreaker
  • 8. Micha Kops www.hascode.com 8 Article on hasCode.com Failsafe - Example UnstableApplication app = new UnstableApplication(); CircuitBreaker breaker = new CircuitBreaker().withFailureThreshold(2).withSuccessThreshold(5).withDelay(1, TimeUnit.SECONDS); RetryPolicy retryPolicy = new RetryPolicy().withDelay(2, TimeUnit.SECONDS).withMaxDuration(60, TimeUnit.SECONDS) .withBackoff(4, 40, TimeUnit.SECONDS); System.out.printf("circuit-breaker state is: %sn", breaker.getState()); for (int i = 0; i < 10; i++) { Thread.sleep(1000); try { String id = Failsafe.with(breaker).with(retryPolicy) .onFailedAttempt((a, b) -> System.err.printf( "failed with exception: '%s' at '%s', circuit-breaker state is: '%s'n", b, ZonedDateTime.now(), breaker.getState())) .onSuccess((a, b) -> System.out.printf("call succeeded, circuit-breaker state is: '%s'n", breaker.getState())) .get(app::generateId); System.out.printf("FailsafeExample: id '%s' received at '%s'n", id, ZonedDateTime.now()); } catch (CircuitBreakerOpenException e) { System.out.printf("circuit-breaker is open (state %s), time is '%s'n", breaker.getState(), ZonedDateTime.now()); } }
  • 9. Micha Kops www.hascode.com 9 Article on hasCode.com Javaslang ExampleUnstableApplication app = new UnstableApplication(); CircuitBreakerConfig breakerConfig = CircuitBreakerConfig.custom().ringBufferSizeInClosedState(2) .ringBufferSizeInHalfOpenState(2).failureRateThreshold(50) .waitDurationInOpenState(Duration.ofMillis(1000)).build(); CircuitBreaker breaker = CircuitBreaker.of("unstableAppBreaker", breakerConfig); Try.CheckedSupplier<String> decoratedSupplier = Decorators.ofCheckedSupplier(app::generateId) .withCircuitBreaker(breaker).decorate(); System.out.printf("circuit-breaker state is: %sn", breaker.getState()); for (int i = 0; i < 10; i++) { Thread.sleep(1000); Try<String> result = Try.of(decoratedSupplier) .onSuccess((a) -> System.out.printf("call succeeded, circuit- breaker state is: '%s'n", breaker.getState())) .onFailure(e -> System.err.printf( "failed with exception: '%s' at '%s', circuit-breaker state is: '%s'n", e, ZonedDateTime.now(), breaker.getState())); if (!result.isEmpty()) { System.out.printf("JavaslangExample: id '%s' received at '%s'n", result.get(), ZonedDateTime.now()); } }
  • 10. Micha Kops www.hascode.com 10 Article on hasCode.com Hystrix Example (I) class IdGeneratingCommand extends HystrixObservableCommand<String> { private final UnstableApplication app; public IdGeneratingCommand(HystrixObservableCommand.Setter setter, UnstableApplication app) { super(setter); this.app = app; } @Override protected Observable<String> construct() { return Observable.create(observer -> { try { if (!observer.isUnsubscribed()) { observer.onNext(app.generateId()); observer.onCompleted(); } } catch (SampleException e) { observer.onError(e); } }); } };
  • 11. Micha Kops www.hascode.com 11 Article on hasCode.com Hystrix Example (II)UnstableApplication app = new UnstableApplication(); HystrixObservableCommand.Setter setter = HystrixObservableCommand.Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey("unstableAppCmdGroup")) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withCircuitBreakerEnabled(t rue) .withCircuitBreakerErrorThresholdPercentage(50) .withCircuitBreakerSleepWindowInMilliseconds(1000).withCircuitBreakerRequestVolumeThreshold (1)); for (int i = 0; i < 10; i++) { CountDownLatch l = new CountDownLatch(1); IdGeneratingCommand cmd = new IdGeneratingCommand(setter, app); final HealthCounts healthCounts = cmd.getMetrics().getHealthCounts(); System.out.printf("circuit-breaker state is open: %s, %d errors of %d requestsn", cmd.isCircuitBreakerOpen(), healthCounts.getErrorCount(), healthCounts.getTotalRequests()); Observable<String> observable = cmd.observe(); observable.subscribe(s -> { System.out.printf("HystrixExample: id '%s' received at '%s'n", s, ZonedDateTime.now()); } , t -> { System.err.printf("HystrixExample: error %s, circuit-breaker state is open: %sn", t, cmd.isCircuitBreakerOpen()); } , () -> { l.countDown(); }); l.await(4, TimeUnit.SECONDS); }
  • 12. Micha Kops www.hascode.com 12 Article on hasCode.com Vert.x ExampleUnstableApplication app = new UnstableApplication(); Vertx vertx = Vertx.vertx(); CircuitBreaker breaker = CircuitBreaker .create("unstableAppBreaker", vertx, new CircuitBreakerOptions().setMaxFailures(2).setTimeout(2000).setFallbackOnFailure(true) .setResetTimeout(2000)) .openHandler(h -> System.err.println("circuit-breaker opened")) .closeHandler(h -> System.out.println("circuit-breaker closed")) .halfOpenHandler(h -> System.err.println("circuit-breaker half-opened")); System.out.printf("circuit-breaker state is: %sn", breaker.state()); for (int i = 0; i < 10; i++) { Thread.sleep(1000); breaker.<String> execute(future -> { try { final String id = app.generateId(); future.complete(id); } catch (SampleException e) { future.fail(e); } if (future.failed()) { System.err.printf("failed with exception: '%s' at '%s', circuit-breaker state is: '%s'n", future.cause(), ZonedDateTime.now(), breaker.state()); } }).setHandler(id -> { if (id.succeeded()) System.out.printf("VertxExample: id '%s' received at '%s'n", id, ZonedDateTime.now()); }); } vertx.close();
  • 13. Micha Kops www.hascode.com 13 Article on hasCode.com The End Thanks for your audience