SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
Introduction of Failsafe
debop@coupang.com 2019.03.14
Agenda
• MSA Use cases
• What is Failsafe
• Usage in Coupang
• How to work
• Main Features
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Async
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Async
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Async
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Async
Fail? -> Retry? Fallback?
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Async
Fail? -> Retry? Fallback?
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Async
Fail? -> Retry? Fallback?
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
MSA - Key features
Service A
Service B
Service C
Our Service
Event Loop
Asynchronous
Non-Blocking
Async
Dashboard
Fail? -> Retry? Fallback?
Non-Blocking
CompletableFuture ?
Observable (RxJava) ?
Cache
Failsafe
• Latency and FaultTolerance for Distributed Systems
• Realtime Operations
• Synchronous & Asynchronous
• Resiliency - Fallback, Retry, Circuit Breaker
Failsafe vs Hystrix
• Executable logic can be passed to Failsafe as simple lambda expression
• Failsafe support retry
• Asynchronous execution in Failsafe are performed on a user suppliedThreadPool /
Scheduler
• Asynchronous execution can be observed via event listener api and return Future
• Hystrix circuit breakers are time sensitive, Failsafe use last executions, regardless of
when they took place.
• Failsafe circuit breakers support execution timeouts and configurable support
thresholds. Hystrix only performs a single execution when in half-open state
• Failsafe circuit breakers can be shared across different executions against the same
component, so that if a failure occurs, all executions against that component will be
halted by the circuit breaker.
Usage in Coupang
• Used in Connect SDK
• Main Goals
• Retry policy (backoff, jitters)
• Circuit breaker (Resiliency)
How to work
Circuit Breaker Pattern
Closed Open
Half
Open
trip breaker
If threshold
reached
Call pass through
count fail/success
reset breakers
trip breaker
try reset
after timeout is
reached
calls pass through
on success

reset breaker
on success

