SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
Reactive Applications in Java
Alex Mrynskyi
Palo Alto Networks
Our Team
Agenda
● The Problem
● What is Reactive Applications?
● Project Reactor 101
● How to Start with Reactive?
Why Reactive?
Today’s Challenges
Today applications are deployed on everything from mobile devices to cloud-based
clusters running thousands of multi-core processors. Users expect millisecond
response times and 100% uptime. Data is measured in Petabytes. Today's demands are
simply not met by yesterday’s software architectures.
Reactive Matifesto, 2014
The Rise of Microservices
The Rise of Microservices
Our Challenges
● Continuously process huge number of events, messages, files
● I/O bound workloads (HTTP requests, DB access, etc)
● Rate limiting from external systems
● Many microservices that interact with each other
Synchronous vs Asynchronous
Event Loop
Little's Law
Little's law, Wikipedia
long-term average number L of customers in a stationary system is equal to
the long-term average effective arrival rate λ multiplied by the average time
W that a customer spends in the system
Little's Law in Practice
Stop Rate Limiting! Capacity Management Done Right" by Jon Moore, Youtube
The number of active workers must be at least the average arrival rate of tasks multiplied by the average time to process
those tasks
workers >= tasks per second x time to process task
or
workers >= throughput x latency
or
throughput <= workers / latency
Web MVC with Blocking I/O
WebFlux with Non-Blocking I/O
Web MVC with Blocking I/O (multiple threads)
Web MVC vs WebFlux
Source - Hands-On Reactive Programming in Spring 5
Conclusion - WebFlux is much more efficient with regard to throughput, latency, and CPU usage.
Reactive Applications
Photo by Brayden Law from Pexels
Reactive Glossary
“Reactive” has become an overloaded term and is now being associated with several different
things to different people
● Reactive programming is a paradigm in which declarative code is issued to construct
asynchronous processing pipelines
● Reactive streams is an initiative that was created to provide a standard to unify reactive
extensions and deal with asynchronous stream processing with non-blocking backpressure
● Reactive systems—as defined by the Reactive Manifesto—is a set of architectural design
principles for building modern systems that are well prepared to meet the increasing demands
that applications face today
● Reactive programming and Reactive streams are all useful tools to design and build Reactive
systems
Reactive programming vs. Reactive systems
Reactive Manifesto
Reactive Systems
● Responsive - low latency
● Resilient - stay responsive on failures
● Elastic - scale as needed
● Message Driven - async messages for communication between components
Reactive Streams
Photo by Avery Nielsen-Webb from Pexels
Reactive Streams API
public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {}
public interface Publisher<T> {
public void subscribe(Subscriber<? super T> s);
}
public interface Subscriber<T> {
public void onSubscribe(Subscription s);
public void onNext(T t);
public void onError(Throwable t);
public void onComplete();
}
public interface Subscription {
public void request(long n);
public void cancel();
}
Don’t try it at home!!!
Reactive Signals
Photo by Avery Nielsen-Webb from Pexels
Reactive Streams Implementations
● RxJava (Netflix)
● Reactor (Pivotal)
● Vert.x (RedHat)
● Akka Streams (Typesafe)
Project Reactor
Photo by Avery Nielsen-Webb from Pexels
Project Reactor
Photo by Avery Nielsen-Webb from Pexels
● Reactor is a fourth-generation reactive library, based on the Reactive Streams
specification, for building non-blocking applications on the JVM
● Fully non-blocking and backpressure-ready network runtimes, including local
TCP/HTTP/UDP clients and servers, based on the robust Netty framework
● Foundation of the reactive stack in the Spring ecosystem and is featured in projects
such as Spring WebFlux, Spring Data, and Spring Cloud Gateway
Reactive Stack in Spring Boot
Web on Reactive Stack
● WebFlux is a non-blocking web stack to handle concurrency with a small number of
threads and scale with fewer hardware resources
● Uses Reactor Netty by default
● Supports two programming models
○ Annotated Controllers: Consistent with Spring MVC and based on the same annotations from the spring-web module
○ Functional Endpoints: Lambda-based, lightweight, and functional programming model
Reactive Libraries and Clients
● MongoDB, Redis, and Cassandra all have native reactive support in Spring Data
● Many relational databases (Postgres, Microsoft SQL Server, MySQL, H2, and Google
Spanner) have reactive support via R2DBC
● Reactor Kafka and Reactor RabbitMQ for messaging
● AWS SDK v2 is fully asynchronous and could be easily wrapped
● WebClient with functional, fluent API based on Reactor
● Resilience4j for Circuit Breaker, Rate Limiter, Retry or Bulkhead in a reactive way
Project Reactor 101
Photo by Avery Nielsen-Webb from Pexels
Photo by Ekaterina Belinskaya from Pexels
Flux
An Asynchronous Sequence of 0-N Items
Mono
An Asynchronous 0-1 Result
Marble Diagrams
Photo by Avery Nielsen-Webb from Pexels
Appendix B: How to read marble diagrams?
Operators
● .map, .filter, .flatMap, .take, .buffer, .subscribe, ....
● Not a part of Reactive Streams specification
Appendix A: Which operator do I need?
Assembly vs Subscription
Photo by Avery Nielsen-Webb from Pexels
Nothing Happens Until You Subscribe
Flight of the Flux 1 - Assembly vs Subscription
● Calling methods on a Flux or Mono (the operators) doesn’t immediately trigger the
behavior. This declarative phase is called assembly time.
● To trigger data to flow we you need to subscribe to the declared pipeline
Demo Time
Photo by Avery Nielsen-Webb from Pexels
Photo by PRAPHAPHAN WONGSAWAN from Pexels
flatMap
Photo by Avery Nielsen-Webb from Pexels
“flatMap Pack”
Photo by Avery Nielsen-Webb from Pexels
● .flatMap()/.flatMapMany() - transforms the elements asynchronously into Publishers,
then flatten these inner publishers into a single Flux through merging
● .concatMap() - transforms the elements asynchronously into Publishers, then flatten
these inner publishers into a single Flux, sequentially and preserving order using
concatenation
● .flatMapSequential() - transforms the elements asynchronously into Publishers, then
flatten these inner publishers into a single Flux, but merge them in the order of their
source element
Threading Model
Photo by Avery Nielsen-Webb from Pexels
● considered to be concurrency-agnostic
● Schedulers.parallel()
○ non-blocking operations
○ fixed size
○ number of of threads = number CPU cores
● Schedulers.boundedElastic()
○ usually used to offload blocking operations
○ creates new worker pools as needed and reuses idle ones
○ number of of threads = number of CPU cores x 10
● Schedulers.single()
○ a single, reusable thread
Flight of the Flux 3 - Hopping Threads and Schedulers
Wrapping Blocking Code
Photo by Avery Nielsen-Webb from Pexels
● Reactor offers two means of switching the execution context (or Scheduler) in a
reactive chain: publishOn and subscribeOn
Error Handling and Resiliency
Photo by Avery Nielsen-Webb from Pexels
● .retry()/.retryWhen() - retry subscription on failure
● .repeat()/.repeatWhen() - repeat (resubscribe) on empty result
● .defaultIfEmpty()/.switchIfEmpty() - fallback on empty
● .onErrorResume()/.onErrorReturn() - fallback on error
● .timeout(Duration) - cancel the subscription and fail if no items emitted
A.5. Handling Errors
Testing
Photo by Avery Nielsen-Webb from Pexels
Debug and Troubleshooting
Photo by Avery Nielsen-Webb from Pexels
Flight of the Flux 2 - Debugging Caveats
● Stack traces in Reactive world could veeeeeeery long and not informative
Debug and Troubleshooting
Photo by Avery Nielsen-Webb from Pexels
Flight of the Flux 2 - Debugging Caveats
● Integrate ReactorDebugAgent - a Java agent which helps debugging exceptions in
your application without paying a runtime cost (unlike Hooks.onOperatorDebug())
○ Hooks.onOperatorDebug() is still really useful in tests
● Use .log() and .checkpoint() operators in development to understand the flow
● Integrate BlockHound into tests to detect blocking code (tests only !!!)
Reactive “Laws”
Photo by Avery Nielsen-Webb from Pexels
● NOTHING happens until you subscribe
○ Idialy subscribe only once
● NEVER block parallel scheduler
○ Run blocking code on a separate Scheduler (i.e. boundedElastic)
● STOP thinking in threads
○ Think about concurrency instead
Learning Resources - Intro
Photo by Avery Nielsen-Webb from Pexels
● Video Flight of the Flux: A Look at Reactor Execution Model
● Blog series Flight of the Flux 1 - Assembly vs Subscription
● Video Avoiding Reactor Meltdown
● Video Do’s and Don’ts: Avoiding First-Time Reactive Programmer Mines - must
● The introduction to Reactive Programming you've been missing - not java but very
good explanation of the idea behind reactive programming
Learning Resources - Hands-on
Photo by Avery Nielsen-Webb from Pexels
● Introduction to Reactive Programming or the same on github GitHub -
reactor/lite-rx-api-hands-on: Lite Rx API Hands-On with Reactor Core 3. Just get
repo and fix all unit tests
● Head-First Reactive Workshop GitHub -
reactor/head-first-reactive-with-spring-and-reactor
Learning Resources - Hardcore
Photo by Avery Nielsen-Webb from Pexels
3-video series about Reactor internals
● https:/
/www.youtube.com/watch?v=OdSZ6mOQDcY
● https:/
/www.youtube.com/watch?v=noeWdjO4fyU
● https:/
/www.youtube.com/watch?v=cVKhFPiebSs

