What Is Functional Programming? Why the Paradigm Changed the Game?


The Path to Functional Programming

Before understanding functional programming, ask yourself how much do you know about another programming “styles”? When programming initially emerged to solve the major problems of the world through a few lines of code, Computer Scientists realized that they required a standard format or style which could help them to program effectively and efficiently. This style is commonly known as “programming paradigm”.

Soon developers began coding in C by using the procedural paradigm. Procedural programming mainly deals with coding with a step-to-step design similar to kitchen recipes; where a set of instructions is followed sequentially. At that time, the paradigm was indeed excellent at solving problems. However, as technologies evolved and programming became much more complex—websites were built and businesses began to adopt IT—the flaws of procedural programming bugged developers.

Enter Object-Oriented Programming, the next popular paradigm. The vision behind OOP was simple; it modeled programming on the basis of real-world examples. For example, a car could be seen as an object which possessed certain behavior (methods in programming) and states (members like variables in programming). OOP succeeded in decreasing global codebases. OOP concepts like encapsulation and inheritance were fundamental to attain an unexpected degree of productivity.

However, soon developers realized that OOP was not up to the task for a number of things. Hence, to address certain issues, functional programming came into the scene. Popular languages like PHP, Python, etc., are examples of languages which support the functional paradigm. Remember, not each language is built to support all paradigms. For example, while C can support procedural programming, it does not offer support for object-oriented programming.

However, most modern languages support procedural, OOP, and functional programming. There are some like Haskell, who received recognition due to features for functional programming. Java was initially not supportive of the paradigm, but since the last few years, Java releases have introduced features like Lambda Expressions to support functional programming. However, the question is, what exactly is functional programming?

What Is Functional Programming

The name suggests that it is linked to “functions”. Now, if you think that this function relates to the programming of methods, then your assumption is flawed. Functional programming refers to functions which incorporate a certain piece of code in the form of a feature or operation to an application. This function facilitates programmers to avoid changing the other parts of the application.

Functional programming highly borrows from mathematics. These functions are highly interlinked with those “mathematical functions” that you may have studied in your college courses.  In mathematics, a specific question is solved with a method without going much in the theoretical complexities of that method; similarly, functional programming is there to gain a higher degree of abstraction in applications.

One key aspect of functional programming is that it avoids change in the mutability and states of data. Another thing to note is that unlike “statements”, which are generally used in the OOP landscape, “expressions” power functional codebases.

Paradigm Shift to Functional Programming

Previously business applications used C++, a phenomenon that can prove to be a nightmare for modern developers. In those days, software engineers focused a lot on low-level aspects where issues related to memory management did not allow them to achieve much productivity. Then, Java came and provided more abstractions and managed these tasks through new features, thus resulting in saving developers from de-coding low-level complexities.

Today, languages like Scala (JVM) and F# (.NET) are promising a similar level of convenience to developers. Even outside of JVM and .NET ecosystems, you can clearly see Apple going with Swift and Facebook with React JS. Many of today’s “cool” languages are known for their functional paradigms. So why exactly has it become famous? Maybe, the following factors may have something to do with it.

Parallelism

One of the major reasons behind the positive reception of functional programming is its support for parallel computing. Traditionally, basic computing requirements like data storage and processing were not too intensive .i.e. there was no need of running several things at once. However, this changed as several technologies came and evolved one after another, expanding the world of software development and transforming it to power as a backbone of global operations.

Today, parallel computing is a highly valued domain of computer science where multiple applications and data require processing at the same time. Here, functional programming has made its impact due to its natural features which support independence components to run and support modern software infrastructure like microservices. This means if you try to add a specific functionality or modify an existing one, then “functions” ensure that you do not affect the other components of your system.

Data Streaming

Another reason which can be associated with the ‘functional leap’ is the advent of “streaming services”. a few years ago, entertainment was mainly associated with TV—the only medium for watching shows and movies.

However, today streaming services like Netflix have changed the game. Entertainment has shifted online. People prefer to take advantage of the luxury of watching football matches on mobile apps while commuting, rather than hurrying their way back to home for their television sets. Since functional programming works well with streaming due to its natural concepts; hence its growth makes a lot of sense.

AI

AI is perhaps the most exciting branch of computer science. Over the past few decades, extensive research has been carried out about AI while its applications and sub-branches like machine learning, deep learning, speech recognition, etc have become their own field of studies. AI is seen with a bright hope that it can modernize the world and take it to the next level through robots and intelligent machines. However, all this AI implementation requires coding where a paradigm has to be ultimately chosen.

Since AI is closely related to mathematics, logic, statistics, and theoretical computer science, hence you can certainly understand why functional paradigm—a paradigm founded on mathematics—is gaining so much prominence among the AI community.

What’s in it for the Developer?

Well, so far you might have understood how the elevation of some technologies and necessities of some requirements raised the need for functional programming. However, why should you as a developer working with “objects” (OOP) think about learning something new? Is the hassle worth it? Well, to be honest, functional programming is not a magic potion that can generate great results for all OF YOUR applications.

However, there are several cases where the use of functional programming can assist you to achieve better results in your projects where the time spent on learning the paradigm may result in saving you a great deal of resources. Following are a few of the reasons to learn it.

Decreasing LOC

What was one of the most well-liked thing aspects about OOP? The programs that used to require 5,000 line of codes via procedural programming, were reduced to less than 1,000 lines of codes by adopting OOP’s fundamental concepts like inheritance.

Similarly, functional programming also promises the same .i.e. it provides shorter code-bases while maintaining the performance of the application. As a result, productivity is increased where fewer lines of codes do more while maintenance is also relatively easier.

Testing and Debugging

When everything is a function; testing is less challenging. You just have to test each function where one’s output does not affect the result of the other function.

The states of functions cannot be modified from outside of its scope. Hence, its input can be tracked effectively, resulting in an efficient management of its output too. As a result, debugging is easy because it is easy to check what went wrong.

Career Growth

There are no negatives in learning a paradigm which goes well with all the hottest modern technologies. With a chance to work on IoT, AI, and, other futuristic fields, functional programming can prove pivotal to your success as a computer scientist. Learning and adapting are the hallmarks of every successful computer science. Also, if you are tired of doing the same old programming, then it can provide a new challenge that can motivate you to work contentedly.

Now that you have learned about some basic definition, importance, and advantages of functional programming, now is the right time to understand its basics.