reset breaker
Closed-State
• The circuit breaker executes operations as usual
• If a failure occurs, the circuit breaker write it down
• If a specified error threshold (number of failures or frequency
of failures) is reached, it trips and opens the circuit breaker
(transitions to the open-state)
Open-State
• Calls to the circuit breaker in the open state fail immediately
• No call to the underlying operations is executed
• After a specified timeout is reached, the circuit breaker
transitions to the half-open state.
Half-Open-State
• In this state, one call is allowed to call the underlying operation
• If this call failed, the circuit-breaker transitions to the open-
state again until another timeout is reached
• If it succeeded, the circuit-breaker resets and transitions to
the closed-state.
Hystrix Flow Chart
Hystrix Flow Chart
Sync
Hystrix Flow Chart
AsyncSync
Hystrix Flow Chart
ReactiveAsyncSync
Hystrix Flow Chart
Cache
ReactiveAsyncSync
Hystrix Flow Chart
Cache
ReactiveAsyncSync
Circuit Breaker
Hystrix Flow Chart
Cache
ReactiveAsyncSync
Circuit Breaker
Thread Pool
Hystrix Flow Chart
Cache
ReactiveAsyncSync
Circuit Breaker
Fallback
Thread Pool
Main Features
Failsafe
Main Features
• Retry
• Circuit breaker
• Fallback
Retry
RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
.handle(ConnectException.class) // handle specific exception
.withDelay(Duration.ofSeconds(1)) // retry with delay
.withMaxRetries(3); // maximum retry count
// Run with retries
Failsafe.with(retryPolicy).run(() -> connect());
// Get with retries
Connection connection = Failsafe.with(retryPolicy).get(() -> connect());
// Run with retries asynchronously
CompletableFuture<Void> future = Failsafe.with(retryPolicy).runAsync(() -> connect());
// Get with retries asynchronously
CompletableFuture<Connection> future = Failsafe.with(retryPolicy).getAsync(() -> connect());
Retry policies
retryPolicy.withMaxAttempts(3);
// delay between attempts
retryPolicy.withDelay(Duration.ofSeconds(1));
// delay with back off exponentially
retryPolicy.withBackoff(1, 30, ChronoUnit.SECONDS);
// random delay for some range
retryPolicy.withDelay(1, 10, ChronoUnit.SECONDS);
// time bases jitter
retryPolicy.withJitter(Duration.ofMillis(100));
retryPolicy
.abortWhen(false)
.abortOn(NoRouteToHostException.class)
.abortIf(result -> result == false)
Circuit Breakers
Circuit breakers allow you to create systems that fail-fast by temporarily disabling execution as a way of preventing system overload.
CircuitBreaker<Object> breaker = new CircuitBreaker<>()
.handle(ConnectException.class) // when ConnectionException occurs, open circuit
.withFailureThreshold(3, 10) // failure threshold to transit to open circuit
.withSuccessThreshold(5) // success threshold to transit to closed state from half-open
.withDelay(Duration.ofMinutes(1)); // after 1 minutes, transit to half-open state
breaker.withFailureThreshold(5); // when a successive number of executions has failed
breaker.withFailureThreshold(3, 5); // the last 3 out of 5 executions has failed
breaker.withSuccessThreshold(3, 5); // the last 3 out of 5 executions has success
Circuit Breaker Best practices
breaker.open();
breaker.halfOpen();
breaker.close();
if (breaker.allowsExecution()) {
try {
breaker.preExecute();
doSomething();
breaker.recordSuccess();
} catch (Exception e) {
breaker.recordFailure(e);
}
}
Fallback
// Fallback is null
Fallback<Object> fallback = Fallback.of(null);
// Fallback is throw a custom exception.
Fallback<Object> fallback = Fallback.of(failure -> { throw new CustomException(failure); });
// Fallback call alternative method
Fallback<Object> fallback = Fallback.of(this::connectToBackup);
// Fallback to run asynchronously
Fallback<Object> fallback = Fallback.ofAsync(this::blockingCall);
Policy Composition
// Policies handle execution results in reverse order
Failsafe.with(fallback, retryPolicy, circuitBreaker).get(supplier);
// Means: Fallback(RetryPolicy(CircuitBreaker(Supplier)))
Event Listeners
Failsafe.with(retryPolicy, circuitBreaker)
.onComplete(e -> {
if (e.getResult() != null)
log.info("Connected to {}", e.getResult());
else if (e.getFailure() != null)
log.error("Failed to create connection", e.getFailure());
})
.get(this::connect);
retryPolicy
.onFailedAttempt(e -> log.error("Connection attempt failed", e.getLastFailure()))
.onRetry(e -> log.warn("Failure #{}. Retrying.", ctx.getAttemptCount()));
Event Listeners
circuitBreaker
.onClose(() -> log.info("The circuit breaker was closed"));
.onOpen(() -> log.info("The circuit breaker was opened"))
.onHalfOpen(() -> log.info("The circuit breaker was half-opened"))
Asynchronous API Integration
Failsafe.with(retryPolicy)
.getAsyncExecution(execution -> service.connect().whenComplete((result, failure) -> {
if (execution.complete(result, failure))
log.info("Connected");
else if (!execution.retry())
log.error("Connection attempts failed", failure);
}));
Failsafe.with(retryPolicy)
.getStageAsync(this::connectAsync)
.thenApplyAsync(value -> value + "bar")
.thenAccept(System.out::println));
Thank you!

Mais conteúdo relacionado

Mais procurados

Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and Fallacies
Roman Elizarov
 
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
Vyacheslav Lapin
 

Mais procurados (20)

The OMR GC talk - Ruby Kaigi 2015
The OMR GC talk - Ruby Kaigi 2015The OMR GC talk - Ruby Kaigi 2015
The OMR GC talk - Ruby Kaigi 2015
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and Fallacies
 
A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9
 
High performance network programming on the jvm oscon 2012
High performance network programming on the jvm   oscon 2012 High performance network programming on the jvm   oscon 2012
High performance network programming on the jvm oscon 2012
 
Stream processing from single node to a cluster
Stream processing from single node to a clusterStream processing from single node to a cluster
Stream processing from single node to a cluster
 
The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018The Year of JRuby - RubyC 2018
The Year of JRuby - RubyC 2018
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applications
 
