What is Serverless Architecture? | Introduction, Uses, and Benefits

What is Serverless Architecture? | Introduction, Uses, and Benefits
×

About the author

Sandeep Mali
Architect
Sandeep Mali, Architect at Nitor Infotech, is an experienced full stack developer who is capable of building complete solutions (frontend, back... Read More

Cloud and DevOps   |      18 Nov 2022   |     15 min  |

Why do we need Serverless architecture?

Exposing a software application over the internet usually involves managing some server infrastructure. It means a virtual server or physical server that we need to be maintained, as well as the operating system and other web server hosting processes required for your application to run. Using a virtual server from a cloud service provider such as Amazon, Microsoft, or GCP does mean the elimination of the physical hardware requirements. However, we still require some level of management web server software processes.

Using a serverless architecture concept, you focus on small individual functions in your application source code. There are multiple cloud service providers that provide this SAAS such as AWS Lambda and Microsoft Azure Functions. They take care of the physical hardware, machine operating system, and server software management. We only need to worry about our application code.

In this blog, I’m going to explain who can use serverless and why we can use Spring frameworks for serverless. Let’s get started!

Who can use Serverless?

You can consider using serverless if you have small logical or business rules that are defined in the application functions and you need to host on cloud, or in case you have requirements where we can call a function occasionally such as image cropping. If you have an already developed application, then you can migrate small logical functions or pieces of the application into serverless functions over time.

There are multiple frameworks in programming languages to write a serverless concept. As a Java techie, I like the Spring frameworks for serverless development.

Why can we use the Spring Framework for Serverless?

The Spring Framework provides many collections of functionalities to implement the serverless functionality. Whether we want to access data with Spring data, using the enterprise integration with Spring integration, or using the reactive programming with Spring frameworks and Project Reactor, Spring lets developers be productive in a serverless functionality implement from day one.

The Spring Framework also helps your functions avoid vendor lock-in. The adapters provided by Spring Cloud Function (SCF) let you decouple from vendor-specific APIs when running your code on their cloud platform.

At this juncture, allow me to tell you some more about Spring Cloud Function.

Spring Cloud Function

Spring Cloud Function (SCF) provides capabilities that let Spring developers take advantage of serverless or Function as a service (FaaS) platforms.

The core Java java.util.function package is the foundation of the programming model used by Spring Cloud Function.

Spring Cloud Function provides the following features and concepts:

  • Programming styles: reactive, imperative, or hybrid
  • We can use Function composition and adaptation concept
  • Spring Cloud Function supports the reactive function with multiple inputs and outputs. Its functions handle complicated streaming operations such as merging, joining etc.
  • SCF can support for data type conversion of inputs and outputs.
  • Packaging functions for deployments, specific to the target platform (such as AWS Lambda, Project Riff, Azure function and more).
  • SCF Functions having flexible signatures
  • All the other benefits of Spring’s expression and programming model.

Spring Cloud Function (SCF) provides adaptors so that you can run your functions on the most common FaaS services including Amazon Lambda, Apache OpenWhisk, Microsoft Azure, and Project Riff.

Now let’s turn to AWS Lambda.

1. AWS Lambda

AWS Lambda is a serverless service provided by Amazon for computing to reduce the configuration of servers, OS, and scalability. AWS Lambda can execute code on AWS Cloud with multiple languages.

The AWS Lambda function runs in response to events on different AWS resources, which triggers AWS Lambda functions. Pricing is pay-as-you-go which means we will not charge money if our function is not called by any AWS resource.

2. Development Maven Dependencies

To enable the AWS Lambda function, we need the following dependency in our Maven project:

<dependency>

<groupId>com.amazonaws</groupId>

<artifactId>aws-lambda-java-core</artifactId>

<version>1.2.1</version>

</dependency>

This dependency AWS Lambda can be found here at Maven repository.

The Maven Shade Plugin is also needed to build the Lambda application:

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-shade-plugin</artifactId>

<version>3.4.1</version>

<configuration> <createDependencyReducedPom>false</createDependencyReducedPom> </configuration>

<executions>

<execution>

<phase>package</phase>

<goals>

<goal>shade</goal>

</goals>

</execution>

</executions>

</plugin>

Now I’m going to walk you through the process of creating a handler.

3. How to Create Handler

To call a Lambda function, we need to specify a handler. Have a look at these ways to create a handler:

  • Creating a custom MethodHandler
  • Implementing the RequestHandler interface
  • Implementing the RequestStreamHandler interface

Let’s do it practically using code examples.

3.1. How to Create a Custom Method Handler

We can create a handler method that will be the entry point for incoming requests for our function. We can use any data types (JSON or primitive) as input values.

Also, there is one optional input called Context object. It will allow us to access useful information available within the Lambda execution environment:

public class SampleMethodHandler {

public String handleRequest(String input_data, Context context) {

context.getLogger().log(" input_data: " + input_data);

return " AWS Lambda Function is called.... ";

}

}

3.2. How to Use RequestHandler Interface

We can implement the RequestHandler class by overriding the handleRequest method which will be our entry point for requests:

public class SampleRequestHandler implements RequestHandler<String, String> {

public String handleRequest(String input_data, Context context) { context.getLogger().log(" input_data: " + input_data);

return " AWS Lambda Function is called.... ";

}

}

In the above example, the input will be the same as in the first option.

3.3. How to use RequestStreamHandler Interface

We can implement the RequestStreamHandler class and override the handleRequest method.

In this method, InputStream, ObjectStream and Context objects are the input parameters:

public class SampleRequestStreamHandler implements RequestStreamHandler {

public void handleRequest(InputStream input_stream, OutputStream output_stream, Context context) {

String input_data = IOUtils.toString(input_stream, "UTF-8");

output_stream,.write(("here is your input pass to output - " + input_data).getBytes());

}

}

4. How to Build the Deployment File

Now that everything is configured, let’s create the deployment file by running the following command. You can use a GUI-based editor to build it:

mvn clean package sample_lambda_function: sample_lambda_function

The final build jar file will be created in the source code target folder.

5. How to Create Lambda Function via AWS Management Console

You can sign in to AWS Amazon and then click on Lambda under Services. The Lambda page will show the list of Lambda functions, which you have already created.

Here are the steps required to create a new Lambda function:

1. On the Lambda screen, select “Select blueprint” and after that select “Blank Function

2. “Configure triggers” (in our use case we don’t have any triggers or events)

3. “Configure function”:

  • Name: Provide SampleMethodHandlerLambda.
  • Description: You can write your function description here.
  • Runtime: Select java8 (You can select your Java version here)
  • Code Entry Type and Function Package: You can select “Upload a .ZIP and Jar file” and click on “Upload” button. It will show you a dialog to select your jar file. You can provide the path of your target folder jar.
  • Now under Lambda function handler and role:
  1. Handler name: Provide lambda function handler name com.sample.lambda.function::handleRequestName
  2. Role name: If any other AWS resources are used in our lambda function, then you need to provide access by creating/using existing role and define the policy template.
  • Some more settings under Advanced settings:
  1. Memory: You can restrict your function to use limited hardware memory.
  2. Timeout: Add a time for execution of lambda function for each request.

4. Once all the above configurations are done with all inputs, click “Next” which will ask you to review the configuration.

5. When the review is completed, click on “Create Function”.

6. How to Invoke the Function

In the 5th step we created an AWS Lambda function, and now we will check how we test it by passing in some data:

  • Click on your latest Lambda function from the lists and then click on the “Test” button.
  • A popup window will appear which contains some dummy value for sending data. You can change those data values with “Testing”.
  • Now click on the “Save and test” button.

On this screen, you can see the Execution result area with a successfully returned output such as:

" AWS Lambda Function is called.... "

And there you have it! In this quick introduction to serverless, we’ve created a sample AWS Lambda app using Java 8, deployed that on AWS Cloud, and tested it. The sample source code for the example app can be found here – https://github.com/nitor-infotech-oss/springboot_serverless.

Feel free to write to us with your thoughts about the blog you just read and visit us at Nitor Infotech to discover all that we offer.

subscribe image

Subscribe to our
fortnightly newsletter!

we'll keep you in the loop with everything that's trending in the tech world.

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.