What is RabbitMQ?


What is RabbitMQ?

The concept of messaging in the software environment is similar to the daily life processes. For example, you went for a morning coffee. After taking your order, the manager inputs it into the system. If there is no rush in the coffee shop, your order does not require to be added in a queue.  However, if there are previous orders, the system puts it behind other orders. Thus, your order becomes part of the queue.

However, what if there are countless orders and the server is unable to manage all those due to a hardware issue? What to do now? In such cases, a service like RabbitMQ can prove to be the game changer. RabbitMQ will take all the orders and only forward them to the server when it can manage the workload.

Before understanding RabbitMQ, it is essential to equip yourself with the knowledge of a message broker. A message broker is an intermediary program that works on the translation of the contents of a message with the messaging protocols of both the receiver and the sender. Message brokers are used as a middleware solution for a variety of software applications.

RabbitMQ is a message broker software that is used for the queuing of messages. There are three main actors in the RabbitMQ lifecycle. First, we have a ‘publisher’ or ‘producer’. A publisher is the one who creates a message and sends it. Second, we have an ‘exchange’. Exchange receives the message with a routing key from the producer. The exchange will then save the message and store it in a queue. Third, we have a consumer. A consumer is a party for which the message was intended. A consumer can either be a third party or the publisher itself who consumes the message after getting it from the queue of the broker.

For the above example, we have used a single queue, but in real-world applications, there would be multiple queues. An exchange is connected to a queue through a binding key. The exchange will use the routing key and binding key to confirm the consumer of a message. However, it is important to note that sometimes an exchange will link a routing key with the name of a queue instead of using a binding key. There are mainly four types of exchanges: direct, topic, headers and fanout.

Whenever a message goes to a consumer, RabbitMQ makes it certain that it is received in the correct order. The queues do not let a message get lost.

RabbitMQ comes with a protocol known as AMQP (Advanced Message Queuing Protocol). AMQP helps to define three major components.

  • Where should the message go?
  • How will it get delivered?
  • What goes in must also come out.

AMQP does not require a learning curve and can be easily programmed due to its flexibility. Thus, if a developer works with the HTTP and TCP requests and responses, they will easily adapt its protocol.

RabbitMQ supports development support for all the popular programming languages including Java, .NET, Python, PHP, JavaScript, etc.

Example

For a practical explanation, we will write a simple application in Java with RabbitMQ. The application will consist of a producer, which will send a message, as well a consumer, which will receive that message. For sending, we have a file named Send.java. You will require the following import.

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

 Now, setup the class.

public class Send { 
private final static String QUEUE_NAME = “hello”;
public static void main(String[] argv)      throws java.io.IOException {      …  }}

Now we will have to link our class with the server.

ConnectionFactory factory = new ConnectionFactory();
factory.setHost(“localhost”);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

 

This code helps in the abstraction of the socket connection. Now, the next step is the creation of a channel. For this purpose, you will have to define a queue.

channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = “Hello World!”;
channel.basicPublish(“”, QUEUE_NAME, null, message.getBytes());
System.out.println(” [x] Sent ‘” + message + “‘”);

Lastly, we close the channel and the connection;

channel.close();
connection.close();

This ends the code for the sender.

Here is complete send java class.

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Send {

private final static String QUEUE_NAME = “hello”;
public static void main(String[] argv) throws Exception {         ConnectionFactory factory = new ConnectionFactory();    factory.setHost(“localhost”);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();    channel.queueDeclare(QUEUE_NAME, false, false, false, null);    String message = “Hello World!”;
channel.basicPublish(“”, QUEUE_NAME, null, message.getBytes(“UTF-8”));
 System.out.println(” [x] Sent ‘” + message + “‘”);
 channel.close();
connection.close();

  }

}

Now you will have to write the code for the consumer. For this purpose, create a Recv.java class. Use the following import.

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;

 

Now we will open a connection here too.

public class Recv { 

private final static String QUEUE_NAME = “hello”; 
public static void main(String[] argv)      throws java.io.IOException,             java.lang.InterruptedException {     ConnectionFactory factory = new ConnectionFactory();    factory.setHost(“localhost”); 
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();     channel.queueDeclare(QUEUE_NAME, false, false, false, null);    System.out.println(” [*] Waiting for messages. To exit press CTRL+C”);

    …    }

}

 

Now you will have to notify the server so it can fetch the messages that are accumulating in the queue.

Consumer consumer = new DefaultConsumer(channel) {  @Override  public void handleDelivery(String consumerTag, Envelope envelope,   AMQP.BasicProperties properties, byte[] body)      throws IOException {    String message = new String(body, “UTF-8”); 
  System.out.println(” [x] Received ‘” + message + “‘”); 
}};
channel.basicConsume(QUEUE_NAME, true, consumer);

Now run both the consumer and the producer, and you will have your RabbitMQ hello world application.

Complete Recv.java

import com.rabbitmq.client.*;
import java.io.IOException;

public class Recv {

private final static String QUEUE_NAME = “hello”;
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(“localhost”);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(” [*] Waiting for messages. To exit press CTRL+C”);
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, “UTF-8”);
System.out.println(” [x] Received ‘” + message + “‘”);
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}

Final Thoughts

RabbitMQ has been adopted in thousands of deployment environments. It provides a significant boost in the scalability and loose coupling of applications. Today, it is by far the most popular message broker. Moreover, it also provides convenience with the cloud and also supports various message protocols, making it a desirable option for your development toolbox.

Serverless Computing: An Introduction to Amazon Lambda


AWS Lambda is a service provided by AWS that relates to the compute service. It assists in the running of application code where a physical server is not required. Lambda processes code per user requirements and raises the scalability bar when the need arises.

Whether your application deals with a few user requests or you need to handle thousands of requests, Lambda can be handy. Lambda utilizes Amazon’s highly powerful IT cloud infrastructure for running its compute services where the hardware and OS intricacies are delegated.

Considerations for Writing Lambda Functions

Irrespective of your choice of programming language, the understanding, and usage of the following components are important for the creation of a function.

Handler

Handler is used by Lambda for the execution of your function. Handler is adjusted after a function is created. Whenever a function has to be invoked, execution initiates with the help of the handler.

Context Object

A handler also receives a context object from the AWS Lambda, which can be marked as the second parameter. Context object provides communication between AWS Lambda and your written code.

Logging

Lambda functions keep a track of logging statements.