What I did in My Internship @ WSO2
What I did in My Internship @ WSO2What I did in My Internship @ WSO2
What I did in My Internship @ WSO2
 
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, TokyoWeaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
 
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
ITSubbotik - как скрестить ежа с ужом или подводные камни внедрения функциона...
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
 
My internship presentation at WSO2
My internship presentation at WSO2My internship presentation at WSO2
My internship presentation at WSO2
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016Ruby Performance - The Last Mile - RubyConf India 2016
Ruby Performance - The Last Mile - RubyConf India 2016
 
Parallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative LanguageParallel-Ready Java Code: Managing Mutation in an Imperative Language
Parallel-Ready Java Code: Managing Mutation in an Imperative Language
 
Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研Facebook C++网络库Wangle调研
Facebook C++网络库Wangle调研
 
Shooting the Rapids
Shooting the RapidsShooting the Rapids
Shooting the Rapids
 
Ruby 2.4 Internals
Ruby 2.4 InternalsRuby 2.4 Internals
Ruby 2.4 Internals
 
Rxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJavaRxjava 介紹與 Android 中的 RxJava
Rxjava 介紹與 Android 中的 RxJava
 

Semelhante a Introduction of failsafe

Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization tools
mukul bhardwaj
 

Semelhante a Introduction of failsafe (20)

Circuit breakers - Using Spring-Boot + Hystrix + Dashboard + Retry
Circuit breakers - Using Spring-Boot + Hystrix + Dashboard + RetryCircuit breakers - Using Spring-Boot + Hystrix + Dashboard + Retry
Circuit breakers - Using Spring-Boot + Hystrix + Dashboard + Retry
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Linux synchronization tools
Linux synchronization toolsLinux synchronization tools
Linux synchronization tools
 
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
 
Burst clock controller
Burst clock controllerBurst clock controller
Burst clock controller
 
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)Reactive Java: Promises and Streams with Reakt  (JavaOne talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne talk 2016)
 
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)Reactive Java:  Promises and Streams with Reakt (JavaOne Talk 2016)
Reactive Java: Promises and Streams with Reakt (JavaOne Talk 2016)
 
Architecting for Microservices Part 2
Architecting for Microservices Part 2Architecting for Microservices Part 2
Architecting for Microservices Part 2
 
Building resilient applications
Building resilient applicationsBuilding resilient applications
Building resilient applications
 
Client Drivers and Cassandra, the Right Way
Client Drivers and Cassandra, the Right WayClient Drivers and Cassandra, the Right Way
Client Drivers and Cassandra, the Right Way
 
Best Practice for Achieving High Availability in MariaDB
Best Practice for Achieving High Availability in MariaDBBest Practice for Achieving High Availability in MariaDB
Best Practice for Achieving High Availability in MariaDB
 
02 2017 emea_roadshow_milan_ha
02 2017 emea_roadshow_milan_ha02 2017 emea_roadshow_milan_ha
02 2017 emea_roadshow_milan_ha
 
Reactive Streams - László van den Hoek
Reactive Streams - László van den HoekReactive Streams - László van den Hoek
Reactive Streams - László van den Hoek
 
MariaDB High Availability Webinar
MariaDB High Availability WebinarMariaDB High Availability Webinar
MariaDB High Availability Webinar
 
Circuit Breaker.pptx
Circuit Breaker.pptxCircuit Breaker.pptx
Circuit Breaker.pptx
 
Cassandra and drivers
Cassandra and driversCassandra and drivers
Cassandra and drivers
 
Not Less, Not More: Exactly Once, Large-Scale Stream Processing in Action
Not Less, Not More: Exactly Once, Large-Scale Stream Processing in ActionNot Less, Not More: Exactly Once, Large-Scale Stream Processing in Action
Not Less, Not More: Exactly Once, Large-Scale Stream Processing in Action
 
Circuit breaker pattern
Circuit breaker patternCircuit breaker pattern
Circuit breaker pattern
 
Designing Fault Tolerant Microservices
Designing Fault Tolerant MicroservicesDesigning Fault Tolerant Microservices
Designing Fault Tolerant Microservices
 
