SlideShare une entreprise Scribd logo
1  sur  13
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

Contenu connexe

Tendances

Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafMasatoshi Tada
 
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...OWASP
 
Test antipatterns
Test antipatternsTest antipatterns
Test antipatternsJiří Kiml
 
SAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeSAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeAndrey Karpov
 
Ajax World Comet Talk
Ajax World Comet TalkAjax World Comet Talk
Ajax World Comet Talkrajivmordani
 
Pre New Year Check of PostgreSQL
Pre New Year Check of PostgreSQLPre New Year Check of PostgreSQL
Pre New Year Check of PostgreSQLAndrey Karpov
 
TestNG & JPA Validation
TestNG & JPA ValidationTestNG & JPA Validation
TestNG & JPA ValidationJiří Kiml
 
So You Want To Write Your Own Benchmark
So You Want To Write Your Own BenchmarkSo You Want To Write Your Own Benchmark
So You Want To Write Your Own BenchmarkDror Bereznitsky
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processguest3379bd
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special CasesCiklum Ukraine
 
performance optimization: UI
performance optimization: UIperformance optimization: UI
performance optimization: UI晓东 杜
 
DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)DataStax Academy
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 
Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Droolsgiurca
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itAlexey Fyodorov
 
Zuul's Journey to Non-Blocking
Zuul's Journey to Non-BlockingZuul's Journey to Non-Blocking
Zuul's Journey to Non-BlockingArthur Gonigberg
 

Tendances (18)

Thread dumps
Thread dumpsThread dumps
Thread dumps
 
Getting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with ThymeleafGetting start Java EE Action-Based MVC with Thymeleaf
Getting start Java EE Action-Based MVC with Thymeleaf
 
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
 
Test antipatterns
Test antipatternsTest antipatterns
Test antipatterns
 
SAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the codeSAST and Application Security: how to fight vulnerabilities in the code
SAST and Application Security: how to fight vulnerabilities in the code
 
Ajax World Comet Talk
Ajax World Comet TalkAjax World Comet Talk
Ajax World Comet Talk
 
Pre New Year Check of PostgreSQL
Pre New Year Check of PostgreSQLPre New Year Check of PostgreSQL
Pre New Year Check of PostgreSQL
 
TestNG & JPA Validation
TestNG & JPA ValidationTestNG & JPA Validation
TestNG & JPA Validation
 
So You Want To Write Your Own Benchmark
So You Want To Write Your Own BenchmarkSo You Want To Write Your Own Benchmark
So You Want To Write Your Own Benchmark
 
Verifikation - Metoder og Libraries
Verifikation - Metoder og LibrariesVerifikation - Metoder og Libraries
Verifikation - Metoder og Libraries
 
Whatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the processWhatever it takes - Fixing SQLIA and XSS in the process
Whatever it takes - Fixing SQLIA and XSS in the process
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
performance optimization: UI
performance optimization: UIperformance optimization: UI
performance optimization: UI
 
DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Introduction to Drools
Introduction to DroolsIntroduction to Drools
Introduction to Drools
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need it
 
Zuul's Journey to Non-Blocking
Zuul's Journey to Non-BlockingZuul's Journey to Non-Blocking
Zuul's Journey to Non-Blocking
 

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

자바 성능 강의
자바 성능 강의자바 성능 강의
자바 성능 강의Terry Cho
 
Jvm operation casual talks
Jvm operation casual talksJvm operation casual talks
Jvm operation casual talksYusaku Watanabe
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
Introduction of failsafe
Introduction of failsafeIntroduction of failsafe
Introduction of failsafeSunghyouk Bae
 
Concurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and GotchasConcurrency in Eclipse: Best Practices and Gotchas
Concurrency in Eclipse: Best Practices and Gotchasamccullo
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVMSylvain Wallez
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aopDror Helper
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Towards a Scalable Non-Blocking Coding Style
Towards a Scalable Non-Blocking Coding StyleTowards a Scalable Non-Blocking Coding Style
Towards a Scalable Non-Blocking Coding StyleAzul Systems Inc.
 
Oracle Drivers configuration for High Availability
Oracle Drivers configuration for High AvailabilityOracle Drivers configuration for High Availability
Oracle Drivers configuration for High AvailabilityLudovico Caldara
 
Java Concurrency and Asynchronous
Java Concurrency and AsynchronousJava Concurrency and Asynchronous
Java Concurrency and AsynchronousLifan Yang
 
Cache is King: Get the Most Bang for Your Buck From Ruby
Cache is King: Get the Most Bang for Your Buck From RubyCache is King: Get the Most Bang for Your Buck From Ruby
Cache is King: Get the Most Bang for Your Buck From RubyMolly Struve
 
[CB20] Vulnerabilities of Machine Learning Infrastructure by Sergey Gordeychik
[CB20] Vulnerabilities of Machine Learning Infrastructure by Sergey Gordeychik[CB20] Vulnerabilities of Machine Learning Infrastructure by Sergey Gordeychik
[CB20] Vulnerabilities of Machine Learning Infrastructure by Sergey GordeychikCODE BLUE
 
ChatOps with Icinga and StackStorm
ChatOps with Icinga and StackStormChatOps with Icinga and StackStorm
ChatOps with Icinga and StackStormIcinga
 
手把手教你如何串接 Log 到各種網路服務
手把手教你如何串接 Log 到各種網路服務手把手教你如何串接 Log 到各種網路服務
手把手教你如何串接 Log 到各種網路服務Mu Chun Wang
 
Spark 2.x Troubleshooting Guide
Spark 2.x Troubleshooting GuideSpark 2.x Troubleshooting Guide
Spark 2.x Troubleshooting GuideIBM
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCLFastly
 

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

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

Dernier

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 

Dernier (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

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