Exceptions

A result of your Lambda function’s execution is necessary to be conveyed to the AWS Lambda. This can be done through various strategies so a request’s lifecycle can come to an end. Likewise, the occurrence of an error can also be notified to the AWS Lambda. AWS Lambda passes the function execution result to the client if a function is invoked through synchronous means.

Writing a Simple AWS Lambda Function

Let’s see an example of our traditional “hello world” where we can run code of an AWS Lambda function without the use of a server— purely on the cloud!

1-     Lambda Console

Open the AWS Management Console. Check for the option of Lambda that appears under the Compute button. Click it so that the Lambda Console can be opened.

2-     Choosing a Blueprint

Now, you have to choose a blueprint. Blueprints have pre-existing code to speed up the processing. Blueprints can handle events from different sources. In the console, click the button of “Create a Function”. Now, click the “Blueprint” option. Find the filter box and enter the following details.

“hello-user-python”.

Choose the associated blueprint.

Now, press the Configure option.

3-Configuring the Function

Lambda functions store lines of code that are written by the users while they also manage dependencies and configuration. Configuration details can include the allocation of the resources for compute like memory, timeout of execution, etc. Lambda takes these details as input and does the required processing in return.

Now, you have to enter a description for your function. This description includes the following.

  • Name – Select a name for your function. For this article, we can use the “hello-user-python”.
  • Role – An execution role can be created which carries certain authorizations. Lambda uses the role for the invocation of a function. Choose the option of “Create a new role from template”.
  • Role Name – Select a role name for your function. For this example, we can use lambda_simple_procsessing.
  • Policy Templates – Before the generation of a function, a role is assigned after selecting an appropriate template.

A sample code is provided under the label of Lambda Function Code. Go to the lower part of your screen now and choose the option of “Create Function”. The coding for Lambda function is supported in all the popular programming languages like C#, Node.js, Java, Python. By default, Python is used for the runtime.

For managing the code, a handler method can be defined in the code. Lambda passes data related to events to the handler after which processing of the event is initiated. By scrolling down the options, any configuration for the execution time or memory can be configured, though we will not modify it in this example.

Invoking the Function and Checking the Results

The Lambda function of the hello-user-python appears on the console. This function can be tested where you can review the results and view the logs. Find a dropdown menu with the name of the “Select a test event” and click on the “Configure Test Event”.

You have a textbox for the testing of a function through an event. Go through the template list of sample events and select the “HelloWorld”. You can now assign any name to your event like “HelloUser”. The field values for the text in JSON can be modified. However, the event structure should not be changed. Modify the “value1” field with the “hello user”.  Now, finish by clicking on the “Create Button” and click the “Test Button”.

If everything goes alright, you can view your results from the console. These results are classified into the following:

  • Execution – Confirms if the execution was successful or not.
  • Summary – Presents the crucial details from the log input.
  • Log Output – Views all the logs that are produced due to the execution of your Lambda function.

Metrics

Amazon CloudWatch engages in the supervision and reporting of the Lambda function’s metrics. For effective management of the code for its execution, Lambda keeps a record of the following and publishes them:

  • Count of requests.
  • A request’s latency.
  • Requests concluding with an error.

Click on the “Test” button a few times so the metrics can be produced and displayed. Now, choose the option “Monitoring” for the displaying of results. As you scroll down, you can find various Lambda function metrics.

Since Lambda supports the “pay-as-you-go” model, users have to pay according to the request numbers of the Lambda functions. To be specific, pricing is based on two invocation factors: Duration and count.

Removing the Function

A Lambda function does not incur any charges. It can be deleted through the console. Go the “Actions” button and choose the “Delete Function”. A pop-up will appear now for confirmation; choose “Delete”.

Well, now you have successfully created, managed and deleted a simple AWS Lambda Function.

Micro Service part 3 with an example


Problem

Before going into the details about microservices, it is important to understand the background of another architecture known as a monolithic architecture. A monolith application is generally a large one that has tightly coupled components. The challenges of monolithic application include the following:

  • It is hard to scale a monolithic application. Since all the components are tightly coupled, larger modifications are needed.
  • If the business aims to adopt a different technology then it is not viable to adopt it, due to the presence of certain constraints.
  • Automation is a hard nut to crack with monolithic applications.
  • Modern-day coding conventions and solutions are also difficult to implement.

What Are Microservices?

One of the easiest definitions of microservices is explained by Sam Newman.

Small autonomous services that work together

Microservices can be seen as a self-contained solution that helps in the provision of distinct business functionalities for applications. Various microservices may appear as separate but their combination as a whole runs the entire application smoothly.

For instance, suppose there is an e-commerce website. For simplicity purposes, we will divide its business processes into two modules. Firstly, we have the order module that helps customers to order a product by selecting customized options. Secondly, we have the processing module that will communicate with the back-end and verify the banking and other relevant details of the customer. In a monolithic application, a change in the order module means a change in the processing module too.

However, if we are talking about microservices, then essentially we separate these mini processes. In microservices architecture, we have an order microservice and a processing microservice. These microservices can exchange information through a protocol or interface like REST. Generally, this communication is stateless which means that there is no dependence on the state of a component. Additionally, each of the microservice is independent and manages its own data.

Why Use Microservices?

Work on the Immediate Problem

In the case of a monolithic application, an upgrade, repair or modification means tinkering with the entire codebase of the application. This dilemma is solved through the emergence of the microservices. Microservices help to focus and modify only the relevant component of the example. For example, if the above-mentioned order microservice needs a change in its business logic, then only its microservice needs to be worked upon. Restructuring or recoding might not seem like a difficult problem for small applications but in the case of enterprise applications, they consume a great deal of time and resources.

Organization of Teams

Often IT managers are unable to properly utilize their developers as they are unsure about how to divide the tasks of different modules. Subsequently, developers from different teams struggle in the debugging and modification of the code. With microservices, each service can be allocated a small team. Due to its loose coupling, developers are empowered to focus on their own services. Consequently, they are also saved from consulting with other teams for the updating of single business functionality.

Different Languages

Often a problem in an enterprise application is the selection of a programming language and framework. Sometimes, PHP is good for certain business functionality while sometimes Java’s security is the need of the hour. Luckily, the microservices architecture allows the writing of code for each service in the language of the developer’s choice. Since all the services communicate with each other through standardized protocols, hence microservices provide flexibility.