Introduction To Hystrix
Introduction To HystrixIntroduction To Hystrix
Introduction To Hystrix
 

Mais de Sunghyouk Bae

Multithread pattern 소개
Multithread pattern 소개Multithread pattern 소개
Multithread pattern 소개
Sunghyouk Bae
 

Mais de Sunghyouk Bae (14)

JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Requery overview
Requery overviewRequery overview
Requery overview
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 
measure metrics
measure metricsmeasure metrics
measure metrics
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Java naming strategy (자바 명명 전략)
Java naming strategy (자바 명명 전략)Java naming strategy (자바 명명 전략)
Java naming strategy (자바 명명 전략)
 
테스트자동화와 TDD
테스트자동화와 TDD테스트자동화와 TDD
테스트자동화와 TDD
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
JUnit & AssertJ
JUnit & AssertJJUnit & AssertJ
JUnit & AssertJ
 
좋은 개발자 되기
좋은 개발자 되기좋은 개발자 되기
좋은 개발자 되기
 
Using AdoRepository
Using AdoRepositoryUsing AdoRepository
Using AdoRepository
 
Multithread pattern 소개
Multithread pattern 소개Multithread pattern 소개
Multithread pattern 소개
 
Strategy Maps
Strategy MapsStrategy Maps
Strategy Maps
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

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
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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-...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
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 ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
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...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
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
 

