serverless framework

Create your first serverless application in Node.js

What is a serverless application? How will it benefit your back-end development or business? Learn what this new approach is about and create your first one with this tutorial.

When we think of a back-end application, we use to imagine server running apache or nginx that requires some DevOps work to set it up. This server architecture is continuously listening for request on a port and driving the traffic to our app.

Serverless architectures flipped this scenario. These ones are composed by event-triggered code that runs on ephemeral containers as FaaS (Function as a Service).

mind blown

Mind blown

Cool technical words said, this type of applications depends on another service that, when receives an event (i.e. an HTTP request), they load the app (as a function) immediately and run it to obtain the result. This means that we’re completely rid of DevOps, which is great news for me, since I hate that.

Main Benefits

Less operational and development cost

Your code runs in a shared environment, you’re outsourcing the configuration and management of the hardware where your app lives. In addition, your environment is virutal, and the actual hardware is shared across a big amount of apps, which reduces the cost per app of that

Scaling out-of-the-box 

As this architecture bootstraps the function upon request, when the number of requests increases, the automated infrastructure will use more hardware to load this diferent instances, allowing your app to accept all this traffic.

Scaling costs

You only pay for what you compute. Usually, this serverless servieces are charged per compute usage (in seconds). This means that you can have an application available all the time, but if no requests are taken you won’t be charged at all.

Shipping, shipping, shipping

This architecture requires zero-configuration, so you can afford more experimentation.

Major cons

Of course, not everything shines in this approach, the main cons of it are:

Vendor coupling

When developing a serverless appilcations, you’re so dependant on the service provider (like aws lambda, Microsoft Azure…). If the provider service API changes or the service is simply out of service, you’re screwed.

Early days

This technology is on early days now, there’s a lack of patterns and shared knowledge in this field.

Developing your first Serverless app

When I decided to play a little bit with this technology I started reading AWS Lambda web page. Personally I don’t like AWS documentation pages, and I was so confused about it.

The first thing you see when creating a lambda application is this: 

AWS Lambda trigger select

AWS Lambda trigger select

First of all, you should select what event will trigger your lambda function. As you can see, there’s a lot of options for cool integrations. For now we’ll use the API Gateway, this means that every time a user makes an HTTP request, it will run the function.

And here comes my problem with this platform:

creating a lambda function

Create your Lambda function

This is the interface for creating the lambda function, an online editor! Yeah, it’s true, there are other options like uploading the file with a ZIP or from S3 but come on, where is my CLI or a proper deployment system from a terminal? Also, this way I have to manage my lambda functions one by one. I would like to find a way to manage the functions all together.

At this time I decided to find another way of doing this.

Serverless (link here) is a JavaScript framework that helps you create this type of applications. First of all, we have to know that this one isn’t like Express nor Ruby on Rails, this one will help us create all the functions we want to code at once (in one project) and will help us deploying it into our service provider. All the syntax you see, all the protocol you have to follow when writing, these are from the service provider, not the framework.

Create the project

For creating your project you should run this code in your terminal:

Once the project is created, you will see two files (aside from the .gitignore): handler.js and serverless.yml.

Severless.yml

Serverless.yml is the yaml configuration file for the framework. In it, you’ll tell the framework all the things related to the service and how it should deploy it on the service provider. It’s pretty self-explanatory since it’s full of comments guiding you through the process. By now, we’ll use this one:

The service is the name of our service. The provider contains the information about our service provider like which one are we using (aws in this case) and the dependencies attached to it (in this project we’re using node v6.10). The last property we’re defining is the list of functions, in it we’re defining the list of functions that the framework will configure and upload in our service. On every function, we’re defining a handler and the events that trigger that function. The handler is composed by the file and the function reference separated by a dot and the events property is a list. In that list, we’re executing that function every http request on /user/create path on a GET method. Serverless will get that list and, for every function, will upload it to the service provider and configure every event that will trigger it.

As we pointed before, it’s plenty of options for function triggers. When a user uploads an image on S3, or when he deletes it; When another app in your AWS system enqueues a message on SNS; On a periodic interval, when you set it up as a cron job with a schedule event… You can check the list of optinons in here.

handlers.js

Then we follow with the handlers.js file:

We should remember that all the contents in this file are following the AWS Lambda protocol, so you should refer to this service provider documentation to solve or learn something related to it. This hello world will help us understand easily the format of the function. First rule: we have to export every function we want to declare, and we’ll accept three arguments on its signature: event, context and the callback.

The event is an object containing the information related to the event that triggered the function execution. The context is an object containing information and method to access to the AWS Lambda instance context (more info). Finally the callback, is a function that we’ll call with the response of the execution. Actually, we can set up the event so it expects the function as synchronous but, come on, we’re on JS, let’s embrace asynchronicity.

Finally, we create an object and we call the callback with no errors, generating the response and sending it back to the client.

Deploy it

It’s time to deploy. First of all we need to set up our AWS Credentials. For that, we should go to AWS IAM (identity and access management, security credentials) and create a new Access Key. After it, copy the access key and the access secret and run the next command in the terminal (interpolating these 2 values):

Finally, deploy it. The process will take several minutes, don’t worry, it only take so much time on the first deployment.

Once deployed, you will se a screen like this one:

terminal output of deployment

Go to the the listed url and BOOM! Function executed 🙂

Deployment Stages

Keep in mind that we just uploaded this function to the development stage. If you want to deploy it to production just add --stage production flag to the deployment command. You can also specify the region with the --region flag.

Database connection (to MongoDB)

In case you want to connect your function to a database, here you have an example of how to do it:

Despite the code quality of this example, it includes the key concepts. The most important is to require your dependencies inside the same function. If you do it outside, like we do in a normal server, it may be released and you won’t have access to it inside the function. You can install dependencies setting up a npm package and performing an npm install.

That’s all for now! We demystified serverless applications and we learnt how to create one. Try things, play with it, then come back and share your experience and your learnings in the comments section. Hope it helped you!

No Comments

Post a Comment

Just published in our blog: Create your first serverless application in Node.jsRead Post →
+