Getting started with AWS Lambda & serverless framework with real world examples

Magnus Lassi
6 min readMar 23, 2020

--

In this article I will discuss AWS Lambda and the serverless framework and what are good use cases. I will include a short example and in future articles I will build on top of this example.

Serverless (or FaaS — Function as a Service) has been talked about a lot in the last several years. Serverless fits certain use cases very well but as soon as you move into real-world projects you notice that there are cases where it’s not as simple as the short “Hello Lambda” examples that people publish.

There are many articles that explain AWS Lambda in detail, I will skip it since you can find that information easily online.

Benefits of FaaS

  • Autoscale our services automatically — we don’t need to configure anything for the lambda to automatically scale up / down depending on the work load
  • Run the code closer to the user — we can easily add it to other regions and more edge services are becoming available
  • infrastructure is automatically patched — with serverless the cloud provider will automatically patch the underlying environment that our services runs in

Disadvantages of FaaS

  • Troubleshooting is more difficult — although there are things that can help us troubleshoot by running locally like DynamoDb-local it’s more difficult than micro-services or a different architecture. We will cover this in future articles.
  • Long-running processes don’t work well with serverless — currently 15 minutes is the longest running process allowed with AWS Lambda
  • Vendor lock-in — there is a degree of vendor lock-in but it will also take to to move for example a micro-service architecture using kubernetes from one cloud vendor to another.

Why use Serverless Framework?

There are many other tools/frameworks that helps deploy FaaS architecture like Claudia, Zappa, Terraform and many others. Serverless Framework is easy to get started with and it supports many different cloud providers. It also supports many programming languages, I will be using Node / JavaScript in this article and the upcoming article.

There are many tutorials on Serverless framework but if you want to see quickly how to install it, there’s a link here . I found it easiest to use aws-cli to configure the credentials but you can do it different ways. You can create a new project using the AWS / Node template which will set up a template that has the basic things in Serverless using the command:

serverless create — template aws-nodejs — path myService

Business Domain

The business domain we will use in our examples is a fictitious coffee shop called Restbucks. I love coffee and a coffee shop is an interesting domain since it’s a mix of synchronous and asynchronous operations. We have the following actions a client / customer can perform:

  • seeing the price list of the different coffee drinks
  • placing an order / cancelling an order
  • getting a notification when the customers order is ready

Initial architecture

We will start by adding a simple operation and slowly building more complex operations. The initial operation will be an URI called /home which the client will send to the backend and in this first example it will just return a message to the client. In a real-world application we may return information how the customer wants to see their content, what their favorite coffee drink is etc.

We want to use the API Gateway in AWS to allow us to control more complex interactions and to be able to validate if a request should be processed instead of having to do it in every lambda function. The API Gateway will forward the request using lambda proxy integration. This means the API Gateway will forward the HTTP request as-is including the payload, query string and the HTTP headers.

Using AWS API Gateway to proxy the requests to our lambda function

Our lambda function is very simple in this example. I added the node module lambda-log which is nice when we want to add meta data like a correlation id that we want to carry with us as we call other modules in the same lambda.

We log the initial request with logger.info and the stringify it so that we can see the JSON data in our logs. Once we know it works as expected we can remove it.

We return a simple object with just status code and a message in this example which the lambda returns to the API Gateway and which is returned to the client which is a mobile app in our example architecture but it could be a web page for example.

'use strict' const logger = require('lambda-log') exports.handler = async function (event) {  
logger.info(`recieved event ${JSON.stringify(event)}`)
return { statusCode: 200, body: 'Welcome to Restbucks Coffee Shop!'
}
}

I also added a unit test for the handler but we will discuss unit tests in more detail later on.

The serverless config is very simple for our initial design. We add the lambda function handler we want it to call and the API Gateway mapping. Since we want to use the API Gateway and have it configured by the serverless framework, we add the events section where we specify the operation we want to allow and the path.

service: restbucks-lambda-home provider:  
name: aws
runtime: nodejs12.x
functions:
homeHandler:
handler: src/homeHandler.handler
events:
- http:
method: get
path: home

If we have configured the AWS account to use and region, we can now run a command from the serverless CLI to deploy it. In a real application we would want to configure in our CI/CD pipeline where to deploy it. The command to deploy from Serverless CLI:

sls deploy

This will build and package all the necessary dependencies and upload it to an S3 bucket that Serverless will use to deploy it to the AWS services it needs to deploy it to. If it was successful, you should see a console log similar to this but a different API Gateway and you may be using a different region.

Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service restbucks-lambda-home.zip file to S3 (103.75 KB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
..............
Serverless: Stack update finished...
Service Information
service: restbucks-lambda-home
stage: dev
region: us-east-1
stack: restbucks-lambda-home-dev
resources: 11
api keys:
None
endpoints:
GET - https://abl42f1m1g.execute-api.us-east-1.amazonaws.com/dev/home
functions:
homeHandler: restbucks-lambda-home-dev-homeHandler
layers:
None
Serverless: Removing old service artifacts from S3...
Serverless: Run the "serverless" command to setup monitoring, troubleshooting and testing.

We can call our lambda function directly from the Serverless CLI. We have to use the function name we defined in our serverless.yml file under functions and use the sls invoke command which will call our lambda function directly. We will see the result immediately it was deployed as expected!

sls invoke -f homeHandler -l
{
"statusCode": 200,
"body": "Welcome to Restbucks Coffee Shop!"
}
--------------------------------------------------------------------

We can also test sending the request via the API Gateway. Use the URL you saw in the output when you first deployed the lambda from the CLI and you should see it work.

curl https://abl42f1m1g.execute-api.us-east-1.amazonaws.com/dev/home
Welcome to Restbucks Coffee Shop!%

Let’s go to the AWS Services to see exactly what was deployed. Go to the API Gateway and you should see a route configured for dev-restbucks-lambda-home. If you go into it, it should look similar to the image below. We are using lambda proxy integration so we don’t have a lot configured yet. We could add validation of the request etc in the API Gateway.

API Gateway

Next, go to the AWS Lambda service and find the lambda called “restbucks-lambda-home-dev-homeHandler”. If the lambda is below a size threshold, we can see the code. This is useful when we want to troubleshoot in a lower environment and want to add additional logging. If we have a lot of dependencies we may go over the threshold even if the lambda function is very small.

AWS Lambda

That’s it! In the next article we will look into the add order flow of the application.

The github repo can be found here .

--

--