SlideShare uma empresa Scribd logo
1 de 51
Baixar para ler offline
Circuit Breaker
Stop the Fire Before It Happens
Brice McIver, Software Consultant
bmciver@keyholesoftware.com
Nebraska Code Conference
May 19, 2016
Sponsors
Agenda
Electricity 1
2
4
5
3
Software
Implementation
Hystrix
Summary
Agenda
Electricity 1
2
3
4
5
Electricity
Software
Implementation
Hystrix
Summary
In the Beginning
● People
○ Like electricity
○ Want electricity in their houses
○ Want to power lots of things with electricity
● Joule heating
○ H ∝ I2
• R • t
○ Wires get hot
○ Walls get hot
First Solution
● Fuses
○ It blows before your house does
● Issues
○ Disposable, one-time use item
○ US residential fuses same diameter as this item
Second Solution
● Circuit Breaker
○ Works like a fuse, but resettable
● Operation
○ Detect excess current
○ Fail
○ Open the circuit
● Allows one subsystem to fail without destroying the entire system
Agenda
Electricity 1
2
4
5
3
Software
Implementation
Hystrix
Summary
Software equivalents
● Failure
○ Error code
○ Timeout
○ Latency
● Blown state
○ Queue and retry
○ Throw error
○ Degraded functionality
● Reset
Lifecycle
Lifecycle
Lifecycle
Lifecycle
Agenda
Electricity 1
2
4
5
3
Software
Implementation
Hystrix
Summary
DumbCircuitBreaker
public class DumbCircuitBreaker {
protected enum BreakerState {OPEN, CLOSED}
protected volatile BreakerState state = BreakerState.CLOSED;
protected boolean allowRequest() {
return (BreakerState.CLOSED == state) ? true : false;
}
DumbCircuitBreaker
public class DumbCircuitBreaker {
protected enum BreakerState {OPEN, CLOSED}
protected volatile BreakerState state = BreakerState.CLOSED;
protected boolean allowRequest() {
return (BreakerState.CLOSED == state) ? true : false;
}
DumbCircuitBreaker
public class DumbCircuitBreaker {
protected enum BreakerState {OPEN, CLOSED}
protected volatile BreakerState state = BreakerState.CLOSED;
protected boolean allowRequest() {
return (BreakerState.CLOSED == state) ? true : false;
}
DumbCircuitBreaker
public class DumbCircuitBreaker {
protected enum BreakerState {OPEN, CLOSED}
protected volatile BreakerState state = BreakerState.CLOSED;
protected boolean allowRequest() {
return (BreakerState.CLOSED == state) ? true : false;
}
DumbCircuitBreaker
public class DumbCircuitBreaker {
protected enum BreakerState {OPEN, CLOSED}
protected volatile BreakerState state = BreakerState.CLOSED;
protected boolean allowRequest() {
return (BreakerState.CLOSED == state) ? true : false;
}
DumbCircuitBreaker
public void trip() {
state = BreakerState.OPEN;
}
protected void handleFailure(Throwable cause) throws Exception {
trip();
throw cause;
}
DumbCircuitBreaker
public void trip() {
state = BreakerState.OPEN;
}
protected void handleFailure(Throwable cause) throws Exception {
trip();
throw cause;
}
DumbCircuitBreaker
public void trip() {
state = BreakerState.OPEN;
}
protected void handleFailure(Throwable cause) throws Exception {
trip();
throw cause;
}
DumbCircuitBreaker
public <V> V invoke(Callable<V> c) throws Exception {
if (!allowRequest()) {
throw new CircuitBreakerException();
}
try {
V result = c.call();
return result;
} catch (Throwable cause) {
handleFailure(cause);
}
throw new IllegalStateException("not possible");
}
DumbCircuitBreaker
public <V> V invoke(Callable<V> c) throws Exception {
if (!allowRequest()) {
throw new CircuitBreakerException();
}
try {
V result = c.call();
return result;
} catch (Throwable cause) {
handleFailure(cause);
}
throw new IllegalStateException("not possible");
}
DumbCircuitBreaker
public <V> V invoke(Callable<V> c) throws Exception {
if (!allowRequest()) {
throw new CircuitBreakerException();
}
try {
V result = c.call();
return result;
} catch (Throwable cause) {
handleFailure(cause);
}
throw new IllegalStateException("not possible");
}
DumbCircuitBreaker
public <V> V invoke(Callable<V> c) throws Exception {
if (!allowRequest()) {
throw new CircuitBreakerException();
}
try {
V result = c.call();
return result;
} catch (Throwable cause) {
handleFailure(cause);
}
throw new IllegalStateException("not possible");
}
DumbCircuitBreaker
public void invoke(Runnable r) throws Exception {
if (!allowRequest()) {
throw new CircuitBreakerException();
}
try {
r.run();
return;
} catch (Throwable cause) {
handleFailure(cause);
}
throw new IllegalStateException("not possible");
}
DumbCircuitBreaker
public <V> V invoke(Runnable r, V result) throws Exception {
if (!allowRequest()) {
throw new CircuitBreakerException();
}
try {
r.run();
return result;
} catch (Throwable cause) {
handleFailure(cause);
}
throw new IllegalStateException("not possible");
}
}
DumbCircuitBreaker
public class Service {
private DumbCircuitBreaker cb = new DumbCircuitBreaker();
public String doSomething(final Object arg) throws Exception {
return cb.invoke(new Callable<String>() {
public String call() {
// make the call ...
}
});
}
}
LessDumbCircuitBreaker
public void reset() {
state = BreakerState.CLOSED;
isAttemptLive = false;
}
protected enum BreakerState {
OPEN,
HALF_CLOSED,
CLOSED
}
protected AtomicLong lastFailure = new AtomicLong(0L);
protected AtomicLong resetMillis = new AtomicLong(15 * 1000L);
protected boolean isAttemptLive = false;
LessDumbCircuitBreaker
protected boolean allowRequest() {
if (BreakerState.CLOSED == state) {
return true;
}
if (BreakerState.OPEN == state &&
System.currentTimeMillis() - lastFailure.get() >= resetMillis.get()) {
state = BreakerState.HALF_CLOSED;
}
return canAttempt();
}
LessDumbCircuitBreaker
private synchronized boolean canAttempt() {
if (!(BreakerState.HALF_CLOSED == state) || isAttemptLive) {
return false;
}
return true;
}
public void trip() {
state = BreakerState.OPEN;
lastFailure.set(System.currentTimeMillis());
isAttemptLive = false;
}
Missing?
● Capturing exceptions
● How many times has the breaker tripped?
● Additional failure scenarios/conditions
● Ability to notify listeners of breaker state changes
● Ability to bypass the circuit breaker
Agenda
Electricity 1
2
4
5
3
Software
Implementation
Hystrix
Summary
“Hystrix is a latency and fault tolerance library designed to
isolate points of access to remote systems, services and 3rd
party libraries, stop cascading failure and enable resilience in
complex distributed systems where failure is inevitable.”
How to Use
● Add to Maven
○ <dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-core</artifactId>
<version>1.5.2</version>
</dependency>
How to Use
● Extend HystrixCommand
○ public class CommandHelloWorld extends HystrixCommand<String> {
private final String name;
public CommandHelloWorld(String name) {
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() {
return "Hello " + name + "!";
}
}
How to Use
● Use in code
○ String s = new CommandHelloWorld("Bob").execute();
○ Future<String> s = new CommandHelloWorld("Bob").queue();
○ Observable<String> s = new CommandHelloWorld("Bob").observe();
Spring Boot
● Add @EnableCircuitBreaker to Application class
○ @SpringBootApplication
@EnableCircuitBreaker
public class Application {
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
● Add @HystrixCommand to methods that might fail
Spring Boot
@Component
public class StoreIntegration {
@HystrixCommand(fallbackMethod = "defaultStores")
public Object getStores(Map<String, Object> parameters) {
//do stuff that might fail
}
public Object defaultStores(Map<String, Object> parameters) {
return /* something useful */;
}
}
Defaults
● Isolation: Thread
● Timeout: 1 s, interrupt
● Max concurrent requests: 10 (both command and fallback)
● Request Volume Threshold: 20 (in 10 s window)
● Sleep Window: 5 s
● Error Threshold: 50%
● 20 failures in 5 s
Properties
@HystrixCommand(commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500")
},
threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "30"),
@HystrixProperty(name = "maxQueueSize", value = "101"),
@HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),
@HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"),
@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"),
@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1440")
})
public User getUserById(String id) {
return userResource.getUserById(id);
}
Dashboard
Agenda
Electricity 1
2
4
5
3
Software
Implementation
Hystrix
Summary
Sources
● Nygard, Michael T. Release It! 30 Mar 2007
● Timms, Simon. Mastering JavaScript Design Patterns. 21 Nov 2014
● Newman, Sam. Building Microservices. 10 Feb 2015
● Paramount Pictures. Wayne’s World. 14 Feb 1992
● Fowler, Martin. CircuitBreaker. 6 Mar 2014. http://martinfowler.
com/bliki/CircuitBreaker.html
● Comcast jrugged source code. https://github.com/Comcast/jrugged
● Netflix Hystrix Readme. https://github.com/Netflix/Hystrix
Sources
● Christensen, Ben. Fault Tolerance in a High Volume, Distributed System. 29
Feb 2012. http://techblog.netflix.com/2012/02/fault-tolerance-in-high-volume.
html
● Schmaus, Ben. Making the Netflix API More Resilient. 8 Dec 2011. http:
//techblog.netflix.com/2011/12/making-netflix-api-more-resilient.html
● Spring Cloud Netflix documentation. http://cloud.spring.io/spring-cloud-
netflix/spring-cloud-netflix.html
Summary
● Like a physical circuit breaker, the circuit
breaker pattern allows a subsystem to fail
without destroying the system
● Failure is inevitable, be prepared for it
● Don’t implement your own, use a trusted
implementation

Mais conteúdo relacionado

Mais procurados

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202Mahmoud Samir Fayed
 
Preparation for mit ose lab4
Preparation for mit ose lab4Preparation for mit ose lab4
Preparation for mit ose lab4Benux Wei
 
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅재춘 노
 
Node.js and angular js
Node.js and angular jsNode.js and angular js
Node.js and angular jsHyungKuIm
 
Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Dennis Byrne
 
Java with a Clojure mindset
Java with a Clojure mindsetJava with a Clojure mindset
Java with a Clojure mindsetDaniel Lebrero
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++Dimitrios Platis
 
The Node.js Event Loop: Not So Single Threaded
The Node.js Event Loop: Not So Single ThreadedThe Node.js Event Loop: Not So Single Threaded
The Node.js Event Loop: Not So Single ThreadedBryan Hughes
 
Parallele Suche in grossen Graphen mit Heuristiken und Caches
Parallele Suche in grossen Graphen mit Heuristiken und CachesParallele Suche in grossen Graphen mit Heuristiken und Caches
Parallele Suche in grossen Graphen mit Heuristiken und CachesJAVAPRO
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopyayaria
 
What is row level isolation on cassandra
What is row level isolation on cassandraWhat is row level isolation on cassandra
What is row level isolation on cassandraKazutaka Tomita
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesBrandon Minnick, MBA
 
Mysql5.1 character set testing
Mysql5.1 character set testingMysql5.1 character set testing
Mysql5.1 character set testingPhilip Zhong
 
Correcting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NETCorrecting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NETBrandon Minnick, MBA
 
Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socketPhilip Zhong
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Philip Zhong
 

Mais procurados (20)

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202The Ring programming language version 1.8 book - Part 105 of 202
The Ring programming language version 1.8 book - Part 105 of 202
 
Preparation for mit ose lab4
Preparation for mit ose lab4Preparation for mit ose lab4
Preparation for mit ose lab4
 
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
드로이드 나이츠 2018: RxJava 적용 팁 및 트러블 슈팅
 
Node.js and angular js
Node.js and angular jsNode.js and angular js
Node.js and angular js
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)Introduction to Unit Testing (Part 2 of 2)
Introduction to Unit Testing (Part 2 of 2)
 
Java with a Clojure mindset
Java with a Clojure mindsetJava with a Clojure mindset
Java with a Clojure mindset
 
Refactoring for testability c++
Refactoring for testability c++Refactoring for testability c++
Refactoring for testability c++
 
The Node.js Event Loop: Not So Single Threaded
The Node.js Event Loop: Not So Single ThreadedThe Node.js Event Loop: Not So Single Threaded
The Node.js Event Loop: Not So Single Threaded
 
Qt Network Explained (Portuguese)
Qt Network Explained (Portuguese)Qt Network Explained (Portuguese)
Qt Network Explained (Portuguese)
 
Ac2
Ac2Ac2
Ac2
 
Parallele Suche in grossen Graphen mit Heuristiken und Caches
Parallele Suche in grossen Graphen mit Heuristiken und CachesParallele Suche in grossen Graphen mit Heuristiken und Caches
Parallele Suche in grossen Graphen mit Heuristiken und Caches
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
What is row level isolation on cassandra
What is row level isolation on cassandraWhat is row level isolation on cassandra
What is row level isolation on cassandra
 
Correcting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await MistakesCorrecting Common .NET Async/Await Mistakes
Correcting Common .NET Async/Await Mistakes
 
Mysql5.1 character set testing
Mysql5.1 character set testingMysql5.1 character set testing
Mysql5.1 character set testing
 
Correcting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NETCorrecting Common Async/Await Mistakes in .NET
Correcting Common Async/Await Mistakes in .NET
 
Mysql handle socket
Mysql handle socketMysql handle socket
Mysql handle socket
 
Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8Compare mysql5.1.50 mysql5.5.8
Compare mysql5.1.50 mysql5.5.8
 

Destaque

LOGIC - European perspective, lifelong learning strategies
LOGIC - European perspective, lifelong learning strategiesLOGIC - European perspective, lifelong learning strategies
LOGIC - European perspective, lifelong learning strategiesLLL Platform
 
Apostolic Center – A City Set On A Hill
Apostolic Center – A City Set On A Hill Apostolic Center – A City Set On A Hill
Apostolic Center – A City Set On A Hill HRockChurch
 
Budaya,kreativitas dan inovasi
Budaya,kreativitas dan inovasiBudaya,kreativitas dan inovasi
Budaya,kreativitas dan inovasiyudharushendrawan
 
MacromolBioSci2004-4-601
MacromolBioSci2004-4-601MacromolBioSci2004-4-601
MacromolBioSci2004-4-601Zdeno Spitalsky
 
Juomakulttuuri muuttuu - sittenkin!
Juomakulttuuri muuttuu - sittenkin!Juomakulttuuri muuttuu - sittenkin!
Juomakulttuuri muuttuu - sittenkin!Panimoliitto
 
Thuốc chữa bệnh gây suy giảm tình dục ở nam giới
Thuốc chữa bệnh gây suy giảm tình dục ở nam giớiThuốc chữa bệnh gây suy giảm tình dục ở nam giới
Thuốc chữa bệnh gây suy giảm tình dục ở nam giớilashawna306
 
Final High Springs Development Plan-2
Final High Springs Development Plan-2Final High Springs Development Plan-2
Final High Springs Development Plan-2Tania Hernandez
 
Panimoliiton ajankohtaiset teemat / elokuu 2016
Panimoliiton ajankohtaiset teemat / elokuu 2016Panimoliiton ajankohtaiset teemat / elokuu 2016
Panimoliiton ajankohtaiset teemat / elokuu 2016Panimoliitto
 
Vertailua; eri EU-maat
Vertailua; eri EU-maatVertailua; eri EU-maat
Vertailua; eri EU-maatPanimoliitto
 

Destaque (15)

LOGIC - European perspective, lifelong learning strategies
LOGIC - European perspective, lifelong learning strategiesLOGIC - European perspective, lifelong learning strategies
LOGIC - European perspective, lifelong learning strategies
 
Backstabber book
Backstabber bookBackstabber book
Backstabber book
 
Apostolic Center – A City Set On A Hill
Apostolic Center – A City Set On A Hill Apostolic Center – A City Set On A Hill
Apostolic Center – A City Set On A Hill
 
CV eldashash
CV eldashashCV eldashash
CV eldashash
 
Budaya,kreativitas dan inovasi
Budaya,kreativitas dan inovasiBudaya,kreativitas dan inovasi
Budaya,kreativitas dan inovasi
 
Leveraging Social
Leveraging SocialLeveraging Social
Leveraging Social
 
MacromolBioSci2004-4-601
MacromolBioSci2004-4-601MacromolBioSci2004-4-601
MacromolBioSci2004-4-601
 
Juomakulttuuri muuttuu - sittenkin!
Juomakulttuuri muuttuu - sittenkin!Juomakulttuuri muuttuu - sittenkin!
Juomakulttuuri muuttuu - sittenkin!
 
Thuốc chữa bệnh gây suy giảm tình dục ở nam giới
Thuốc chữa bệnh gây suy giảm tình dục ở nam giớiThuốc chữa bệnh gây suy giảm tình dục ở nam giới
Thuốc chữa bệnh gây suy giảm tình dục ở nam giới
 
Final High Springs Development Plan-2
Final High Springs Development Plan-2Final High Springs Development Plan-2
Final High Springs Development Plan-2
 
Poir badania i_rozwoj_ncbir
Poir badania i_rozwoj_ncbirPoir badania i_rozwoj_ncbir
Poir badania i_rozwoj_ncbir
 
Panimoliiton ajankohtaiset teemat / elokuu 2016
Panimoliiton ajankohtaiset teemat / elokuu 2016Panimoliiton ajankohtaiset teemat / elokuu 2016
Panimoliiton ajankohtaiset teemat / elokuu 2016
 
Capitulo2
Capitulo2Capitulo2
Capitulo2
 
Ganesh_Gopalakrishnan
Ganesh_GopalakrishnanGanesh_Gopalakrishnan
Ganesh_Gopalakrishnan
 
Vertailua; eri EU-maat
Vertailua; eri EU-maatVertailua; eri EU-maat
Vertailua; eri EU-maat
 

Semelhante a Circuit breaker

Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaFrank Lyaruu
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»SpbDotNet Community
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++Dimitrios Platis
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7Mike North
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3Jieyi Wu
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 

Semelhante a Circuit breaker (20)

Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Fault tolerance made easy
Fault tolerance made easyFault tolerance made easy
Fault tolerance made easy
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Resilience mit Hystrix
Resilience mit HystrixResilience mit Hystrix
Resilience mit Hystrix
 
[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++[grcpp] Refactoring for testability c++
[grcpp] Refactoring for testability c++
 
Curator intro
Curator introCurator intro
Curator intro
 
Async JavaScript in ES7
Async JavaScript in ES7Async JavaScript in ES7
Async JavaScript in ES7
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3
 
Thread
ThreadThread
Thread
 
An intro to cqrs
An intro to cqrsAn intro to cqrs
An intro to cqrs
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 

Último

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Circuit breaker

  • 1. Circuit Breaker Stop the Fire Before It Happens Brice McIver, Software Consultant bmciver@keyholesoftware.com Nebraska Code Conference May 19, 2016
  • 5. In the Beginning ● People ○ Like electricity ○ Want electricity in their houses ○ Want to power lots of things with electricity ● Joule heating ○ H ∝ I2 • R • t ○ Wires get hot ○ Walls get hot
  • 6.
  • 7. First Solution ● Fuses ○ It blows before your house does ● Issues ○ Disposable, one-time use item ○ US residential fuses same diameter as this item
  • 8.
  • 9.
  • 10. Second Solution ● Circuit Breaker ○ Works like a fuse, but resettable ● Operation ○ Detect excess current ○ Fail ○ Open the circuit ● Allows one subsystem to fail without destroying the entire system
  • 12. Software equivalents ● Failure ○ Error code ○ Timeout ○ Latency ● Blown state ○ Queue and retry ○ Throw error ○ Degraded functionality ● Reset
  • 18. DumbCircuitBreaker public class DumbCircuitBreaker { protected enum BreakerState {OPEN, CLOSED} protected volatile BreakerState state = BreakerState.CLOSED; protected boolean allowRequest() { return (BreakerState.CLOSED == state) ? true : false; }
  • 19. DumbCircuitBreaker public class DumbCircuitBreaker { protected enum BreakerState {OPEN, CLOSED} protected volatile BreakerState state = BreakerState.CLOSED; protected boolean allowRequest() { return (BreakerState.CLOSED == state) ? true : false; }
  • 20. DumbCircuitBreaker public class DumbCircuitBreaker { protected enum BreakerState {OPEN, CLOSED} protected volatile BreakerState state = BreakerState.CLOSED; protected boolean allowRequest() { return (BreakerState.CLOSED == state) ? true : false; }
  • 21. DumbCircuitBreaker public class DumbCircuitBreaker { protected enum BreakerState {OPEN, CLOSED} protected volatile BreakerState state = BreakerState.CLOSED; protected boolean allowRequest() { return (BreakerState.CLOSED == state) ? true : false; }
  • 22. DumbCircuitBreaker public class DumbCircuitBreaker { protected enum BreakerState {OPEN, CLOSED} protected volatile BreakerState state = BreakerState.CLOSED; protected boolean allowRequest() { return (BreakerState.CLOSED == state) ? true : false; }
  • 23. DumbCircuitBreaker public void trip() { state = BreakerState.OPEN; } protected void handleFailure(Throwable cause) throws Exception { trip(); throw cause; }
  • 24. DumbCircuitBreaker public void trip() { state = BreakerState.OPEN; } protected void handleFailure(Throwable cause) throws Exception { trip(); throw cause; }
  • 25. DumbCircuitBreaker public void trip() { state = BreakerState.OPEN; } protected void handleFailure(Throwable cause) throws Exception { trip(); throw cause; }
  • 26. DumbCircuitBreaker public <V> V invoke(Callable<V> c) throws Exception { if (!allowRequest()) { throw new CircuitBreakerException(); } try { V result = c.call(); return result; } catch (Throwable cause) { handleFailure(cause); } throw new IllegalStateException("not possible"); }
  • 27. DumbCircuitBreaker public <V> V invoke(Callable<V> c) throws Exception { if (!allowRequest()) { throw new CircuitBreakerException(); } try { V result = c.call(); return result; } catch (Throwable cause) { handleFailure(cause); } throw new IllegalStateException("not possible"); }
  • 28. DumbCircuitBreaker public <V> V invoke(Callable<V> c) throws Exception { if (!allowRequest()) { throw new CircuitBreakerException(); } try { V result = c.call(); return result; } catch (Throwable cause) { handleFailure(cause); } throw new IllegalStateException("not possible"); }
  • 29. DumbCircuitBreaker public <V> V invoke(Callable<V> c) throws Exception { if (!allowRequest()) { throw new CircuitBreakerException(); } try { V result = c.call(); return result; } catch (Throwable cause) { handleFailure(cause); } throw new IllegalStateException("not possible"); }
  • 30. DumbCircuitBreaker public void invoke(Runnable r) throws Exception { if (!allowRequest()) { throw new CircuitBreakerException(); } try { r.run(); return; } catch (Throwable cause) { handleFailure(cause); } throw new IllegalStateException("not possible"); }
  • 31. DumbCircuitBreaker public <V> V invoke(Runnable r, V result) throws Exception { if (!allowRequest()) { throw new CircuitBreakerException(); } try { r.run(); return result; } catch (Throwable cause) { handleFailure(cause); } throw new IllegalStateException("not possible"); } }
  • 32. DumbCircuitBreaker public class Service { private DumbCircuitBreaker cb = new DumbCircuitBreaker(); public String doSomething(final Object arg) throws Exception { return cb.invoke(new Callable<String>() { public String call() { // make the call ... } }); } }
  • 33. LessDumbCircuitBreaker public void reset() { state = BreakerState.CLOSED; isAttemptLive = false; } protected enum BreakerState { OPEN, HALF_CLOSED, CLOSED } protected AtomicLong lastFailure = new AtomicLong(0L); protected AtomicLong resetMillis = new AtomicLong(15 * 1000L); protected boolean isAttemptLive = false;
  • 34. LessDumbCircuitBreaker protected boolean allowRequest() { if (BreakerState.CLOSED == state) { return true; } if (BreakerState.OPEN == state && System.currentTimeMillis() - lastFailure.get() >= resetMillis.get()) { state = BreakerState.HALF_CLOSED; } return canAttempt(); }
  • 35. LessDumbCircuitBreaker private synchronized boolean canAttempt() { if (!(BreakerState.HALF_CLOSED == state) || isAttemptLive) { return false; } return true; } public void trip() { state = BreakerState.OPEN; lastFailure.set(System.currentTimeMillis()); isAttemptLive = false; }
  • 36. Missing? ● Capturing exceptions ● How many times has the breaker tripped? ● Additional failure scenarios/conditions ● Ability to notify listeners of breaker state changes ● Ability to bypass the circuit breaker
  • 38. “Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.”
  • 39.
  • 40. How to Use ● Add to Maven ○ <dependency> <groupId>com.netflix.hystrix</groupId> <artifactId>hystrix-core</artifactId> <version>1.5.2</version> </dependency>
  • 41. How to Use ● Extend HystrixCommand ○ public class CommandHelloWorld extends HystrixCommand<String> { private final String name; public CommandHelloWorld(String name) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.name = name; } @Override protected String run() { return "Hello " + name + "!"; } }
  • 42. How to Use ● Use in code ○ String s = new CommandHelloWorld("Bob").execute(); ○ Future<String> s = new CommandHelloWorld("Bob").queue(); ○ Observable<String> s = new CommandHelloWorld("Bob").observe();
  • 43. Spring Boot ● Add @EnableCircuitBreaker to Application class ○ @SpringBootApplication @EnableCircuitBreaker public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } } ● Add @HystrixCommand to methods that might fail
  • 44. Spring Boot @Component public class StoreIntegration { @HystrixCommand(fallbackMethod = "defaultStores") public Object getStores(Map<String, Object> parameters) { //do stuff that might fail } public Object defaultStores(Map<String, Object> parameters) { return /* something useful */; } }
  • 45. Defaults ● Isolation: Thread ● Timeout: 1 s, interrupt ● Max concurrent requests: 10 (both command and fallback) ● Request Volume Threshold: 20 (in 10 s window) ● Sleep Window: 5 s ● Error Threshold: 50% ● 20 failures in 5 s
  • 46. Properties @HystrixCommand(commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "500") }, threadPoolProperties = { @HystrixProperty(name = "coreSize", value = "30"), @HystrixProperty(name = "maxQueueSize", value = "101"), @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"), @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15"), @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "12"), @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "1440") }) public User getUserById(String id) { return userResource.getUserById(id); }
  • 49. Sources ● Nygard, Michael T. Release It! 30 Mar 2007 ● Timms, Simon. Mastering JavaScript Design Patterns. 21 Nov 2014 ● Newman, Sam. Building Microservices. 10 Feb 2015 ● Paramount Pictures. Wayne’s World. 14 Feb 1992 ● Fowler, Martin. CircuitBreaker. 6 Mar 2014. http://martinfowler. com/bliki/CircuitBreaker.html ● Comcast jrugged source code. https://github.com/Comcast/jrugged ● Netflix Hystrix Readme. https://github.com/Netflix/Hystrix
  • 50. Sources ● Christensen, Ben. Fault Tolerance in a High Volume, Distributed System. 29 Feb 2012. http://techblog.netflix.com/2012/02/fault-tolerance-in-high-volume. html ● Schmaus, Ben. Making the Netflix API More Resilient. 8 Dec 2011. http: //techblog.netflix.com/2011/12/making-netflix-api-more-resilient.html ● Spring Cloud Netflix documentation. http://cloud.spring.io/spring-cloud- netflix/spring-cloud-netflix.html
  • 51. Summary ● Like a physical circuit breaker, the circuit breaker pattern allows a subsystem to fail without destroying the system ● Failure is inevitable, be prepared for it ● Don’t implement your own, use a trusted implementation