Weitere ähnliche Inhalte

Was ist angesagt?

Akka streams - Umeå java usergroup
Akka streams - Umeå java usergroupAkka streams - Umeå java usergroup
Akka streams - Umeå java usergroupJohan Andrén
 
Asynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsJohan Andrén
 
Scala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streamsScala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streamsJohan Andrén
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConfJohan Andrén
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentationGene Chang
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka StreamsKonrad Malawski
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsKonrad Malawski
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsKevin Webber
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayRoland Kuhn
 
End to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to SocketEnd to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to SocketKonrad Malawski
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJavaJobaer Chowdhury
 
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Lightbend
 
A dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioA dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioGioia Ballin
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Konrad Malawski
 
VJUG24 - Reactive Integrations with Akka Streams
VJUG24  - Reactive Integrations with Akka StreamsVJUG24  - Reactive Integrations with Akka Streams
VJUG24 - Reactive Integrations with Akka StreamsJohan Andrén
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTPRoland Kuhn
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for androidEsa Firman
 
Using akka streams to access s3 objects
Using akka streams to access s3 objectsUsing akka streams to access s3 objects
Using akka streams to access s3 objectsMikhail Girkin
 
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...Codemotion
 

Was ist angesagt? (20)

Akka streams - Umeå java usergroup
Akka streams - Umeå java usergroupAkka streams - Umeå java usergroup
Akka streams - Umeå java usergroup
 
Asynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka StreamsAsynchronous stream processing with Akka Streams
Asynchronous stream processing with Akka Streams
 
Scala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streamsScala usergroup stockholm - reactive integrations with akka streams
Scala usergroup stockholm - reactive integrations with akka streams
 
Async - react, don't wait - PingConf
Async - react, don't wait - PingConfAsync - react, don't wait - PingConf
Async - react, don't wait - PingConf
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Reactive integrations with Akka Streams
Reactive integrations with Akka StreamsReactive integrations with Akka Streams
Reactive integrations with Akka Streams
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
 
Journey into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka StreamsJourney into Reactive Streams and Akka Streams
Journey into Reactive Streams and Akka Streams
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive Way
 
End to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to SocketEnd to End Akka Streams / Reactive Streams - from Business to Socket
End to End Akka Streams / Reactive Streams - from Business to Socket
 
Reactive programming with RxJava
Reactive programming with RxJavaReactive programming with RxJava
Reactive programming with RxJava
 
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
Build Real-Time Streaming ETL Pipelines With Akka Streams, Alpakka And Apache...
 
A dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenarioA dive into akka streams: from the basics to a real-world scenario
A dive into akka streams: from the basics to a real-world scenario
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014
 
VJUG24 - Reactive Integrations with Akka Streams
VJUG24  - Reactive Integrations with Akka StreamsVJUG24  - Reactive Integrations with Akka Streams
VJUG24 - Reactive Integrations with Akka Streams
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTP
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
Using akka streams to access s3 objects
Using akka streams to access s3 objectsUsing akka streams to access s3 objects
Using akka streams to access s3 objects
 
