SlideShare a Scribd company logo
1 of 31
Download to read offline
Hands-on Hystrix - Best Practices und Stolperfallen
WER ERZÄHLT DIE NÄCHSTEN 50+ MINUTEN
ETWAS?
Gerrit Brehmer, Karlsruhe
Auf der Arbeit: So ware-Entwickler/Architekt bei der inovex GmbH
In der Freizeit: Meine Tochter & Smart Home
REPRESENTATIVE UMFRAGE
Wer hat Hystrix schon im Produktiv-Einsatz oder plant es in Kürze?
WARUM IST ROBUSTHEIT WICHTIG?
Michael Nygard über den Alltag
bei mittleren bis großen SW-Systemen:
“The normal mode of operation
is partial failure.“
BEISPIELE GROSSER AUSFÄLLE
VORAB: HÄUFIGES (ANTI-)PATTERN
@Transactional
@RequestMapping("api")
public ResponseEntity updateUser(UserData data) {
validate(data); // DB
checkWithExternalService(data); // Extern
Entity updatedUsed = saveToDb(data); // DB
return toResponseEntity(updatedUsed); // DB / DTO
}
DB-Transaktion/Verbindung so kurz wie möglich
Wartende Requests blockieren kostbare Ressourcen
Böse: OpenSessionInViewFilter
VERURSACHER VON AUSFÄLLEN
Teilausfälle
Hardware
So ware
Fehlerkaskaden
Laufzeitprobleme
Last-Peaks
ABHÄNGIGKEITEN IM GRIFF
Nichtfunktionale Anforderungen
an den eigenen Dienst
an und von externen Diensten
SLAs (leider viel zu selten vorhanden)
Entkopplung & Isolation
Ziele:
Eine robuste und fehlertolerante Anwendung
Die beste Fehlerbehandlung ist die,
von der der Nutzer nichts mitbekommt
ENTKOPPLUNG - USE CASE #1
Berechnung von kundenspezifischen Empfehlungen durch ein entferntes
System
enge Integration in einen Großteil der Seiten
Fehler/Timeouts schlagen sofort auf diese Seiten durch
Lösung mit Hystrix:
Alternative Empfehlungen auf Basis von statischen Regeln/einfachen
Filtern (kein entferntes System) im Fehlerfall
ERGEBNIS OHNE HYSTRIX
@Inject
RecoService recoClient;
public Movies getReco(long customerId) {
return recoClient.getMovies(customerId);
}
ERGEBNIS MIT HYSTRIX
STATISCHER FALLBACK
public class RecoForCustomerCommand extends HystrixCommand<Movies> {
...
public RecoForCustomerCommand(RecoService recoClient, long customerId) {
super(
Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Reco"))
.andCommandKey(HystrixCommandKey.Factory.asKey("RecoForCustomer"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RecoTP")));
this.recoClient = recoClient;
this.customerId = customerId;
}
@Override
protected Movies run() {
return recoClient.getMovies(customerId);
}
@Override
protected Movies getFallback() {
return Movies.EMPTY_LIST;
}
}
public Movies getReco(long customerId) {
return new RecoForCustomerCommand(recoClient, customerId).execute();
}
ERGEBNIS MIT HYSTRIX
DYNAMISCHER FALLBACK
public class RecoForCustomerCommand extends HystrixCommand<Movies> {
...
public RecoForCustomerCommand(RecoService recoClient, long custId) {
super(
Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Reco"))
.andCommandKey(HystrixCommandKey.Factory.asKey("RecoForCustomer"))
.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RecoTP")));
this.recoClient = recoClient;
this.customerId = custId;
}
@Override
protected Movies run() {
return recoClient.getMovies(customerId);
}
@Override
protected Movies getFallback() {
return InternalRecoClient.getTopMovies();
}
}
public Movies getReco(long customerId) {
return new RecoForCustomerCommand(recoService, customerId).execute();
}
ENTKOPPLUNG - USE CASE #2
Fehler-Kaskaden: Laufzeit-Probleme wirken sich auch auf aufrufende
Systeme aus
begrenzte Ressourcen
werden gebunden
Aufwand für Connection-
Handling steigt rapide
Seiteneffekte in andere
Systeme
ENTKOPPLUNG - USE CASE #2
Lösung mit Hystrix:
Direkte Fehlerrückgabe
Verhindert weitere
Laufzeitprobleme
HYSTRIX PATTERNS
Implementierung diverser Resilience Patterns
Graceful degradation (Use
Case 1)
Fail Fast (Use case 2)
Fail silent
Bulkheading
Circuit Breaker
CIRCUIT BREAKER
PITFALLS
WENN DA NICHT DIE PRAXIS WÄRE...
THREAD-POOLS ODER SEMAPHOREN
Thread Pools
können zwischen mehreren Commands geshared werden
bessere Isolierung
spürbarer Overhead (0-9ms, ø 1ms)
Thread-Pools verhindern nicht, dass Aufrufe dauerha blockieren
Java Threads können nicht gesichert beendet werden
Komplexer in der Implementierung
Timeouts setzen - immer und überall
Nicht blockierende APIs verwenden (Java NIO Channel, Netty)
Thread.currentThread().isInterrupted() nutzen
THREAD-POOLS ODER SEMAPHOREN
Semaphoren
minimaler Overhead
Timeouts ab Hystrix 1.4 ... Aber:
Ausführungsdauer wird nicht verringert (Caller-Thread)
Fallback wird in einem extra Thread ausgeführt, wenn Timeout
erreicht wird
Fallback-Rückgabe erst mit Abschluss Caller-Thread
Empfehlung für Aufrufe mit minimaler Latenz
EINSCHRÄNKUNGEN DURCH THREADPOOLS
ThreadLocals stehen nicht zur Verfügung
MDC / NDC Log Kontexte
(DB-)Transaktionsstatus
Aktueller HTTP Request / Security Context
Thread gebundene DI-Scopes (RequestScope, ThreadScope)
LÖSUNG THREADLOCAL
Custom ConcurrencyStrategy
public class CustomStrategy extends HystrixConcurrencyStrategy {
@Override
public <T> Callable<T> wrapCallable(final Callable<T> callable) {
final Map context = MDC.getContext();
final RequestAttributes attr = RequestContextHolder.get();
return super.wrapCallable(new Callable<T>() {
@Override
public T call() throws Exception {
try {
MDC.replaceAll(context);
RequestContextHolder.set(attr);
return callable.call();
} finally {
RequestContextHolder.resetRequestAttributes();
MDC.clear();
} ...
HystrixPlugins.getInstance().registerConcurrencyStrategy(new CustomStrategy());
EINSATZ IN SERVLET-/JEE CONTAINERN
Dynamisches Deployment statt Container Restart
Potentielle Resource Leaks
Lösung:
Hystrix.reset()
Servlet listener
Shutdown Hook
Singelton @PreDestroy-Methode
EXCEPTIONHANDLING
Hystrix Standard: Unchecked Exceptions
Eigene werden in HystrixRuntimeExceptions gewrappt
Kompatibilität Legacy Code
Neue Fehlerfälle
Timeout durch Hystrix
Offener Circuit, Pool ausgelastet
Sonderfall HystrixBadRequestException
Stellt fehlerha e Anfrage dar
Kein Fallback
Keine Fehler-Statistik
EXCEPTIONS: ABWÄRTSKOMPATIBILITÄT
public abstract class LegacyCommand extends HystrixCommand {
...
public T executeWithCheckedEx() throws CheckedIOException {
try {
return super.execute();
} catch (RuntimeException e) {
if (isCircuitBreakerOpen() || isResponseRejected()
|| isResponseTimedOut() || isResponseShortCircuited()) {
throw new CheckedIOException("req. aborted:"+e.getMessage());
} else if (e.getCause() instanceof CheckedIOException) {
throw (CheckedIOException) e.getCause();
} else {
throw e;
}
}
}
HYSTRIX-ANNOTATIONS: JAVANICA
Aspekt zur Erstellung von HystrixCommands zur Laufzeit
Interceptoren & andere Aspekte greifen nicht!
Konfiguration per Annotation
Einschränkung zur Laufzeit & Wiederverwendbarkeit
Implizite Regeln (Convention over Configuration)
Exception-Handling anders
Exceptiontypen können ignoriert werden und werden ohne
"Verpackung" zurückgeworfen
Exceptionhandling ansonsten identisch
Änderung Exception Handling durch Anpassung
HystrixCommandAspect
HYSTRIX/(NETFLIX)-INTEGRATION MIT
SPRING
Spring Cloud Netflix
Features per Annotation in der JavaConfig aktivieren
Javanica Aktivierung & ShutdownHook
Hystrix Event Stream
Hystrix Dashboard
Hystrix Turbine (auf Cloud Anwendung spezialisiert)
Integration mit weiteren Netflix Bibliotheken (Heureka, Zuul,
Ribbon,..)
MICROSERVICES & HYSTRIX
Netflix einer der großen Treiber der Microservice Architektur
Hystrix wird hauptsächlich in deren API Gateways eingesetzt
Reduzierung der Requests
Handling vieler Abhängigkeiten
Parallele Verarbeitung (RxJava)
Weitere Optimierungen:
RequestCollapser
RequestCache
DEMO
JHipster Stack als API Gateway
Angular JS / Bootstrap
Spring Boot
Hystrix
Drei simple REST Microservices
(Spring Boot)
Monitoring
Hystrix Dashboard
Kibana Dashboard (ELK)
FAZIT & AUSBLICK
Hystrix
Entkopplung und Isolierung leicht gemacht
Neue Version bringt weitere Features und Verbesserungen
Dennoch: Komplexität mit Hystrix ist nicht zu unterschätzen
Hystrix für Microservices
Bei Inter-Service Kommunikation
Integration externer Dienste
API Gateway
BILDERVERZEICHNIS
Hystrix Patterns:
https://www.flickr.com/photos/ramnaganat/7154180752
Circuit Breaker: http://martinfowler.com/bliki/CircuitBreaker.html
Pitfalls: https://www.flickr.com/photos/nafmo/1488330724
VIELEN DANK FÜR EURE AUFMERKSAMKEIT!

More Related Content

What's hot

openstack Übersicht @GPN15
openstack Übersicht @GPN15openstack Übersicht @GPN15
openstack Übersicht @GPN15m1no
 
Einführung in Elasticsearch
Einführung in ElasticsearchEinführung in Elasticsearch
Einführung in ElasticsearchFlorian Hopf
 
Prometheus Monitoring
Prometheus MonitoringPrometheus Monitoring
Prometheus Monitoringinovex GmbH
 
Die Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickeln
Die Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickelnDie Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickeln
Die Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickelnQAware GmbH
 
Mit OpenStack zur eigenen Cloud (OSDC 2012)
Mit OpenStack zur eigenen Cloud (OSDC 2012)Mit OpenStack zur eigenen Cloud (OSDC 2012)
Mit OpenStack zur eigenen Cloud (OSDC 2012)hastexo
 
Stackstorm – Event driven Automation
Stackstorm – Event driven AutomationStackstorm – Event driven Automation
Stackstorm – Event driven Automationinovex GmbH
 
Quarkus Quickstart
Quarkus QuickstartQuarkus Quickstart
Quarkus QuickstartQAware GmbH
 

What's hot (8)

openstack Übersicht @GPN15
openstack Übersicht @GPN15openstack Übersicht @GPN15
openstack Übersicht @GPN15
 
Einführung in Elasticsearch
Einführung in ElasticsearchEinführung in Elasticsearch
Einführung in Elasticsearch
 
Prometheus Monitoring
Prometheus MonitoringPrometheus Monitoring
Prometheus Monitoring
 
Die Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickeln
Die Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickelnDie Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickeln
Die Leichtigkeit des Seins: Bindings für Eclipse SmartHome entwickeln
 
Mit OpenStack zur eigenen Cloud (OSDC 2012)
Mit OpenStack zur eigenen Cloud (OSDC 2012)Mit OpenStack zur eigenen Cloud (OSDC 2012)
Mit OpenStack zur eigenen Cloud (OSDC 2012)
 
Stackstorm – Event driven Automation
Stackstorm – Event driven AutomationStackstorm – Event driven Automation
Stackstorm – Event driven Automation
 
Node.js Security
Node.js SecurityNode.js Security
Node.js Security
 
Quarkus Quickstart
Quarkus QuickstartQuarkus Quickstart
Quarkus Quickstart
 

Similar to Hands-on Hystrix - Best Practices und Stolperfallen

Lightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPALightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPAmh0708
 
Cloud Native & Java EE: Freund oder Feind?
Cloud Native & Java EE: Freund oder Feind?Cloud Native & Java EE: Freund oder Feind?
Cloud Native & Java EE: Freund oder Feind?QAware GmbH
 
Cloud Native und Java EE: Freund oder Feind?
Cloud Native und Java EE: Freund oder Feind?Cloud Native und Java EE: Freund oder Feind?
Cloud Native und Java EE: Freund oder Feind?Josef Adersberger
 
Camunda@1&1
Camunda@1&1Camunda@1&1
Camunda@1&11&1
 
Praesentation TYPO3Camp Berlin Speed mit Extbase
Praesentation TYPO3Camp Berlin Speed mit ExtbasePraesentation TYPO3Camp Berlin Speed mit Extbase
Praesentation TYPO3Camp Berlin Speed mit ExtbaseStefan Frömken
 
MicroProfile 2.x: Der alternative Standard
MicroProfile 2.x: Der alternative StandardMicroProfile 2.x: Der alternative Standard
MicroProfile 2.x: Der alternative StandardOPEN KNOWLEDGE GmbH
 
Elegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2day
Elegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2dayElegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2day
Elegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2dayMario-Leander Reimer
 
SOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter SystemeSOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter SystemeMario Rodler
 
Speeding up Java Persistence
Speeding up Java PersistenceSpeeding up Java Persistence
Speeding up Java Persistencegedoplan
 
Microservices mit Rust
Microservices mit RustMicroservices mit Rust
Microservices mit RustJens Siebert
 
Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!gedoplan
 
Anbindung von Silverlight an RESTful Web Services
Anbindung von Silverlight an RESTful Web ServicesAnbindung von Silverlight an RESTful Web Services
Anbindung von Silverlight an RESTful Web ServicesAndré Wussow
 
Clean mit visual studio
Clean mit visual studioClean mit visual studio
Clean mit visual studioHendrik Lösch
 
Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...
Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...
Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...GFU Cyrus AG
 
Android Development ...and the daily challenges
Android Development ...and the daily challengesAndroid Development ...and the daily challenges
Android Development ...and the daily challengesDominik Helleberg
 
Reaktive Applikationen mit Scala, Play und Akka
Reaktive Applikationen mit Scala, Play und AkkaReaktive Applikationen mit Scala, Play und Akka
Reaktive Applikationen mit Scala, Play und AkkaMarkus Klink
 

Similar to Hands-on Hystrix - Best Practices und Stolperfallen (20)

Lightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPALightweight AOP with CDI and JPA
Lightweight AOP with CDI and JPA
 
Cloud Native & Java EE: Freund oder Feind?
Cloud Native & Java EE: Freund oder Feind?Cloud Native & Java EE: Freund oder Feind?
Cloud Native & Java EE: Freund oder Feind?
 
Cloud Native und Java EE: Freund oder Feind?
Cloud Native und Java EE: Freund oder Feind?Cloud Native und Java EE: Freund oder Feind?
Cloud Native und Java EE: Freund oder Feind?
 
Camunda@1&1
Camunda@1&1Camunda@1&1
Camunda@1&1
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Praesentation TYPO3Camp Berlin Speed mit Extbase
Praesentation TYPO3Camp Berlin Speed mit ExtbasePraesentation TYPO3Camp Berlin Speed mit Extbase
Praesentation TYPO3Camp Berlin Speed mit Extbase
 
MicroProfile 2.x: Der alternative Standard
MicroProfile 2.x: Der alternative StandardMicroProfile 2.x: Der alternative Standard
MicroProfile 2.x: Der alternative Standard
 
Elegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2day
Elegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2dayElegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2day
Elegantes In-Memory Computing mit Apache Ignite und Kubernetes. @data2day
 
SOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter SystemeSOLID Prinzipien, Designgrundlagen objektorientierter Systeme
SOLID Prinzipien, Designgrundlagen objektorientierter Systeme
 
Speeding up Java Persistence
Speeding up Java PersistenceSpeeding up Java Persistence
Speeding up Java Persistence
 
Microservices mit Rust
Microservices mit RustMicroservices mit Rust
Microservices mit Rust
 
Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!Schnell, schneller, Quarkus!!
Schnell, schneller, Quarkus!!
 
Anbindung von Silverlight an RESTful Web Services
Anbindung von Silverlight an RESTful Web ServicesAnbindung von Silverlight an RESTful Web Services
Anbindung von Silverlight an RESTful Web Services
 
Clean mit visual studio
Clean mit visual studioClean mit visual studio
Clean mit visual studio
 
Einführung in React
Einführung in ReactEinführung in React
Einführung in React
 
T3ak12 extbase
T3ak12 extbaseT3ak12 extbase
T3ak12 extbase
 
GWT – Google Web Toolkit in der Praxis
GWT – Google Web Toolkit in der PraxisGWT – Google Web Toolkit in der Praxis
GWT – Google Web Toolkit in der Praxis
 
Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...
Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...
Java Code Quality: Gute Software braucht guten Code - Regeln für verständlich...
 
Android Development ...and the daily challenges
Android Development ...and the daily challengesAndroid Development ...and the daily challenges
Android Development ...and the daily challenges
 
Reaktive Applikationen mit Scala, Play und Akka
Reaktive Applikationen mit Scala, Play und AkkaReaktive Applikationen mit Scala, Play und Akka
Reaktive Applikationen mit Scala, Play und Akka
 

More from inovex GmbH

lldb – Debugger auf Abwegen
lldb – Debugger auf Abwegenlldb – Debugger auf Abwegen
lldb – Debugger auf Abwegeninovex GmbH
 
Are you sure about that?! Uncertainty Quantification in AI
Are you sure about that?! Uncertainty Quantification in AIAre you sure about that?! Uncertainty Quantification in AI
Are you sure about that?! Uncertainty Quantification in AIinovex GmbH
 
Why natural language is next step in the AI evolution
Why natural language is next step in the AI evolutionWhy natural language is next step in the AI evolution
Why natural language is next step in the AI evolutioninovex GmbH
 
Network Policies
Network PoliciesNetwork Policies
Network Policiesinovex GmbH
 
Interpretable Machine Learning
Interpretable Machine LearningInterpretable Machine Learning
Interpretable Machine Learninginovex GmbH
 
Jenkins X – CI/CD in wolkigen Umgebungen
Jenkins X – CI/CD in wolkigen UmgebungenJenkins X – CI/CD in wolkigen Umgebungen
Jenkins X – CI/CD in wolkigen Umgebungeninovex GmbH
 
AI auf Edge-Geraeten
AI auf Edge-GeraetenAI auf Edge-Geraeten
AI auf Edge-Geraeteninovex GmbH
 
Prometheus on Kubernetes
Prometheus on KubernetesPrometheus on Kubernetes
Prometheus on Kubernetesinovex GmbH
 
Deep Learning for Recommender Systems
Deep Learning for Recommender SystemsDeep Learning for Recommender Systems
Deep Learning for Recommender Systemsinovex GmbH
 
Representation Learning von Zeitreihen
Representation Learning von ZeitreihenRepresentation Learning von Zeitreihen
Representation Learning von Zeitreiheninovex GmbH
 
Talk to me – Chatbots und digitale Assistenten
Talk to me – Chatbots und digitale AssistentenTalk to me – Chatbots und digitale Assistenten
Talk to me – Chatbots und digitale Assistenteninovex GmbH
 
Künstlich intelligent?
Künstlich intelligent?Künstlich intelligent?
Künstlich intelligent?inovex GmbH
 
Das Android Open Source Project
Das Android Open Source ProjectDas Android Open Source Project
Das Android Open Source Projectinovex GmbH
 
Machine Learning Interpretability
Machine Learning InterpretabilityMachine Learning Interpretability
Machine Learning Interpretabilityinovex GmbH
 
Performance evaluation of GANs in a semisupervised OCR use case
Performance evaluation of GANs in a semisupervised OCR use casePerformance evaluation of GANs in a semisupervised OCR use case
Performance evaluation of GANs in a semisupervised OCR use caseinovex GmbH
 
People & Products – Lessons learned from the daily IT madness
People & Products – Lessons learned from the daily IT madnessPeople & Products – Lessons learned from the daily IT madness
People & Products – Lessons learned from the daily IT madnessinovex GmbH
 
Infrastructure as (real) Code – Manage your K8s resources with Pulumi
Infrastructure as (real) Code – Manage your K8s resources with PulumiInfrastructure as (real) Code – Manage your K8s resources with Pulumi
Infrastructure as (real) Code – Manage your K8s resources with Pulumiinovex GmbH
 

More from inovex GmbH (20)

lldb – Debugger auf Abwegen
lldb – Debugger auf Abwegenlldb – Debugger auf Abwegen
lldb – Debugger auf Abwegen
 
Are you sure about that?! Uncertainty Quantification in AI
Are you sure about that?! Uncertainty Quantification in AIAre you sure about that?! Uncertainty Quantification in AI
Are you sure about that?! Uncertainty Quantification in AI
 
Why natural language is next step in the AI evolution
Why natural language is next step in the AI evolutionWhy natural language is next step in the AI evolution
Why natural language is next step in the AI evolution
 
WWDC 2019 Recap
WWDC 2019 RecapWWDC 2019 Recap
WWDC 2019 Recap
 
Network Policies
Network PoliciesNetwork Policies
Network Policies
 
Interpretable Machine Learning
Interpretable Machine LearningInterpretable Machine Learning
Interpretable Machine Learning
 
Jenkins X – CI/CD in wolkigen Umgebungen
Jenkins X – CI/CD in wolkigen UmgebungenJenkins X – CI/CD in wolkigen Umgebungen
Jenkins X – CI/CD in wolkigen Umgebungen
 
AI auf Edge-Geraeten
AI auf Edge-GeraetenAI auf Edge-Geraeten
AI auf Edge-Geraeten
 
Prometheus on Kubernetes
Prometheus on KubernetesPrometheus on Kubernetes
Prometheus on Kubernetes
 
Deep Learning for Recommender Systems
Deep Learning for Recommender SystemsDeep Learning for Recommender Systems
Deep Learning for Recommender Systems
 
Azure IoT Edge
Azure IoT EdgeAzure IoT Edge
Azure IoT Edge
 
Representation Learning von Zeitreihen
Representation Learning von ZeitreihenRepresentation Learning von Zeitreihen
Representation Learning von Zeitreihen
 
Talk to me – Chatbots und digitale Assistenten
Talk to me – Chatbots und digitale AssistentenTalk to me – Chatbots und digitale Assistenten
Talk to me – Chatbots und digitale Assistenten
 
Künstlich intelligent?
Künstlich intelligent?Künstlich intelligent?
Künstlich intelligent?
 
Dev + Ops = Go
Dev + Ops = GoDev + Ops = Go
Dev + Ops = Go
 
Das Android Open Source Project
Das Android Open Source ProjectDas Android Open Source Project
Das Android Open Source Project
 
Machine Learning Interpretability
Machine Learning InterpretabilityMachine Learning Interpretability
Machine Learning Interpretability
 
Performance evaluation of GANs in a semisupervised OCR use case
Performance evaluation of GANs in a semisupervised OCR use casePerformance evaluation of GANs in a semisupervised OCR use case
Performance evaluation of GANs in a semisupervised OCR use case
 
People & Products – Lessons learned from the daily IT madness
People & Products – Lessons learned from the daily IT madnessPeople & Products – Lessons learned from the daily IT madness
People & Products – Lessons learned from the daily IT madness
 
Infrastructure as (real) Code – Manage your K8s resources with Pulumi
Infrastructure as (real) Code – Manage your K8s resources with PulumiInfrastructure as (real) Code – Manage your K8s resources with Pulumi
Infrastructure as (real) Code – Manage your K8s resources with Pulumi
 

Hands-on Hystrix - Best Practices und Stolperfallen

  • 2. WER ERZÄHLT DIE NÄCHSTEN 50+ MINUTEN ETWAS? Gerrit Brehmer, Karlsruhe Auf der Arbeit: So ware-Entwickler/Architekt bei der inovex GmbH In der Freizeit: Meine Tochter & Smart Home
  • 3. REPRESENTATIVE UMFRAGE Wer hat Hystrix schon im Produktiv-Einsatz oder plant es in Kürze?
  • 4. WARUM IST ROBUSTHEIT WICHTIG? Michael Nygard über den Alltag bei mittleren bis großen SW-Systemen: “The normal mode of operation is partial failure.“
  • 6. VORAB: HÄUFIGES (ANTI-)PATTERN @Transactional @RequestMapping("api") public ResponseEntity updateUser(UserData data) { validate(data); // DB checkWithExternalService(data); // Extern Entity updatedUsed = saveToDb(data); // DB return toResponseEntity(updatedUsed); // DB / DTO } DB-Transaktion/Verbindung so kurz wie möglich Wartende Requests blockieren kostbare Ressourcen Böse: OpenSessionInViewFilter
  • 7. VERURSACHER VON AUSFÄLLEN Teilausfälle Hardware So ware Fehlerkaskaden Laufzeitprobleme Last-Peaks
  • 8. ABHÄNGIGKEITEN IM GRIFF Nichtfunktionale Anforderungen an den eigenen Dienst an und von externen Diensten SLAs (leider viel zu selten vorhanden) Entkopplung & Isolation Ziele: Eine robuste und fehlertolerante Anwendung Die beste Fehlerbehandlung ist die, von der der Nutzer nichts mitbekommt
  • 9. ENTKOPPLUNG - USE CASE #1 Berechnung von kundenspezifischen Empfehlungen durch ein entferntes System enge Integration in einen Großteil der Seiten Fehler/Timeouts schlagen sofort auf diese Seiten durch Lösung mit Hystrix: Alternative Empfehlungen auf Basis von statischen Regeln/einfachen Filtern (kein entferntes System) im Fehlerfall
  • 10. ERGEBNIS OHNE HYSTRIX @Inject RecoService recoClient; public Movies getReco(long customerId) { return recoClient.getMovies(customerId); }
  • 11. ERGEBNIS MIT HYSTRIX STATISCHER FALLBACK public class RecoForCustomerCommand extends HystrixCommand<Movies> { ... public RecoForCustomerCommand(RecoService recoClient, long customerId) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Reco")) .andCommandKey(HystrixCommandKey.Factory.asKey("RecoForCustomer")) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RecoTP"))); this.recoClient = recoClient; this.customerId = customerId; } @Override protected Movies run() { return recoClient.getMovies(customerId); } @Override protected Movies getFallback() { return Movies.EMPTY_LIST; } } public Movies getReco(long customerId) { return new RecoForCustomerCommand(recoClient, customerId).execute(); }
  • 12. ERGEBNIS MIT HYSTRIX DYNAMISCHER FALLBACK public class RecoForCustomerCommand extends HystrixCommand<Movies> { ... public RecoForCustomerCommand(RecoService recoClient, long custId) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Reco")) .andCommandKey(HystrixCommandKey.Factory.asKey("RecoForCustomer")) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("RecoTP"))); this.recoClient = recoClient; this.customerId = custId; } @Override protected Movies run() { return recoClient.getMovies(customerId); } @Override protected Movies getFallback() { return InternalRecoClient.getTopMovies(); } } public Movies getReco(long customerId) { return new RecoForCustomerCommand(recoService, customerId).execute(); }
  • 13. ENTKOPPLUNG - USE CASE #2 Fehler-Kaskaden: Laufzeit-Probleme wirken sich auch auf aufrufende Systeme aus begrenzte Ressourcen werden gebunden Aufwand für Connection- Handling steigt rapide Seiteneffekte in andere Systeme
  • 14. ENTKOPPLUNG - USE CASE #2 Lösung mit Hystrix: Direkte Fehlerrückgabe Verhindert weitere Laufzeitprobleme
  • 15. HYSTRIX PATTERNS Implementierung diverser Resilience Patterns Graceful degradation (Use Case 1) Fail Fast (Use case 2) Fail silent Bulkheading Circuit Breaker
  • 17. PITFALLS WENN DA NICHT DIE PRAXIS WÄRE...
  • 18. THREAD-POOLS ODER SEMAPHOREN Thread Pools können zwischen mehreren Commands geshared werden bessere Isolierung spürbarer Overhead (0-9ms, ø 1ms) Thread-Pools verhindern nicht, dass Aufrufe dauerha blockieren Java Threads können nicht gesichert beendet werden Komplexer in der Implementierung Timeouts setzen - immer und überall Nicht blockierende APIs verwenden (Java NIO Channel, Netty) Thread.currentThread().isInterrupted() nutzen
  • 19. THREAD-POOLS ODER SEMAPHOREN Semaphoren minimaler Overhead Timeouts ab Hystrix 1.4 ... Aber: Ausführungsdauer wird nicht verringert (Caller-Thread) Fallback wird in einem extra Thread ausgeführt, wenn Timeout erreicht wird Fallback-Rückgabe erst mit Abschluss Caller-Thread Empfehlung für Aufrufe mit minimaler Latenz
  • 20. EINSCHRÄNKUNGEN DURCH THREADPOOLS ThreadLocals stehen nicht zur Verfügung MDC / NDC Log Kontexte (DB-)Transaktionsstatus Aktueller HTTP Request / Security Context Thread gebundene DI-Scopes (RequestScope, ThreadScope)
  • 21. LÖSUNG THREADLOCAL Custom ConcurrencyStrategy public class CustomStrategy extends HystrixConcurrencyStrategy { @Override public <T> Callable<T> wrapCallable(final Callable<T> callable) { final Map context = MDC.getContext(); final RequestAttributes attr = RequestContextHolder.get(); return super.wrapCallable(new Callable<T>() { @Override public T call() throws Exception { try { MDC.replaceAll(context); RequestContextHolder.set(attr); return callable.call(); } finally { RequestContextHolder.resetRequestAttributes(); MDC.clear(); } ... HystrixPlugins.getInstance().registerConcurrencyStrategy(new CustomStrategy());
  • 22. EINSATZ IN SERVLET-/JEE CONTAINERN Dynamisches Deployment statt Container Restart Potentielle Resource Leaks Lösung: Hystrix.reset() Servlet listener Shutdown Hook Singelton @PreDestroy-Methode
  • 23. EXCEPTIONHANDLING Hystrix Standard: Unchecked Exceptions Eigene werden in HystrixRuntimeExceptions gewrappt Kompatibilität Legacy Code Neue Fehlerfälle Timeout durch Hystrix Offener Circuit, Pool ausgelastet Sonderfall HystrixBadRequestException Stellt fehlerha e Anfrage dar Kein Fallback Keine Fehler-Statistik
  • 24. EXCEPTIONS: ABWÄRTSKOMPATIBILITÄT public abstract class LegacyCommand extends HystrixCommand { ... public T executeWithCheckedEx() throws CheckedIOException { try { return super.execute(); } catch (RuntimeException e) { if (isCircuitBreakerOpen() || isResponseRejected() || isResponseTimedOut() || isResponseShortCircuited()) { throw new CheckedIOException("req. aborted:"+e.getMessage()); } else if (e.getCause() instanceof CheckedIOException) { throw (CheckedIOException) e.getCause(); } else { throw e; } } }
  • 25. HYSTRIX-ANNOTATIONS: JAVANICA Aspekt zur Erstellung von HystrixCommands zur Laufzeit Interceptoren & andere Aspekte greifen nicht! Konfiguration per Annotation Einschränkung zur Laufzeit & Wiederverwendbarkeit Implizite Regeln (Convention over Configuration) Exception-Handling anders Exceptiontypen können ignoriert werden und werden ohne "Verpackung" zurückgeworfen Exceptionhandling ansonsten identisch Änderung Exception Handling durch Anpassung HystrixCommandAspect
  • 26. HYSTRIX/(NETFLIX)-INTEGRATION MIT SPRING Spring Cloud Netflix Features per Annotation in der JavaConfig aktivieren Javanica Aktivierung & ShutdownHook Hystrix Event Stream Hystrix Dashboard Hystrix Turbine (auf Cloud Anwendung spezialisiert) Integration mit weiteren Netflix Bibliotheken (Heureka, Zuul, Ribbon,..)
  • 27. MICROSERVICES & HYSTRIX Netflix einer der großen Treiber der Microservice Architektur Hystrix wird hauptsächlich in deren API Gateways eingesetzt Reduzierung der Requests Handling vieler Abhängigkeiten Parallele Verarbeitung (RxJava) Weitere Optimierungen: RequestCollapser RequestCache
  • 28. DEMO JHipster Stack als API Gateway Angular JS / Bootstrap Spring Boot Hystrix Drei simple REST Microservices (Spring Boot) Monitoring Hystrix Dashboard Kibana Dashboard (ELK)
  • 29. FAZIT & AUSBLICK Hystrix Entkopplung und Isolierung leicht gemacht Neue Version bringt weitere Features und Verbesserungen Dennoch: Komplexität mit Hystrix ist nicht zu unterschätzen Hystrix für Microservices Bei Inter-Service Kommunikation Integration externer Dienste API Gateway
  • 30. BILDERVERZEICHNIS Hystrix Patterns: https://www.flickr.com/photos/ramnaganat/7154180752 Circuit Breaker: http://martinfowler.com/bliki/CircuitBreaker.html Pitfalls: https://www.flickr.com/photos/nafmo/1488330724
  • 31. VIELEN DANK FÜR EURE AUFMERKSAMKEIT!