How Microservices Improve on the Previous Architectures?

There is a misunderstanding regarding the nature of microservices architecture. Some people believe that the microservices divide an application’s web, business and data models. This approach is not dissimilar to the vision behind the previous out-dated architectures. However, this is a faulty analysis.

Instead, each microservice manages its own data model. Hence, only the team of a specific microservice can change its behavior. Another feature that separates microservices from others is stateless communication. Stateless communication helps in the scalability of the application as each pair of the request and response is handled independently.

Example

For a practical implementation, let’s take a look at an example of Hello World application using Microservices in Java. We will create a HelloWorldService class.

class HelloWorldService {

public String greet() {

return “Hello, World!”;

}

The above-mentioned code can be written in different Java environments. For example, for our console application, we can write the following.

class Starter {

  HelloWorldService helloWorldService = new HelloWorldService();

  public static void main(String[] args) {

    String message = helloWorldService.greet();

    System.out.println(message);

  }

}

For java servlets, we can write the following lines of code.

class HelloWorldServlet extends HttpServlet {

  HelloWorldService helloWorldService = new HelloWorldService();

  public void doPost(HttpServletRequest request,

    HttpServletResponse response) throws ServletException, IOException {

    String message = helloWorldService.greet();

    response.getWriter().println(message);

  }

}

For coding the controllers of Spring MVC applications, we will have to write the following piece of code.

@Controller

class HelloWorldController {

  HelloWorldService helloWorldService = new HelloWorldService();

  @RequestMapping(“/helloWorld”)

