Getting Started with AWS Lambda & Node.js

Written by RisingStack | Published 2017/06/07
Tech Story Tags: aws-lambda | nodejs | tutorial | serverless | javascript

TLDRvia the TL;DR App

In this article we will discuss what serverless programming is, and how to get started with AWS Lambda as a Node.js Developer.

Since the launch of AWS Lambda back in 2014, serverless (or FaaS — Function as a Service) computing became more and more popular. It lets you concentrate on your applications’ functionality by not having to worry about your infrastructure.

In the past years, most of the cloud providers started to offer their own version of serverless: Microsoft launched Azure Functions while Google launched Cloud Functions. IBM released an open-source version of serverless, called OpenWhisk.

Serverless Computing

Serverless is a type of event-driven architecture — functions are reacting to specific type of trigger events. Speaking of AWS, it can be an event fired by S3, SNS or the API Gateway just to name a few.

Lifecycle events of AWS Lambda functions

AWS Lambda functions are executed in an isolated environment, just like containers. This environment is provided with the resources specified in the functions’ configuration (like memory size).

AWS Lambda handles differently what happens when you call a Lambda function for the first time, and consequent calls to the same Lambda function.

Calling a new Lambda function for the first time

When you deploy your Lambda function (or update an existing one), a new container will be created for it.

Your code will be moved into the container, and the initialization code will run before the first request arrives to the exposed handler function.

The Lambda function can complete in one of the following ways:

  • timeout — the timeout specified by the user has been reached (defaults to 5 seconds as of now),
  • controlled termination — the callback of handler function is called,
  • default termination — if all callbacks finished execution (even without the callback of the handler function is called),
  • crashing the process.

Consequent calls to an existing Lambda function

For the next calls, Lambda may decide to create new containers to serve your requests. In this case, the same process will happen as described above, with initialization.

However, if you have not changed your Lambda function and only a little time passed since the last call, Lambda may reuse the container. This way it saves the initialization time required to spin up the new container and your code inside it.

Building your first function

Now as we’re done discussing the lifecycle events of Lambda functions it is time to take a look at some actual Lambda function implementations!

The Anatomy of an AWS Lambda function (in Node.js)

/* Initialization part starts here */

const mysql = require('mysql')const connection = mysql.createConnection({  host : process.env.MYSQL_HOST,   user : process.env.MYSQL_USER,   password : process.env.MYSQL_PASSWORD,   database : process.env.MYSQL_DB })

/* Initialization part ends here */ 

/* Handler function starts here */

exports.handler = (event, context, callback) => {   const sql = 'SELECT * FROM users WHERE id = ' +connection.escape(event.userId)   connection.query(sql, function (error, results, fields) {     if (error) {       return callback(error)     } callback(null, results)   }) } 

/* Handler function ends here */

Let’s examine what you can see in the example above:

  • initialization — this is the part of the code snippet that will only run once per container creation. This is a good place to create database connections.
  • handler function — this function will be called every time your Lambda function is executed.
  • event — this variable is used by Lambda to pass in event data to the handler (like an HTTP request).
  • context — the context variable is used to pass in runtime information for the Lambda function, like how much time is remaining before the function will be terminated.
  • callback — By using it, you can explicitly return data to the caller (like an HTTP response)

Deploying AWS functions

As now we have a working Lambda function, it’s time to deploy it.

This is where your troubles begin! But Why?

By default, to make AWS Lambda work with HTTP for example, you’d have to manage not just to AWS Lambda function, but an API Gateway as well.

Deploying usually means uploading a ZIP file, which replaces the old version of the AWS Lambda function. To save you all the headaches, let’s introduce the Serverless framework.

Enter the Serverless framework

The Serverless framework is an open-source, MIT-licensed solution which helps with creating and managing AWS Lambda functions easier.

Serverless helps you to create and configure all the necessary resources to run Lambda functions seamlessly.

Getting started with Serverless on AWS Lambda is just a few commands away:

# 1. Create a new Serverless project: $ serverless create --template aws-nodejs --path my-service 

# 2. Change into the newly created directory $ cd my-service 

# 3. Install npm dependencies $ npm install 

# 4. Deploy $ serverless deploy

These steps will produce a serverless.yml in your project which stores the description of the service (like route mapping for functions) as well as a .serverless directory, which contains CloudFormation files and the deployed ZIP artifact.

Drawbacks of using AWS Lambda

• Vendor control / lock-in

When you start to use a serverless solution, you’ll have to give up some control of your system to the cloud provider. In case of an outage, you will be affected as well most probably.

Also, when choosing either of the solutions, there will be differences on how their FaaS interface works. So porting your codebase from one provider to the other won’t be possible without code changes.

• Multitenancy

Multitenancy refers to the situation, where multiple customers are running on the same host. This can cause problems both in security, robustness, and performance (like a high load customer causing another to slow down).

Benefits of using AWS Lambda

• Reduced operational cost

You can think of Serverless Computing as an outsourced infrastructure, where basically you are paying someone to manage your servers.

Since you are using a service that many other companies are using as well, the costs go down. The cost reduction manifests in two different areas, both infrastructure and people costs, as you will spend less time maintaining your machines.

• Reduced scaling cost

Given that horizontal scaling happens automatically, and you will only pay for the resources you actually use, serverless can bring a huge cost cut for you.

Imagine a scenario when you are sending out marketing/sales emails on a weekly basis, your sites’ peak traffic will be present in the next hours only after they are sent.

• Easier operational management

As the auto-scaling logic of your infrastructure is handled by the vendor, you don’t even have to think about horizontally scaling your application — you just have to write it in a way that it can be scaled horizontally.

Read more

I hope after reading this article, you became more curious about what Serverless and AWS Lambda can do for you. If that’s the case, I recommend checking out the following extra resources:

If you have any questions, let me know in the comments below!

Originally published at blog.risingstack.com on May 23, 2017.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Published by HackerNoon on 2017/06/07