Akka streams
Akka streamsAkka streams
Akka streams
 
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
 

Ähnlich wie Reactive Applications in Java

Reactive microservices with eclipse vert.x
Reactive microservices with eclipse vert.xReactive microservices with eclipse vert.x
Reactive microservices with eclipse vert.xRam Maddali
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorVMware Tanzu
 
App Mod 04: Reactive microservices with eclipse vert.x
App Mod 04: Reactive microservices with eclipse vert.xApp Mod 04: Reactive microservices with eclipse vert.x
App Mod 04: Reactive microservices with eclipse vert.xJudy Breedlove
 
reactive_programming_for_java_developers.pdf
reactive_programming_for_java_developers.pdfreactive_programming_for_java_developers.pdf
reactive_programming_for_java_developers.pdfAkshitkumar437417
 
From Streams to Reactive Streams
From Streams to Reactive StreamsFrom Streams to Reactive Streams
From Streams to Reactive StreamsOleg Tsal-Tsalko
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingSUDIP GHOSH
 
Reactive applications tools of the trade huff po
Reactive applications   tools of the trade huff poReactive applications   tools of the trade huff po
Reactive applications tools of the trade huff poshinolajla
 
20160609 nike techtalks reactive applications tools of the trade
20160609 nike techtalks reactive applications   tools of the trade20160609 nike techtalks reactive applications   tools of the trade
20160609 nike techtalks reactive applications tools of the tradeshinolajla
 
Building RESTFUL APIs with Spring Webflux
Building RESTFUL APIs with Spring WebfluxBuilding RESTFUL APIs with Spring Webflux
Building RESTFUL APIs with Spring WebfluxKnoldus Inc.
 
Streaming to a New Jakarta EE
Streaming to a New Jakarta EEStreaming to a New Jakarta EE
Streaming to a New Jakarta EEJ On The Beach
 
Streaming to a new Jakarta EE
Streaming to a new Jakarta EEStreaming to a new Jakarta EE
Streaming to a new Jakarta EEMarkus Eisele
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootVMware Tanzu
 
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...MskDotNet Community
 
Guide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxGuide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxInexture Solutions
 
Solve it Differently with Reactive Programming
Solve it Differently with Reactive ProgrammingSolve it Differently with Reactive Programming
Solve it Differently with Reactive ProgrammingSupun Dissanayake
 
Going Reactive with Spring 5
Going Reactive with Spring 5Going Reactive with Spring 5
Going Reactive with Spring 5Drazen Nikolic
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 

Ähnlich wie Reactive Applications in Java (20)

Reactive microservices with eclipse vert.x
Reactive microservices with eclipse vert.xReactive microservices with eclipse vert.x
Reactive microservices with eclipse vert.x
 
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project ReactorReactive Card Magic: Understanding Spring WebFlux and Project Reactor
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
 
App Mod 04: Reactive microservices with eclipse vert.x
App Mod 04: Reactive microservices with eclipse vert.xApp Mod 04: Reactive microservices with eclipse vert.x
App Mod 04: Reactive microservices with eclipse vert.x
 
reactive_programming_for_java_developers.pdf
reactive_programming_for_java_developers.pdfreactive_programming_for_java_developers.pdf
reactive_programming_for_java_developers.pdf
 
