Thursday, May 26, 2022

Reactive programming concepts

 Lets try to understand the traditional approach in web application. When ever a request is made from the webclient it goes to server and server create and assign a single thread (httpservlet) to that request. This further follows the frame work class as suggestion and do the business logic and if needed goes to DB for performing CRUD operation as required. During this process our request tread need to wait till the response did not come from the DB and our thread time goes on waste.

Lets assume if we have a concept where in our request thread after giving the data to Db and rather than waiting for response immediately show itself ready for new client request and let’s have some underline implementation that will notify once the data is ready from the DB side that we need to send to client and the data is send to client then after. This is what Reactive behavior of programming.

One simple example is day to day life is of restaurant. Consider this scenario where in customer comes to restaurant and waiter take the request and place them to chef and again once the chef give him the signal about the order ready it delivers to customer. In mean time (from order given to chef and delivered back to waiter) waiter did not wait there only. He went back to serve more customer. This is exact that reactive programming is. Here customer is web request, Waiter is Httpservlet thread and Chef is Database.

So in general traditional approach

As shown above in traditional approach every request is blocked till the data from the DB is not given back to it so that they can take the value back to user. Now every server has some thread pool limitation . i.e. Tomcat has by default 100 thread in pool… you may say we can increase the thread, but that is not vice job as it will again create a hug impact on Tomcat server and as Thread is directly link with CPU utilization we did not have much ownership of it in JVM. By the way, you can increase the thread pool size in tomcat using this parameter in properties files server.tomcat.threads.max=250.

Now let’s take the new Reactive screenshot

Here we have a limited thread pool which take the request and assign it to event loop.
Reactive eliminate use of thread per request concept now let’s understand how it works on reactive programming in reactive programming let’s say request came to my application and it assigned to thread one now thread one will go to database for fetching the data but the advantage is here he will not wait to get response back instead he will send an event to database and he’ll inform to database hey i’m not going to wait to you anymore you just do your job whenever you will ready with response assign that response to available thread and just publish me a complete event/response .Now in that case my thread is completely free he can happily accept n number of request because not a single thread is blocking in this event loop approach. With this approach you can handle tons of concurrent request with very less thread that is what asynchronous unknown blocking means. Request assigned to the particular thread and thread is not going to wait for database driver to get the response he will continue his process he will accept n number of requests simultaneously that is what the all about.

Now lets try to understand some of the basic concept of Reactive programming.

Here we have four interface
1- Publisher
2- Subscriber
3- Subscription
4- Processor

1- Publisher :- Publish the event/data. This will always publish an event, so if you observe in this publisher interface we have only one method, Subscribe(). You can also call it as producer.
2- Subscriber:- Subscribe the event. you can call it as a consumer. It will subscribe or consume the event from publisher. If you observe the method signature it has four abstract method onSubscribe, onNext, onError and OnComplete. They are used respectively call when subsriber subscribe to it, iterate to the response, if any error occur or completed the iteration properly till the end.
3- Subscription :- This interface represents the unique relationship between a subscriber and publisher so if you observe the method signature it contains two method request and cancel, so subscriber will call this request method to use back pressure i.e. if the producer large number of response and client is not able to absorbs or process that many records it will tell the producer to send only that number of record that is mention in request() method and cancel is to cancel the subscription so that we are no more interested to listen to the producer for any other values.
4- Processor:- This interface represents a processing stage which is both a subscriber and a publisher and it is most obey the contract of both okay so if you observe the method signature it extends from both subscriber and publisher so it should over the contract of both publisher and subscriber

Now let’s understand the complete Reactive flow

As shown above figure we have publisher and subscriber and the first step subscriber will invoke subscribe() method of publisher and pass the instance of subscriber instance as an input (This will help subscriber to register itself to Publisher) now the next step publisher will going to send a subscription() event to the subscriber confirming that your subscription is successful now after that subscriber will call request(long n) method from subscription interface to get the data from publisher so if you observe the method signature is request n where n means subscriber can request any number of data from publisher. Now next publisher will send data stream to subscriber by invoking on next() method but let’s assume publisher is returning 10 record then in that case publisher will fire 10 times on next() event. If publishers send n number of data then there will be n time on next event process or it will execute onNext() event 10 times once all the record received by subscriber then publisher will invoke one onComplete() method of subscriber to confirming hey subscriber i am done with my job your execution is successful if there is any error then publisher will fire onError event. In addition, as said above the request() method of subscription interface there is a option for subscriber to ask the limited number of data from publisher i.e. let’s say publisher send 10 item, and you want to fetch only two item then subscriber can control using request(long n) method. So if we pass your request(2)then we can fetch only two record from publisher, that is what all about data back pressure in reactive stream programming.

So in short we can say this to have talk between publisher and subscriber to each other using given above four interfaces so in first step subscriber need to register to this publisher by calling the subscribe() method now publisher need to send one subscription event to the subscriber
then third step subscriber need to get the data from publisher by requesting this request(n) method from subscription interface now publisher will publish the data to subscriber by calling this onNext() event method then on completion you will find oncomplete() event and if there is error you will find onError() event.this is what reactive specification is all about.

Now let’s understand how to build reactive programming, i.e. what all library or frameworks are available .
In market to design a reactive programming, we have three library through which we can design a reactive programming
1- project reactor
2- rx java and
3- jdk 9 itself provided one reactive stream implementation

we will use the fist library project reactor as it is recommended library to work with spring boot framework.

Project reactor have large number of module in it. you can refer to the below url for more understanding

https://projectreactor.io/docs

Now lets try to understand the datatype that we are going and needed to work with when dealing with reactive programming.

There are two main datatype flux and mono for project reactor.

Mono stand for one and Flux stand of stream so in short when you are expecting single data use the Mono and when you expect stream of data use Flux.

So in short following the few of the advantages of using Reactive programming

1- new programming paradigm
2- it is asynchronous and non-blocking
3- it supports back pressure on data streams
4- support functional style of code
5- supports data flow as a event

In our next series, let’s try to understand a simple Reactive example using springwebflux standard way of using reactive programing in springboot concept as it is written on top of Project Reactor.

No comments: