SlideShare a Scribd company logo
1 of 48
Download to read offline
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

More Related Content

What's hot

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
 

What's hot (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...
 

Similar to 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
 

Similar to 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
 

Recently uploaded

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

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