From Streams to Reactive Streams
From Streams to Reactive StreamsFrom Streams to Reactive Streams
From Streams to Reactive Streams
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
Reactive applications tools of the trade huff po
Reactive applications   tools of the trade huff poReactive applications   tools of the trade huff po
Reactive applications tools of the trade huff po
 
20160609 nike techtalks reactive applications tools of the trade
20160609 nike techtalks reactive applications   tools of the trade20160609 nike techtalks reactive applications   tools of the trade
20160609 nike techtalks reactive applications tools of the trade
 
Building RESTFUL APIs with Spring Webflux
Building RESTFUL APIs with Spring WebfluxBuilding RESTFUL APIs with Spring Webflux
Building RESTFUL APIs with Spring Webflux
 
Streaming to a New Jakarta EE
Streaming to a New Jakarta EEStreaming to a New Jakarta EE
Streaming to a New Jakarta EE
 
Streaming to a new Jakarta EE
Streaming to a new Jakarta EEStreaming to a new Jakarta EE
Streaming to a new Jakarta EE
 
Reactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring BootReactive Applications with Apache Pulsar and Spring Boot
Reactive Applications with Apache Pulsar and Spring Boot
 
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...Дмитрий Тежельников  «Разработка вэб-решений с использованием Asp.NET.Core и ...
Дмитрий Тежельников «Разработка вэб-решений с использованием Asp.NET.Core и ...
 
Guide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFluxGuide to Spring Reactive Programming using WebFlux
Guide to Spring Reactive Programming using WebFlux
 
Solve it Differently with Reactive Programming
Solve it Differently with Reactive ProgrammingSolve it Differently with Reactive Programming
Solve it Differently with Reactive Programming
 
Spring reactor
Spring reactorSpring reactor
Spring reactor
 
Going Reactive with Spring 5
Going Reactive with Spring 5Going Reactive with Spring 5
Going Reactive with Spring 5
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Reactive systems
Reactive systemsReactive systems
Reactive systems
 

Kürzlich hochgeladen

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
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.pdfryanfarris8
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 

Kürzlich hochgeladen (20)

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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
 
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
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 