Introduction of failsafe

  • 2. Agenda • MSA Use cases • What is Failsafe • Usage in Coupang • How to work • Main Features
  • 3. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 4. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 5. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 6. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 7. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 8. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 9. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 10. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 11. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 12. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Async Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 13. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Async Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 14. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Async Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 15. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Async Fail? -> Retry? Fallback? Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 16. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Async Fail? -> Retry? Fallback? Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 17. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Async Fail? -> Retry? Fallback? Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 18. MSA - Key features Service A Service B Service C Our Service Event Loop Asynchronous Non-Blocking Async Dashboard Fail? -> Retry? Fallback? Non-Blocking CompletableFuture ? Observable (RxJava) ? Cache
  • 19. Failsafe • Latency and FaultTolerance for Distributed Systems • Realtime Operations • Synchronous & Asynchronous • Resiliency - Fallback, Retry, Circuit Breaker
  • 20. Failsafe vs Hystrix • Executable logic can be passed to Failsafe as simple lambda expression • Failsafe support retry • Asynchronous execution in Failsafe are performed on a user suppliedThreadPool / Scheduler • Asynchronous execution can be observed via event listener api and return Future • Hystrix circuit breakers are time sensitive, Failsafe use last executions, regardless of when they took place. • Failsafe circuit breakers support execution timeouts and configurable support thresholds. Hystrix only performs a single execution when in half-open state • Failsafe circuit breakers can be shared across different executions against the same component, so that if a failure occurs, all executions against that component will be halted by the circuit breaker.
  • 21. Usage in Coupang • Used in Connect SDK • Main Goals • Retry policy (backoff, jitters) • Circuit breaker (Resiliency)
  • 23. Circuit Breaker Pattern Closed Open Half Open trip breaker If threshold reached Call pass through count fail/success reset breakers trip breaker try reset after timeout is reached calls pass through on success
 reset breaker on success
 reset breaker
  • 24. Closed-State • The circuit breaker executes operations as usual • If a failure occurs, the circuit breaker write it down • If a specified error threshold (number of failures or frequency of failures) is reached, it trips and opens the circuit breaker (transitions to the open-state)
  • 25. Open-State • Calls to the circuit breaker in the open state fail immediately • No call to the underlying operations is executed • After a specified timeout is reached, the circuit breaker transitions to the half-open state.
  • 26. Half-Open-State • In this state, one call is allowed to call the underlying operation • If this call failed, the circuit-breaker transitions to the open- state again until another timeout is reached • If it succeeded, the circuit-breaker resets and transitions to the closed-state.
  • 36. Main Features • Retry • Circuit breaker • Fallback
  • 37. Retry RetryPolicy<Object> retryPolicy = new RetryPolicy<>() .handle(ConnectException.class) // handle specific exception .withDelay(Duration.ofSeconds(1)) // retry with delay .withMaxRetries(3); // maximum retry count // Run with retries Failsafe.with(retryPolicy).run(() -> connect()); // Get with retries Connection connection = Failsafe.with(retryPolicy).get(() -> connect()); // Run with retries asynchronously CompletableFuture<Void> future = Failsafe.with(retryPolicy).runAsync(() -> connect()); // Get with retries asynchronously CompletableFuture<Connection> future = Failsafe.with(retryPolicy).getAsync(() -> connect());
  • 38. Retry policies retryPolicy.withMaxAttempts(3); // delay between attempts retryPolicy.withDelay(Duration.ofSeconds(1)); // delay with back off exponentially retryPolicy.withBackoff(1, 30, ChronoUnit.SECONDS); // random delay for some range retryPolicy.withDelay(1, 10, ChronoUnit.SECONDS); // time bases jitter retryPolicy.withJitter(Duration.ofMillis(100)); retryPolicy .abortWhen(false) .abortOn(NoRouteToHostException.class) .abortIf(result -> result == false)
  • 39. Circuit Breakers Circuit breakers allow you to create systems that fail-fast by temporarily disabling execution as a way of preventing system overload. CircuitBreaker<Object> breaker = new CircuitBreaker<>() .handle(ConnectException.class) // when ConnectionException occurs, open circuit .withFailureThreshold(3, 10) // failure threshold to transit to open circuit .withSuccessThreshold(5) // success threshold to transit to closed state from half-open .withDelay(Duration.ofMinutes(1)); // after 1 minutes, transit to half-open state breaker.withFailureThreshold(5); // when a successive number of executions has failed breaker.withFailureThreshold(3, 5); // the last 3 out of 5 executions has failed breaker.withSuccessThreshold(3, 5); // the last 3 out of 5 executions has success
  • 40. Circuit Breaker Best practices breaker.open(); breaker.halfOpen(); breaker.close(); if (breaker.allowsExecution()) { try { breaker.preExecute(); doSomething(); breaker.recordSuccess(); } catch (Exception e) { breaker.recordFailure(e); } }
  • 41. Fallback // Fallback is null Fallback<Object> fallback = Fallback.of(null); // Fallback is throw a custom exception. Fallback<Object> fallback = Fallback.of(failure -> { throw new CustomException(failure); }); // Fallback call alternative method Fallback<Object> fallback = Fallback.of(this::connectToBackup); // Fallback to run asynchronously Fallback<Object> fallback = Fallback.ofAsync(this::blockingCall);
  • 42. Policy Composition // Policies handle execution results in reverse order Failsafe.with(fallback, retryPolicy, circuitBreaker).get(supplier); // Means: Fallback(RetryPolicy(CircuitBreaker(Supplier)))
  • 43. Event Listeners Failsafe.with(retryPolicy, circuitBreaker) .onComplete(e -> { if (e.getResult() != null) log.info("Connected to {}", e.getResult()); else if (e.getFailure() != null) log.error("Failed to create connection", e.getFailure()); }) .get(this::connect); retryPolicy .onFailedAttempt(e -> log.error("Connection attempt failed", e.getLastFailure())) .onRetry(e -> log.warn("Failure #{}. Retrying.", ctx.getAttemptCount()));
  • 44. Event Listeners circuitBreaker .onClose(() -> log.info("The circuit breaker was closed")); .onOpen(() -> log.info("The circuit breaker was opened")) .onHalfOpen(() -> log.info("The circuit breaker was half-opened"))
  • 45. Asynchronous API Integration Failsafe.with(retryPolicy) .getAsyncExecution(execution -> service.connect().whenComplete((result, failure) -> { if (execution.complete(result, failure)) log.info("Connected"); else if (!execution.retry()) log.error("Connection attempts failed", failure); })); Failsafe.with(retryPolicy) .getStageAsync(this::connectAsync) .thenApplyAsync(value -> value + "bar") .thenAccept(System.out::println));