  public String greet() {

    String message = helloWorldService.greet();

    return message;

  }

}

Now, we have to solve the service issues that can be either related to the entire service’s unavailability or its ineffectiveness in returning an appropriate response. Service unavailability is mainly the client’s headache to deal with. With code written with the help of frameworks like unirest.io, clients are able to manage the service unavailability better.

Future<HttpResponse<JsonNode>>future= Unirest.post(“HTTP://helloworld.myservices.local/greet”).header(“accept”,”application/json”).asJsonAsync(new Callback<JsonNode>() {

public void failed(UnirestException e) {  //tell them UI folks that the request went south

    }

public void completed(HttpResponse<JsonNode> response) { //extract data from response and fulfill it’s destiny }

    public void cancelled() {//shot a note to UI dept that the request got cancelled   } } );

In the case the service fails, you can use the following code for the response.

{

  “status”:”ok”,

  ”message”:”Hello, World!”

}

The status attributes help to show the correct nature of a response.

Final Thoughts

Since its emergence, microservices have reinvented several enterprise applications and helped save developers from a great deal of complexities. Now, developers do not need to reduplicate their codebases. The working of entire projects has been improved vastly this way.

Microservice through my lens (Part2)


Have you finally taken a leap of faith and resolved to adopt the microservices architecture? Hopefully, it is for the best. The other out-dated solution architecture might have been compromising the performance, security, and customer satisfaction of your applications, website or mobile app.

However, as you will delve deeper in the microservices world, you will face certain hiccups. Thankfully, a number of design patterns and best practices have been introduced in the software community that can help you to tackle these challenges and move forward with your application.

API Gateway

While using the micro-services architecture, often the client-side has to face a certain issue. The problem stems from the client’s inability to gain access to different services. Through applying the API gateway pattern, client-side is provided with a single access point.

This point acts as a center from which it can interact with other services of the application. Sometimes, the API will send a request from the client to its suitable receiver while other times, more than a single service will receive the request. As a result, the client-side does not need to fall into the complexities about how different microservices have been split up by the application.

Service Registry

Often microservices in an application struggle to locate the free instances of the services. In this case, the service registry can be helpful. Service registry can be basically considered as a DB for all of your services.

It holds the instances of the services which are registered and de-registered on each startup and shutdown. Hence, clients can search for any available or free instance through the service registry. However, there are few problems that are related to the pattern.

One of them is that it needs constant configuration and management. In case a service registry falters, crucial data can be lost. Hence, it has to be ensured that the service registry is always available for use by the application.

Circuit Breaker

In a microservices application, services often have to communicate and execute tasks together. A service can receive a request for which it has to call another service for action. However, the summoned service can sometimes be unavailable due to an issue. In such a predicament, valuable resources can be wasted and the actual service that was called will not be able to process other incoming requests. As a result, one service’s failure incurs a significant loss to the entire application’s resources.

In such events, ‘circuit breaker’ is the need of the hour. It is a remote service that listens to the communication between two services. If a service fails to respond after a certain limit, then the circuit breaker will trip. The summoned service cannot communicate any further during the timeout interval. After the interval, few requests can be accepted by the circuit breaker to see if the service has regained its working. In case the service is working, the communication will be restored. However, a timeout interval will follow if the called service is still unavailable.

DB per Service

Let’s suppose you are working with an e-commerce application. For the order of products, you have an ‘Order’ service while for payment, there is a ‘payment’ service. Since the majority of the services require data to be stored, how will you manage your data storage of services? Since it is a microservices application, you cannot use a single DB. Instead, you can link each microservices’ API with its own DB.

As a result, each service will be able to keep its data confidential. You can also try to use separate tables, schemas and DB servers for your services. With every service having a dedicated DB, one of the primary requirements for microservices architecture, loose coupling, is achieved. Additionally, each service will be able to use a DB according to its needs.

Health Check API

Often, a service instance is running fine but it is unable to process requests. This can happen if the DB connections are not available. For this scenario, a monitoring mechanism is required that can serve as a warning tool. Hence, in order to alert about a running service that is facing difficulty in processing requests, we can use health check API. As the name suggests, it is used to examine and alert about the health of a microservice. The API will examine things like application-specific logic, disk space, connection status etc. However, it must be noted that a service instance can still falter in the middle of a health check and thus the pattern should not be considered to deliver 100% success.

Messaging

For handling and processing the requests from the clients as well as working together with other microservices, a standard communication mechanism is required that can enhance the performance of the application through effective communication. For this purpose, the asynchronous message can be the solution to your problems. It helps in inter-service communication through which microservices are able to pass all types of messages to each other. Kafka and RabbitMQ are one of the most popular messaging tools available. Due to the message broker mechanism, requests are handled better and do not get lost. However, the message broker has to be available 24/7 while the client will also need to know the message broker’s address.

Log Aggregation

While dealing with a large application that is built on microservices architecture, you will have to deal with a number of instances spawning from each service. There would be a continuous stream of requests that have to be handled by all the instances. These instances produce information about their workings to a log file.

The log file will entail debug, warnings, errors and other information. Hence, in order to increase the understanding of an application’s complete behavior, a logging service can be used that is based on the centralized model. The service will help to accumulate the log data from all the instances of services. As a result, IT professionals can find and understand these logs and apply configuration for alerts so any important message can be displayed on a priority basis.

Best Java Web Frameworks


Java is easily the most popular language of the last two decades. Due to its wide range of features, including the cross-platform compatibility, strong community, an extensive list of libraries, and high security, it has been the first and foremost option for the developers in coding business and enterprise systems for both the public and private sector.

However, earlier Java web development used to be too complex as the ecosystem and tools were confusing for many coders. As a result, many developers had to scratch their heads while reading through hundreds of pages of official documentation for the software bugs that can even originate from a single line code in a class. Luckily, today Java’s ecosystem has been bolstered by the arrival of several frameworks that has made programming on the web for Java easier, and Java no longer bears the tag of the most difficult language for the web. Some of these frameworks are the following.

Spring

Spring was and still is one of the most popular web frameworks in Java. Spring is a light-weight framework as Spring uses various technologies like Hibernate, Tapestry, etc.   Thus, it thus can be implemented for a wide segment of web applications. Spring employs a software engineering concept known as dependency injection through the use of either a construction injection or setter injection. Through Spring’s container, the hard coupling of Java objects is reduced. Moreover, another programming framework called the Aspect Oriented Programming is used in Spring. This focuses on the modularization of concerns, making it easier to deal with middleware development.

Spring helps greatly in the elimination of presentation and business logic and minimizes the previously existed complexities that existed with the J2EE frameworks. Spring is flexible and assists coders with the elimination of a framework-specific base class. With the addition of Model View Architecture, it allows data binding and efficient management of data models.

JSF (Java Server Faces)

One of the biggest problems with a web back-end project is not only the design and development. For enterprises, continuous updates and maintenance are a frequent requirement. However, with JSF corporate developers can easily maintain their code with the support of modern software architectures. With a JSF web application, you can map component-specific event handling with HTTP requests while the server can also be used to treat the components as stateful objects. Java Server Faces eases back-end development through the introduction of an approach that centers on components, which helps in the coding of the web UIs. This is made possible due to JSF’s Facelets that help in the design of the views in web projects with the integration of HTML. Moreover, JSF has in-built support for AJAX.

JSF is chosen by developers for enterprise systems as they are handy for corporate development. For beginners, the drag-and-drop feature will facilitate the design of sleek and elegant user interfaces. For senior developers, the JSF API provides high customization.

Play 2

If you desire a speedy framework without any compromise on the scalability, then Play Framework 2 is a good option. This means that you can edit your code and refresh it to see instant results. Moreover, with support for non-blocking I/0, the performance of an application is highly improved through remote calls in parallel.

Unlike the previous Java web frameworks’, Play rescues developers from the complexity of Servlets and provides modern components of web development frameworks including REST, JSON, NoSQL, and ORM. Furthermore, due to its support for JVM, developers who have to transition from Java to Scala find it convenient due to the community and libraries support.  Additionally, with its integration with front-end technology like CoffeeScript and Less, it has received considerable praise for being one of the most promising new Java frameworks in the last few years.

Google Web Toolkit (GWT)

Are you a full stack web developer working with React and Vue JS? Or do you focus solely on the back-end logic?

For full stack developers, Google Web Toolkit provides a great advantage for design and development of both front-end and back-end development. GWT was released in 2006 by Google for its own use. Seven years later, Google made it open source and it gained popularity quickly due to Google’s extensive documentation and support for the framework for a variety of development environments and technologies.

Its platform advantages include generating JavaScript, compatibility with all the popular web browsers, as well as coding advantages like refactoring, syntax highlighting, and a dynamic UI component library. Thus, if you are incorporating front-end controls like a radio button or a checkbox in your project and are linking it with the back-end in Java code, GWT serves as a leading option for full stack development.

Grails

If you are familiar with the JVM ecosystem and write code in Groovy, then Grails can provide an easier learning curve for a shift in Java web development. Grails also has an extensive support for Java libraries and boasts availability of 700+ plugins. Grails also employ the modern day programming ideology of ‘convention over configuration’, limiting the lines of code.

Moreover, if the requirement of CRUD functionalities is a recurrent theme in your development then Grails’ Scaffolding makes it a breeze. Furthermore, if you are also involved in the Search Engine Optimization of your website, then the websites developed on Grails are easy to optimize for better search engine results. Additionally, with Grails’ GORM, developers have an access to a reliable data tool for linking with relational databases and NoSQL, including MongoFB.

With such powerful tools at your disposal, web development in Java has never been easier. If you have a wide range of web projects, then Spring MVC is the go-to option, while JSF can assist in the upgrade and maintenance of enterprise systems. If you require a framework for full stack development for working with both the front-end and back-end and also require sufficient documentation, then Google Web Toolkit is quite powerful, while for a stateless and non-blocking project, Play 2 can be the best solution.

What Is NoSQL? How Is It Different Than the Traditional Databases and What Are the Types of NoSQL Databases?


As the computers progressed through different stages, computer scientists realized that the real-life information of humans could be stored through a digital solution called database. With the rising processing and storage demand, pen and paper were not enough to handle the requirements of mankind. As a result, relational databases made an entry in the 1970s. All the information was saved on the databases through a query language called SQL (Structured Query Language).

Relational databases were a massive hit, and businesses of all scales began designing schemas, relations, and database designs to manage their clients and customer bases. However, data continued increasing at a rapid pace.

As more technologies emerged and the web and mobile platforms accelerated, discussions were held about the feasibility of relational databases in today’s world. Similarly, the ability of DBMS systems to handle a massive number database request was also part of the discussion where real-time interactions like those of social media platforms have increased the data requirements.

What Is NoSQL?

NoSQL stands for ‘Not Only SQL’. NoSQL database is an approach where the traditional concepts of database management systems are not followed. NoSQL databases are required when enterprise systems have issues related to the performance and scalability of their application.

NoSQL has been especially deemed suitable and fit for the requirements of modern day web applications where it is a part of the MEAN (MongoDB Express Angular Node JS) and MERN (MongoDB Express Angular Node JS) technology stacks. These web development stacks have been insanely popular in the recent years where the NoSQL database models are either slowly used as an additional tool or are used to completely replace the RDBMS systems.

Types of NoSQL Databases

There are four key types of NoSQL databases that store information in different ways.

Key-Value Data Store

In key-value DBs, data is stored through a distinct series of key-value pairs, which is similar to the concept of dictionaries. This means that a key can only be linked with a single value of a collection. As a result, the simplicity of the application is increased as a simple query that can generate the required result with a key-value data store.

Additionally, it also negates the need of a query language like SQL. Now the question arises, when should you use the key-value data store? Well, if you have are developing a social media platform, then you can save the profiles of the users through key-value data store.

Similarly, if you are managing a blog, then the comments of your fan following can be stored through a key-value data store. Social media platforms like Twitter and Pinterest are already using key-value data store for their newsfeeds and user profiles.

See the following example where our key is a list of countries that have cities as their values.

Key Value
USA {“New York, San Diego, Seattle”}
India {“Mumbai, Chennai, Delhi“}
Canada {“Toronto, Vancouver, Montreal”}

Example of KeyValue store

These are Key-value store options.

 AerospikeApache IgniteArangoDBBerkeley DBCouchbaseDynamo,  FoundationDBInfinityDBMemcacheDBMUMPSOracle NoSQL DatabaseOrientDBRedisRiakSciDB,  ZooKeeper

Column Store

Traditional DBMS always store and process data horizontally using rows. However, the rows are not stored together in the disk and, thus, accessing different rows can be slow for the database retrieval purposes.

In the case of a column store, the horizontal concept of storing and retrieving data is completely changed. Instead, a new approach has been designed where data can be stored in columns. These columns are combined together into column families. A column family can have countless columns that may either have to be generated at the runtime or at the time of specifying a schema. Column store is useful because the disk saves the column data continuously, which makes searching and accessing data for retrieval purposes easier and faster.

Column DBs is used by Spotify to manage the metadata related information of the music industry. Facebook also uses Column stores for searching mechanisms and personalization.

Example of Column store

These are Column options.

 AccumuloCassandraDruidHBaseVertica.

 

Document Store

In a document store DB, different data formats can be saved. These include the common JSON (JavasScript Object Notation), XML (Extensible Markup Language) or BSON (Binary Encoding of the JSON) data.

Hence, the document store provides a level of flexibility that was previously unimaginable with the relational database approach. It is similar to the key-value store in its storage mechanism of key-value pairs, but here all the values are called ‘documents’.

Additionally, the values also have encoding and structure related information. For example, see the following instance where our values are stored in the form of a document. All of the following instances are related to the address of offices. However, you can see how they can be represented in different formats.

 

{officeName:”ABC 1”,

{Street: “B-329, City:”Mumbai”, Pincode:”806923”}

}

{officeName:”ABC 2”,

{ Block:”A, 2nd Floor”, City: “Chennai”, Pincode: 400452”}

}

{officeName:”ABC 3”,

{Latitude:”60.257314”, Longitude:”-80.495292”}

}

We can also query our searches through the details of the data in the document. For instance, in the above example, we can use the city ‘Mumbai’ for all the data related to the “ABC offices”.

The popular gaming franchise SEGA utilizes the document store approach through MongoDB for its management of more than 10 million gaming accounts. Similarly, the real-time weather functionalities in Android and iOS are provided through the document store model.

Example of Document store

These are document store option

Apache CouchDBArangoDBBaseXClusterpointCouchbaseCosmos DBIBM DominoMarkLogicMongoDBOrientDBQizxRethinkDB

Graph Database

As the name suggests, graph databases use a graphical representation. Like the CS algorithm of the graph, there are nodes, edges, and other related components in graph databases. A graph database is useful to tackle the scalability issues of the applications. In graph databases, entities are represented by the nodes, while the association is linked through relationships. Each node contains records of relationships. For example, suppose a social media network where users know each other.

 

graphdb

Example of Column store

These are Key-value store options.

 AllegroGraphArangoDBInfiniteGraphApache GiraphMarkLogicNeo4JOrientDBVirtuoso

Final Thoughts

With the rising application development needs and demands, NoSQL databases serve as an excellent solution. Whether you are managing an e-commerce store or you are intending to create the next big app, the traditional databases may not always fulfill your needs. With the help of a NoSQL database, you can get an instant performance boost, and your applications will be able to handle requests with enhanced optimization.

What Is Spring Boot and Why Should It Be Chosen Over Spring?


Do you wish to speed up your web development? Are your projects unable to meet the deadlines set by the clients? Do you want to fast track your applications?

Why was Spring Boot Needed?

Before understanding Spring Boot, you will have to understand why it is needed? For Java developers who choose Spring over the older and more complex Java EE, Spring provides speed and scalability along with various components in its ecosystem that eliminate redundancy from coding.

Spring introduced concepts like dependency injection, REST, Batch, AOP, and others, etc. Spring was also easily integrated with other frameworks like Struts and Hibernate. However, there were still qualms related to the configuration complexities of the Spring projects. Since Spring is mainly used for the development of enterprise and large-scale projects, these projects require external Java files and need to be configured heavily.

For developers who work on small projects, the difference in the configuration of enterprise projects is noticeable. As a developer, it is undesirable to spend a lot of time on the configuration when that time can be utilized in the coding of business logic.

Hence, with the arrival of Spring Boot, developers have received a much-need boost that eases up their development complexities. The important thing to note with Spring Boot is that it is not a web framework and, therefore,  cannot be viewed as a complete replacement for Spring framework. Rather, it is a solution or an approach for web development in Java that minimizes the heavier configurations and dependencies. This means that as soon as you start a Spring Boot project, you can run it instantly without many configurations. Because of this, it has become one of the most popular tools in the development of Spring projects.

What is Spring Boot?

With the emergence of Spring Boot, Java developers are able to center their attention on the application logic. This means developers are saved from the complexities and difficulties associated with the configuration of web projects. The important thing to note with Spring Boot is that it is not a web framework. Rather, it a solution or an approach for web development in Java.

Why Spring Boot Over Spring?

The questions that come into mind with the mention of Spring Boot are, “Why should I use it when there is Spring? Is it an extension of Spring?”

Starters

Are you tired of searching Google for the source codes of different dependency descriptors? Spring Boot has a certain feature called ‘starter’. These starters are available for a number of use cases, which is handy for quick configurations. With a starter dependency for the most used Java technologies, these starters are highly productive for the POM management and help in the development of production-ready applications. Some of these are the following.

Web

Suppose you are building a REST service. You may need to use Spring MVC, Jetty, and Jersey for your web project. All of these technologies require their own set of dependencies. So will you add all of them?

Fortunately, with the Spring Boot starter, you will only be required to type a single dependency known as ‘spring-boot-starter-web’. Now, you can proceed to write your REST service without adding any further dependency.

Test

Whether you use JUnit or Spring Test for your testing, you will have to add all of them one-by-one in your project. However, with the help of ‘spring-boot-starter-test’, all your testing dependencies can automatically be managed. If the need for the upgrade of the Boot library arises in the future, then you will just have to make a single change for the Boot version.

JPA

Persistence is a common feature of Java’s web projects. Mostly, it is Java Persistent API (JPA) that requires its own set of dependencies. However, with a single line addition of spring-boot-starter-data-jpa, all of the required dependencies are automatically managed.

Opinionated Default Configuration

Whether you are working with Groovy or Java, Spring Boot provides convenience with the help of the coding conventions of the opinionated default configuration. This means that developers do not have to spend time in the writing of boilerplate code. Likewise, the XML annotations and configuration complexities can also be reduced significantly. As a result, the productivity of a project increases considerably.

Integration

Spring’s projects need to be configured so a developer can get its ecosystem’s necessary features. The use of Spring Boot does not mean leaving the Spring’s ecosystem. In fact, Spring Boot helps with the integration of Spring technologies like Spring JDBC, Spring Security, and others to your development toolbox.

Scripting

Spring Boot comes with a command line module that can be used for Spring scripts. These scripts are written in the JVM language, Groovy. Groovy adopts various features from Java, and thus it provides convenience for Java developers to use without meddling with the boilerplate coding conundrums. The tool can also be used with Spring’s Batch, Integration, and Web.

Type-Safe Configuration

Spring Boot also comes with the support for type-safe configuration. This helps in the validation of the configurations of web projects.

Externalize Configuration

Do you consistently need to modify your configurations as you write a code in a variety of software environments? With Spring Boot, developers have the ability to externalize their configuration and write the same code for all the environments. As a result, reusability is increased in the projects.

Logging

Spring Boot also helps common logging for internal logging. This means that all the dependencies of a web project are set by default. However, developers can customize these dependencies if needed.

Embedded Servers

Spring Boot provides Embedded Servers. This means that you can eliminate the need of WAR files from your toolkit. Instead, you can now create JAR files and put your Tomcat Web Server inside the JAR file. This JAR file is called an embedded server. Now this embedded server can be run on any machine that recognizes JVM.

First Spring boot application

Before you start building spring boot application you need to have some tools ready.

  • Java 8 and above
  • Apache Maven 3.3.9
  • Spring STS/eclipse

 

  1. Open STS IDE select New-> Maven project. Select your workspace location.
  2. In New maven project explorer select maven-archetype-quickstart
  3. Enter Name of your application (Let say “myFirstSpringBootApplication”) and click the finish button.
  4. Open pox.xml and add spring-boot-starter-parent and the spring-boot-starter-web dependency.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

  1. Go to App.java which was created by default and add @SpringBootApplication               import org.springframework.boot.SpringApplication;
                   import org.springframework.boot.autoconfigure.SpringBootApplication;              @SpringBootApplication
  2. Create a new class TestMyFirstSpringBootApplicationController and write the code like this.

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestMyFirstSpringBootApplicationController {
      @RequestMapping(“/”)
      public String firstMethod() {
             return “yey .I wrote my first application!”;

}

}

 

  1. Start your application by clicking on Run As-> Java Application
  2. Test your application. Open the web browser and type http://localhost:8080. You should see the message “yey. I wrote my first application!”;
  3. Write your comment on my blog and suggest if you want to update /add anything

 

Final Thoughts

Are you exhausted with the management of dependencies? Do you hate to continuously write boilerplate code? Well, then you should certainly think about using Spring Boot, especially for small projects.

Message-Driven Architecture


A message-driven architecture can have the following components.

  • Producer – The one that generates a message and then forwards it ahead.
  • Consumer – The one for whom the message was intended; who will then read it and process accordingly.
  • Queue – A communication model that saves the messages so they can be sent ahead to other services for processing.
  • Exchange – It is a queue aggregator. This means that it can apply abstraction on the queues and manage the messages so they can be sent to the right queues.
  • Message – It consists of the headers which contain metadata as well as a body. The body entails the actual contents of the message.

A message-driven architecture also needs a message broker. This message broker decides who should send the message or who should receive it.

Surely, the benefits of the microservices outweigh those of monolithic applications but the paradigm shift means that you will have to look into the communication protocols and processes between various components of your application. By using the same mechanisms of monolithic systems in a microservices application, it may impact the performance of the system and slow it down, particularly if you are coding distributed applications.

To counter such problems, the isolation of the microservices architecture can be helpful. For this purpose, asynchronous communication can be utilized to link microservices. This can be done through the grouping of calls. The services in a microservices application are often requires interaction through protocols like HTTP, TCP etc.

The general opinion of the developers regarding the microservices architecture is to inject decoupling in applications while maintaining the cohesiveness of the system. A true microservices applications is one in which each service has its own data model and business logic.

A protocol can be either asynchronous or synchronous. In the synchronous protocol, a client can forward a request. The system will then listen for a response. The entire process is independent with client code execution. An example of such messaging is the HTTP protocol. In asynchronous protocols, the sender will not listen or wait for a response.

Types of Message Brokers

There are many message brokers that are used for message-driven architectures. Some of these are the following.

RabbitMQ

RabibtMQ is perhaps the most popular message broker out there. It is open-sourced and uses the Advanced Message Queuing Protocol (AMQP) with cross-platform functionality. Whether you are a Java developer or a C# one, all of your microservices can be used to communicate the message with different microservices.

Azure Event Hub

This one is a PaaS (Platform as a Service) related solution that is offered by Microsoft Azure. It does not need any management and can be easily consumed by a service. It also uses AMQP. It basically has an Azure Event Hub that works with partitions and communicates with consumers and receivers.

Apache Kafka

Kafka is the brainchild of Linkedin and was made open-source in 2011. It is not dissimilar to Azure’s solution and has the capability to manage millions of messages. However, the difference stems from the fact that unlike the Event Hub, it works with IaaS (Infrastructure as a Service). Though, newer solutions are also integrating Kafka with PaaS.

There are two types of asynchronous messaging communications for message-driven architectures.

Single Receiver

Single receiver message-driven communication is particularly helpful when dealing with asynchronous process while working with different microservices. A single receiver is one in which a message is sent only once by its consumer. After forwarded, it also will be processed only once. However, it must be noted that at times a consumer may send the message more than once. For example, there is an application crash; the application will try to repeat the message. In the case of an event like an Internet connectivity failure, the consumer can send a message multiple times. However, it must be noted that it should not be combined with the HTTP communication that is synchronous. Message-driven commands are especially useful when developers scale an application.

Multiple Receivers

To get your hands on a more adaptable technique, multiple receivers message-driven communication can be proficient. This communication utilizes the subscribe/publish strategy. This refers to an approach where a sender’s message can be broadcasted to multiple microservices in the application. The one who sends a message is called the publisher while the one who receives it is called the subscriber. Additionally, further subscribers can be added to the mix without any complex modification.

Asynchronous Event-Driven

In the case of asynchronous event-driven communication, a microservice will have to generate an event for integration. Afterward, another service is fed with the information. Other microservices engage in the subscription of events so messages are received in an asynchronous manner. Subsequently, the receivers will now have to upgrade their entities that entail information regarding the domains so further integrations events can be published.

However, here the publish-and-subscribe strategy requires tinkering with event bus. The event bus can be coded in such a way that it occurs as a means of the interface while dealing with API (Application Programming Interface). To be more flexible with the event bus, other options are available through processes like a messaging queue where asynchronous communication and the publish-and-subscribe strategy are fully supported.

However, it must be noted that all the message brokers have different levels of abstraction. For example, if we are talking about RabbitMQ, then it has a lower level abstraction if we compare it with solutions like MassTransit or Brighter. Brighter and others use RabbitMQ for abstraction. So, how to choose a message broker? Well, it depends on your application type as well as the scalability needs. For simple applications, a combination of RabbitMQ and Docker can prove to be enough.

Though, if you are developing large applications then Microsoft’s Azure Service Bus is a powerful option. In the case of desiring abstraction on a greater level, Brighter and MassTransit are the good options. If you are thinking about developing your own solution then it is not a good idea since it is time-consuming and the cost is too high.

What Is Event-Based Architecture?


Before reading about event-based architecture, you will need to understand what an event is. An event can be termed as any ‘change’ that occurs between two states. For example, a module in application sends a message to another component. This message can be the event that will trigger a change in the processing of the system. Event-based architectures are favored because they help software development of asynchronous and scalable applications.

What Is Event-Based Architecture?

Event-based architecture is a type of software architectural design in which the application component receives the notification of an event. As a result, a response is generated. In comparison to other paradigms, event-based architecture is considered loosely coupled. EDA can be considered as an approach for coding software solutions where the heart of the architecture lies in ‘events’ which process the communication between different components.

How Does Event-Driven Architecture Work?

The architecture has several components that help to speed up the development process of an application.

Queue

In an event-based architecture, the requests accumulate into queues called event queues. From these queues, the events are then sent to the services where they are processed.

The events in this architecture are collected in central event queues. For example, check the following diagram.

queue

 

 

 

S here denotes the service. The queue will provide an event for each service accordingly.

Log

The event log exists on the hard disk. It consists of the messages that were written for the event queue. An event queue is useful because in case of an unexpected system shutdown or crash, rebuilding can be eased through the contents of the event log. The following diagram will help to explain the event log’s place in the architecture.

 

log

 

 

 

The event log can also be utilized for any future back up. This back up can take the entire state of the system which can be critical in testing. The comparison between the performance of both the old and newer releases of an application can be analyzed through this backup.

Event Collector

Okay so far we have talked about the collection of the events in the event queue but how exactly are the events received? Well, the answer lies within the term ‘event collector’. These collectors get requests from protocols like HTTP and forward them to the event queue. Further understanding can be gained through the following diagram.

eventCon

 

Reply Queue

Not all the events can be categorized as same. Sometimes, an event does not require a response. For example, a user has entered some data in a feedback form. In this case, the system does not require sending a response. However, some events require the system formulating a response for a request. The request here will be called as an ‘event’ in our architecture. For this response, a reply queue is needed which will utilize the event queue. The collectors that forward the events can also provide the response back. However, it must be noted that the event log does not record the contents of the reply queues. The following diagram can explain the reply queue.

 

 

replay

 

Read vs. Write

When all the requests from the collectors act as an event to trigger a function, then all of them are added in the event queue. In the case, this queue is linked to the event log. All the requests are persisted which slows down the system. If some of the non-important requests can be eliminated then the event queue’s processing can be increased considerably.

The core concept behind this persisting of events is the rebuilding of the former states of a system. This means, events that actually modify the state of the system, need to be persisted to the event log. This can be done through the classification of events into write and read events. A write event is one in which the states of the system are modified while a read event does not modify any state. As a result, the application can now only persist during the write events which in turn will provide a much-needed boost to the management and processing of the event queue.

Ratios between both read and write events can be drawn to further gain an understanding of the difference. For instance, our system has 10 events. Out of the 10, only 2 events are actually changing the state of the system. Without classification, we can find all of them to be slowing the speed of the event queue through persistent to the log. However, by dividing them between read and write events, only 2 of our events require to be persisted. Subsequently, the other 8 read events cannot risk the speed of the queue.

Now a question arises. How to distinguish between these events? Events should be distinguished through the collectors. If a collector does not separate them, then the event queue will be unable to make a decision of its own.

Another approach is to divide an event queue. One event queue will be responsible for dealing solely with the read events while the second one can look after the write events. This saves the resources as no other component in the system has to decide on the persistence of the events. The following example shows the idea behind this approach. Some may feel that it may make the system more complex but in reality, it is reducing the workload of the application.

 

event

 

Final Thoughts

The main benefit of event-based architectures is seen while working with scalable enterprise applications. Event-based architecture also particularly assists in the testing phase and can generate productivity in test driven approaches which means that each core component of an application can be designed and developed separately. Additionally, with low to no coupling, the architecture stands as an excellent choice for the removal of complexity in applications.