Leveraging Serverless To Build Scalable Soluions
Tags: serverless, lambda, python, api
Published: 2023-01-06 09:44:52

**Introduction**

Serverless is a cloud computing application development and execution model that enables developers to build and run application code without provisioning or managing servers or backend infrastructure. 

A serverless provider allows users to write and deploy code without worrying about the underlying infrastructure. A company that gets backend services from a serverless provider is charged based on their computation and do not have to reserve and pay for a fixed amount of bandwidth or number of servers, as the service is auto-scaling. 

**Note:** Despite the name serverless, physical servers are still used but developers do not need to be aware of that.

So, to leverage serverless computing, we will be exploring and implementing serverless framework in this blog.


**What is serverless framework?**

Serverless framework is an open-source web framework written using Node.js which enables us to build, package and deploy scalable applications without worrying about provisioning and managing infrastructure. It supports different Public Cloud vendors and satisfies the definition of an Infrastructure As A Code.

It's a CLI that offers structure, automation and best practices out-of-the-box, allowing you to focus on building sophisticated, event-driven, serverless architectures, comprised of [Functions](https://www.serverless.com/framework/docs/providers/aws/guide/intro#functions) and [Events](https://www.serverless.com/framework/docs/providers/aws/guide/intro#events).

**Functions :**

The code of a serverless application is deployed and executed in AWS Lambda functions.
Each function is an independent unit of execution and deployment, like a microservice. A function is merely code, deployed in the cloud, that is most often written to perform a single job such as:

•	Saving a user to the database
•	Processing a file in a database
•	Performing a scheduled task


**Events :**

Functions are triggered by events. Events come from other AWS resources, for example:
•	An HTTP request on an API Gateway URL (e.g. for a REST API)
•	A new file uploaded in an S3 bucket (e.g. for an image upload)
•	A CloudWatch schedule (e.g. run every 5 minutes)
•	A message in an SNS topic
•	A CloudWatch alert
•	And more...

When you configure an event on a Lambda function, Serverless Framework will automatically create the infrastructure needed for that event (e.g. an API Gateway endpoint) and configure your functions to listen to it.


The entry point of a Serverless Framework application is the **serverless.yml** file in a source root that describes the serverless application in its own syntax. Just like an AWS SAM template, it allows configuring the whole serverless application. It also has its own blueprints that can be used to bootstrap your own application.
[Check more details here.](https://tinyurl.com/384vyzh2)


**Why serverless framework?**

The Serverless Framework is different from other application frameworks because:

•	It manages your code as well as your infrastructure
•	It supports multiple languages (Node.js, Python, Java, and more)
•	It supports different cloud providers which supports function as a service.

We should focus on developing the business logic and let the infrastructure related stuff abstracted and handled by a managed service.


**How to leverage serverless framework?**

Let’s use serverless framework to develop and deploy a simple serverless API using AWS Lambda with Python.
Since serverless framework is a node.js CLI tool, at first we need to install Node.js
Now, just to verify Node.js installation use version check command.
Note: Serverless runs on Node v6 or higher

`node -v`


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jajl8adg4qv7025190e.png)

Now, the next step would be to install serverless framework using following command :

`npm install -g serverless`
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6pcapouadbeq7vrhqee.png)

We can verify the serverless framework installation by using version check command.

`serverless -v`

Next, we need to have an AWS account and an AWS profile is setup for the same. If not, [you can use this guide.](https://tinyurl.com/yv2kw6d3) to set it up.

Basically, you need to create an IAM user and access role to secure the service deployment on AWS. Here is how we can config AWS credentials :

`serverless config credentials --provider aws --key <AccessKey> --secret <secretKey> --profile <profile name>`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzsks5anqjem32fllyww.png)

Now, let’s create a python service using the template available in serverless framework. Use following command with service name as “backend” here :

`serverless create --template aws-python --path backend`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8kwc3gkwu5mcyazojiq.png)
 
To see a list of available templates run serverless create --help
Most commonly used templates are:

•	aws-clojurescript-gradle
•	aws-clojure-gradle
•	aws-nodejs
•	aws-nodejs-typescript
•	aws-alexa-typescript
•	aws-nodejs-ecma-script
•	aws-python
•	aws-python3
•	aws-ruby
•	aws-provided

Note: To check the available templates, [follow this link.](https://tinyurl.com/yhhe895p)

This will create two files in backend project directory , one serverless.yml and another one as handler.py, we can see below :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aktp4r7a4hadrmg60upz.png)

The serverless.yml file includes all the configurations related to cloud resources, language and functions. While handler.py have codes or logic related to lambda function.

Since we have the boilerplate for both the files created, let’s modify these files to create a simple API which gives us the product of two number.

We will start with the serverless.yml file :

•	First, define the name of the service you want to create: mybackendservice (This should be a unique service name for a particular serverless account).
•	If you want to monitor the serverless project in the serverless dashboard(dashboard.serverless.com), you can mention the app and org.
•	Now, we have to mention the configuration of the cloud provider, resources and permissions. In our case, we are using AWS as our cloud service provider.
•	At last, we include the lambda function configurations. In our case, we will define a POST API.

Note :  For more details on provider configurations, [please visit here](https://tinyurl.com/bp4r4nk2)

Here, we can see the configurations added for POST API in serverless.yml file.

Note: Add app/org name same as in your serverless dashboard.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txgyfqhwihny6boswq1q.png)

Now, let’s add the service logic in handler.py file.

We need to write a python function which returns product of two numbers in the json response.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hr3grz0yqgibe509jlsw.png)

Since, we are done with the changes. Let’s deploy our service using below command :

`serverless deploy`

once we execute this command it will be provisioning all the necessary resources in AWS and deploy our code.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2gqrsv6s4dptq2fo8q5.png)

Here, we can see after deployment, we got dashboard link to our app and the endpoint URL.


**Invoking A Lambda Function :**

Events are the things that trigger your functions to run.
 
If you are using AWS as your provider, all events in the service are anything in AWS that can trigger an AWS Lambda function, like an S3 bucket upload, an SNS topic, and HTTP endpoints created via API Gateway.

Other way to invoke a lambda function is using CLI:

`serverless invoke [local] --function functionName`

It invokes a deployed function. You can send event data, read logs and display other important information of the function invocation.

[check this link for more details about invocation](https://tinyurl.com/2s3wu8j9)


**Logs :**

One way to get the logs of a lambda function invocation is the AWS cloudwatch which we can access for a particular log set through monitoring tab in AWS Console.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w41u8r3jy33lyk8d39ba.png)

Another way is using CLI :

`serverless logs -f hello`

This lets you watch the logs of a specific function. This command returns as many log events as can fit in 1MB (up to 10,000 log events).

This will fetch the logs from last 10 minutes as startTime was not given.

[For more details on logs, check this link](https://tinyurl.com/2w3p6rfx)


Now, let’s try out our API service using Postman.

Here, we are using an HTTP request as an event to invoke serverless lambda function which we have developed.
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pel6rdplzpeyrte3dyc0.png)

We can see here, that the service is working as expected. So, now it’s your turn. Write your own service using serverless.


**Removing A Serverless App :**

The sls remove command will remove the deployed service, defined in your current working directory, from the provider.

Use this command from your CLI :

`serverless remove --stage dev --region us-east-1`

This example will remove the deployed service of your current working directory with the stage “dev” and the region “us-east-1”.

The alternate way is to delete the CloudFormation Stack corresponding to your service using AWS Console.


**Final Thoughts:**

This was a very basic example, but we can create a full stack and very sophisticated application as well with ease using serverless. So, with serverless we as developer can focus mostly at the logic part without caring about configuring and managing infrastructures. Serverless computing is evolving day by day and it’s adoption is also growing. This basic understanding will help you to develop and deploy your own service using serverless.


**References:**

•	https://tinyurl.com/4sxwwwfs
•	https://tinyurl.com/mtdruy88


**Disclaimer:**

This is a personal [blog, post, statement, opinion]. The views and opinions expressed here are only those of the author and do not represent those of any organization or any individual with whom the author may be associated, professionally or personally.