Reactive Applications in Java

  • 1. Reactive Applications in Java Alex Mrynskyi Palo Alto Networks
  • 3. Agenda ● The Problem ● What is Reactive Applications? ● Project Reactor 101 ● How to Start with Reactive?
  • 5. Today’s Challenges Today applications are deployed on everything from mobile devices to cloud-based clusters running thousands of multi-core processors. Users expect millisecond response times and 100% uptime. Data is measured in Petabytes. Today's demands are simply not met by yesterday’s software architectures. Reactive Matifesto, 2014
  • 6. The Rise of Microservices
  • 7. The Rise of Microservices
  • 8. Our Challenges ● Continuously process huge number of events, messages, files ● I/O bound workloads (HTTP requests, DB access, etc) ● Rate limiting from external systems ● Many microservices that interact with each other
  • 11. Little's Law Little's law, Wikipedia long-term average number L of customers in a stationary system is equal to the long-term average effective arrival rate λ multiplied by the average time W that a customer spends in the system
  • 12. Little's Law in Practice Stop Rate Limiting! Capacity Management Done Right" by Jon Moore, Youtube The number of active workers must be at least the average arrival rate of tasks multiplied by the average time to process those tasks workers >= tasks per second x time to process task or workers >= throughput x latency or throughput <= workers / latency
  • 13. Web MVC with Blocking I/O
  • 15. Web MVC with Blocking I/O (multiple threads)
  • 16. Web MVC vs WebFlux Source - Hands-On Reactive Programming in Spring 5 Conclusion - WebFlux is much more efficient with regard to throughput, latency, and CPU usage.
  • 17. Reactive Applications Photo by Brayden Law from Pexels
  • 18. Reactive Glossary “Reactive” has become an overloaded term and is now being associated with several different things to different people ● Reactive programming is a paradigm in which declarative code is issued to construct asynchronous processing pipelines ● Reactive streams is an initiative that was created to provide a standard to unify reactive extensions and deal with asynchronous stream processing with non-blocking backpressure ● Reactive systems—as defined by the Reactive Manifesto—is a set of architectural design principles for building modern systems that are well prepared to meet the increasing demands that applications face today ● Reactive programming and Reactive streams are all useful tools to design and build Reactive systems Reactive programming vs. Reactive systems
  • 20. Reactive Systems ● Responsive - low latency ● Resilient - stay responsive on failures ● Elastic - scale as needed ● Message Driven - async messages for communication between components
  • 21. Reactive Streams Photo by Avery Nielsen-Webb from Pexels
  • 22. Reactive Streams API public interface Processor<T, R> extends Subscriber<T>, Publisher<R> {} public interface Publisher<T> { public void subscribe(Subscriber<? super T> s); } public interface Subscriber<T> { public void onSubscribe(Subscription s); public void onNext(T t); public void onError(Throwable t); public void onComplete(); } public interface Subscription { public void request(long n); public void cancel(); } Don’t try it at home!!!
  • 23. Reactive Signals Photo by Avery Nielsen-Webb from Pexels
  • 24. Reactive Streams Implementations ● RxJava (Netflix) ● Reactor (Pivotal) ● Vert.x (RedHat) ● Akka Streams (Typesafe)
  • 25. Project Reactor Photo by Avery Nielsen-Webb from Pexels
  • 26. Project Reactor Photo by Avery Nielsen-Webb from Pexels ● Reactor is a fourth-generation reactive library, based on the Reactive Streams specification, for building non-blocking applications on the JVM ● Fully non-blocking and backpressure-ready network runtimes, including local TCP/HTTP/UDP clients and servers, based on the robust Netty framework ● Foundation of the reactive stack in the Spring ecosystem and is featured in projects such as Spring WebFlux, Spring Data, and Spring Cloud Gateway
  • 27. Reactive Stack in Spring Boot
  • 28. Web on Reactive Stack ● WebFlux is a non-blocking web stack to handle concurrency with a small number of threads and scale with fewer hardware resources ● Uses Reactor Netty by default ● Supports two programming models ○ Annotated Controllers: Consistent with Spring MVC and based on the same annotations from the spring-web module ○ Functional Endpoints: Lambda-based, lightweight, and functional programming model
  • 29. Reactive Libraries and Clients ● MongoDB, Redis, and Cassandra all have native reactive support in Spring Data ● Many relational databases (Postgres, Microsoft SQL Server, MySQL, H2, and Google Spanner) have reactive support via R2DBC ● Reactor Kafka and Reactor RabbitMQ for messaging ● AWS SDK v2 is fully asynchronous and could be easily wrapped ● WebClient with functional, fluent API based on Reactor ● Resilience4j for Circuit Breaker, Rate Limiter, Retry or Bulkhead in a reactive way
  • 30. Project Reactor 101 Photo by Avery Nielsen-Webb from Pexels Photo by Ekaterina Belinskaya from Pexels
  • 33. Marble Diagrams Photo by Avery Nielsen-Webb from Pexels Appendix B: How to read marble diagrams?
  • 34. Operators ● .map, .filter, .flatMap, .take, .buffer, .subscribe, .... ● Not a part of Reactive Streams specification Appendix A: Which operator do I need?
  • 35. Assembly vs Subscription Photo by Avery Nielsen-Webb from Pexels Nothing Happens Until You Subscribe Flight of the Flux 1 - Assembly vs Subscription ● Calling methods on a Flux or Mono (the operators) doesn’t immediately trigger the behavior. This declarative phase is called assembly time. ● To trigger data to flow we you need to subscribe to the declared pipeline
  • 36. Demo Time Photo by Avery Nielsen-Webb from Pexels Photo by PRAPHAPHAN WONGSAWAN from Pexels
  • 37. flatMap Photo by Avery Nielsen-Webb from Pexels
  • 38. “flatMap Pack” Photo by Avery Nielsen-Webb from Pexels ● .flatMap()/.flatMapMany() - transforms the elements asynchronously into Publishers, then flatten these inner publishers into a single Flux through merging ● .concatMap() - transforms the elements asynchronously into Publishers, then flatten these inner publishers into a single Flux, sequentially and preserving order using concatenation ● .flatMapSequential() - transforms the elements asynchronously into Publishers, then flatten these inner publishers into a single Flux, but merge them in the order of their source element
  • 39. Threading Model Photo by Avery Nielsen-Webb from Pexels ● considered to be concurrency-agnostic ● Schedulers.parallel() ○ non-blocking operations ○ fixed size ○ number of of threads = number CPU cores ● Schedulers.boundedElastic() ○ usually used to offload blocking operations ○ creates new worker pools as needed and reuses idle ones ○ number of of threads = number of CPU cores x 10 ● Schedulers.single() ○ a single, reusable thread Flight of the Flux 3 - Hopping Threads and Schedulers
  • 40. Wrapping Blocking Code Photo by Avery Nielsen-Webb from Pexels ● Reactor offers two means of switching the execution context (or Scheduler) in a reactive chain: publishOn and subscribeOn
  • 41. Error Handling and Resiliency Photo by Avery Nielsen-Webb from Pexels ● .retry()/.retryWhen() - retry subscription on failure ● .repeat()/.repeatWhen() - repeat (resubscribe) on empty result ● .defaultIfEmpty()/.switchIfEmpty() - fallback on empty ● .onErrorResume()/.onErrorReturn() - fallback on error ● .timeout(Duration) - cancel the subscription and fail if no items emitted A.5. Handling Errors
  • 42. Testing Photo by Avery Nielsen-Webb from Pexels
  • 43. Debug and Troubleshooting Photo by Avery Nielsen-Webb from Pexels Flight of the Flux 2 - Debugging Caveats ● Stack traces in Reactive world could veeeeeeery long and not informative
  • 44. Debug and Troubleshooting Photo by Avery Nielsen-Webb from Pexels Flight of the Flux 2 - Debugging Caveats ● Integrate ReactorDebugAgent - a Java agent which helps debugging exceptions in your application without paying a runtime cost (unlike Hooks.onOperatorDebug()) ○ Hooks.onOperatorDebug() is still really useful in tests ● Use .log() and .checkpoint() operators in development to understand the flow ● Integrate BlockHound into tests to detect blocking code (tests only !!!)
  • 45. Reactive “Laws” Photo by Avery Nielsen-Webb from Pexels ● NOTHING happens until you subscribe ○ Idialy subscribe only once ● NEVER block parallel scheduler ○ Run blocking code on a separate Scheduler (i.e. boundedElastic) ● STOP thinking in threads ○ Think about concurrency instead
  • 46. Learning Resources - Intro Photo by Avery Nielsen-Webb from Pexels ● Video Flight of the Flux: A Look at Reactor Execution Model ● Blog series Flight of the Flux 1 - Assembly vs Subscription ● Video Avoiding Reactor Meltdown ● Video Do’s and Don’ts: Avoiding First-Time Reactive Programmer Mines - must ● The introduction to Reactive Programming you've been missing - not java but very good explanation of the idea behind reactive programming
  • 47. Learning Resources - Hands-on Photo by Avery Nielsen-Webb from Pexels ● Introduction to Reactive Programming or the same on github GitHub - reactor/lite-rx-api-hands-on: Lite Rx API Hands-On with Reactor Core 3. Just get repo and fix all unit tests ● Head-First Reactive Workshop GitHub - reactor/head-first-reactive-with-spring-and-reactor
  • 48. Learning Resources - Hardcore Photo by Avery Nielsen-Webb from Pexels 3-video series about Reactor internals ● https:/ /www.youtube.com/watch?v=OdSZ6mOQDcY ● https:/ /www.youtube.com/watch?v=noeWdjO4fyU ● https:/ /www.youtube.com/watch?v=cVKhFPiebSs