Your first serverless multi-tier web app on AWS (updated for 2017)

Jeshan Babooa
LambdaTV
Published in
11 min readOct 22, 2017

What we’re going to cover

Today, I want to show you a general overview on how to get started with making your first multi-tier serverless architecture; what it looks like, how to create your own and give you a demo that you can copy for your own project.

Why you might want to do that could be for many reasons; maybe your architecture is becoming hard to maintain or you’re facing issues with scale…

To keep this tutorial short and to the point, I have omitted steps like how to setup the CLI so you must have a minimum of familiarity with AWS for you to get the most out of this video.

Where does this architecture come from?

This tutorial is inspired from an AWS whitepaper wrote. In there, you can find the guidelines. This is the recommendation straight from AWS. The document is available here:

https://d0.awsstatic.com/whitepapers/AWSServerlessMulti-Tier_Architectures.pdf

The whitepaper is good. But I figured a video tutorial and a detailed blog post would make it easier for you to understand.

Also, I was expecting them to cover some follow up steps on what to do after you design your 3-tier architecture. For example:

  • A step-by-step guide on how to get up and running
  • how to automate the setup from start to finish

What you can build with this

A multi-tier architecture designed as discussed here can be used in many types of apps.

  • Web app, especially one with a static frontend (where I’m going to focus in this video)
  • Mobile app (I’ll leave that for a future video)
  • Or even any kind of app that can make https requests.

The three tiers

Presentation tier

W3C [CC BY 3.0], via Wikimedia Commons

In this architecture, it it AWS’s (and mine too) recommendation to use a front end that’s fully static. That is, it’s written only using HTML, CSS and JS. If you use PHP to generate html, then this system won’t work for you. Having a fully static website offers a lot of advantages, performance-related or otherwise; the server doesn’t have to dynamically generate the response, you can deliver your site to a global audience on a content delivery network, it can also be cached and compressed for you.

So, back to AWS. You are going to host your frontend on S3 which is AWS’s object-based (or file-based) storage.

Logic tier

We will use 2 AWS services for the logic tier; API gateway and Lambda:

API Gateway

Amazon API Gateway makes it easy for you to deploy scalable and secure APIs. You define methods and resources just as you would in a REST api. Then you tell it which routes need to execute what logic that you have defined in Lambda functions. Then it gives you https endpoints that you can tell your frontend code to call.

AWS Lambda

Lambda is my favourite piece of technology that have been made available in recent years. Essentially, it means that you upload some functions and with minimal configuration, it can run and scale as and when needed on your behalf. Lambda also encourages you to think of your applications as a decoupled set of microservices. There are no servers to run (hence the term “serverless”) and you only pay for resources consumed while the functions run. You can execute millions of requests for less than a dollar and there’s even a million calls that you are given free of charge every month… which is cool.

If you have ever managed servers before, you know that it can be a pain to make sure your servers are always secure, or figuring out how to autoscale and even how to deploy applications at scale. Thankfully, if you use Lambda, you won’t have to worry about that anymore.

You can make a lambda function run on many types of events, like uploading a file, running on a schedule or like in our case, hitting https endpoints.

Data tier

Now, let’s take a look at the data tier. 2 common options we have on AWS are Relational databases with AWS Relational Database Service (RDS) or NoSQL with DynamoDB. DynamoDB is AWS’s NoSQL offering that offers the performance we come to expect from AWS; high availability, performance and durability. There’s less administration required with it compared to a conventional relational database. Besides, it doesn’t require managing a server. We want a fully serverless solution, so we’ll go with DynamoDB for now.

Walkthrough

In this demo, I am going to show you how to make a TODO app (duh!) work on serverless. You will be able to view todos, create, make updates and delete them with CRUD operations.

Tip: Choose a region and use it throughout this demo. I’ll be using eu-west-1.

Step-by-step

Data tier

  • Let me start with the data tier

I’m going to show you how to setup the DynamoDB tables.

Our table called todo will consist of todos will consist of records that will look like this:

{  "completed": false,  "id": 1485277189149,  "title": "one"}

Completed indicates whether the todo has been marked as done or not, the id is a timestamp, and the title is what the todo is about.

Go to https://console.aws.amazon.com/dynamodb

Click create table:

Use todo as table name and id of type Number as primary key.

After a few seconds, your table will be created.

Next on to the logic tier. You will recall that this consists of the API gateway and Lambda.

Logic tier

Api Gateway

We will create our epic API with the API gateway.

Go to https://console.aws.amazon.com/apigateway/home

Create a new API by clicking Get Started:

Choose an api name, e.g multi-tier:

An empty API will be created:

We’ll get back to the API Gateway later.

Lambda

We’ll use one function that will handle our CRUD operations. We could also create a function for each operation (let’s call that function a ‘nanoservice’). I think in the case of CRUD, one function for all 4 operations makes for simpler code writing and deployment. It’s a matter of taste and it’s up to you and your use case.

Now go to https://console.aws.amazon.com/lambda

The select blueprint step will have many samples that you can use but skip to the Configure triggers step for this tutorial.

Choose the api name that you created and security open. Let’s leave the security open for now for simplicity. I’ll come back to it in a future tutorial.

Enter a name. We’ll use a function written in Node.js.

Paste the code available on github (explanation below the snippet):

https://github.com/jeshan/lambdatv/blob/master/multi-tier-architecture-todomvc/aws/index.js

The service’s main logic is found in the exports.handler function. We use exports.handler to tell Lambda that this is the lambda function we want to run.

I put the logic in a switch statement where each case corresponds to one of the CRUD operations:

I tell lambda that I’ve finished doing the server side logic with a call to the context.succeed function.

Take a few minutes to understand how this works. For example, you may want to check out how the docClient object is used to make operations on DynamoDB.

Let’s move on with the Lambda function creation.

Create a role with the name multi-tier or use an existing one. You’ll need the “Simple Microservice permissions” to be able to write to DynamoDB tables.

You can leave the other default values. Then click next to review your input and then click create function.

This should successfully create our function. Our API and Lambda function is available as shown in the screenshot below:

E.g https://pa71qoosib.execute-api.eu-west-1.amazonaws.com/prod/multi-tier

Save this endpoint; we’ll need it soon in our web application.

Identity Access Management

Before proceeding, our microservice needs an additional permission that wasn’t added automatically for us, i.e the ability to batch write on to a dynamodb table. We need this permission to be able to delete several TODOs at once in our demo app. This is done through the IAM feature.

Let’s add the permission quickly using the Identify and Access Management console.

If you used multi-tier as role name, you can find the role directly with this link:

https://console.aws.amazon.com/iam/home#/roles/multi-tier

Add the DynamoDB Full Access policy:

One final thing before proceeding to the front end: Our demo is calling the microservice asynchronously from a web app. So, we need to enable CORS. Back to our API in the API Gateway. Enable CORS as follows:

Select the API, then the resource and then Enable CORS:

Then deploy it on the same stage that was created before, i.e prod:

Now, we’re ready to connect our frontend to our API.

Presentation tier

Remember that our endpoint for our API is something like:

E.g https://pa71qoosib.execute-api.eu-west-1.amazonaws.com/prod/multi-tier

Now, we need to tell our frontend to use it. The javascript file that is of interest to us is found at:

https://github.com/jeshan/lambdatv/blob/master/multi-tier-architecture-todomvc/site/js/services/todoStorage.js

Set the apiGatewayBaseUrl constant to be equal to the endpoint:

If you want to understand how it’s used, read how the api factory is coded:

Now it’s time to upload your website to Amazon S3 where’ll you host your frontend code.

S3

Go to the S3 console at: https://console.aws.amazon.com/s3/home

Create a bucket:

Choose a name that suits you. If you want to use your own domain for the website (which you probably do), you must choose a name that equals that of your down, e.g I own jeshan.co so I could choose multitier.jeshan.co.

Upload the files contained in the site folder on github:

https://github.com/jeshan/lambdatv/tree/master/multi-tier-architecture-todomvc/site

When the upload has completed, select all of them and make them public so that they are viewable publicly:

Now we need to enable website hosting. Open properties for your bucket and use the settings as shown below:

Your website should now be up and running:

Now to use your own domain, you want to setup a DNS CNAME record for your domain. For example, I enter multitier as host on my DNS config that points to multitier.jeshan.co.s3-website-eu-west-1.amazonaws.com for my domain jeshan.co:

After the DNS record propagates, your website should be available at your chosen domain:

Congrats, we’re now done with setting up your first multi-tier serverless architecture on AWS!

“But wait… there’s more!”

I’d now like to cover a few topics on what I expected to find in the whitepaper but didn’t.

For example, I’d love some automation. So how could I script this whole process?

“What if I want to automate this whole process?”

Setting up the various tiers on the UI is cool but it makes it difficult to automate. I’m making a couple of Bash scripts available so that you can automate the process.

  • 1-setup-data-and-logic-tier.sh
  • 2-setup-presentation-tier.sh

You can find them on github here:

https://github.com/jeshan/lambdatv/tree/master/multi-tier-architecture-todomvc/aws

Prerequisites

Aws CLI setup. If you don’t have it setup, you can find instructions here:

http://docs.aws.amazon.com/cli/latest/userguide/installing.html

The scripts

This is how the first script looks like:

In there, you’ll find commands to set up the various tiers, such as:

To create the table…

aws dynamodb create-table --table-name ${TABLE_NAME} \  --attribute-definitions AttributeName=id,AttributeType=N \  --key-schema KeyType=HASH,AttributeName=id \  --provisioned-throughput WriteCapacityUnits=1,ReadCapacityUnits=1

To upload the website…

aws s3 sync . s3://$DOMAIN --acl public-read

aws s3 website s3://$DOMAIN --index-document index.html

Just fill in a chosen domain and you’re good to go:

There are some comments in there to help you find your way through it. Let me know if it doesn’t work for you.

“What if my app is not AngularJS based?”

In this case, you can use SDKs that have been automatically generated for you by API Gateway. At the moment, it supports the platforms iOS, Java, plain JavaScript and Android.

You can find them at a URL like: https://eu-west-1.console.aws.amazon.com/apigateway/home?region=eu-west-1#/apis/${YOUR_API}/stages/prod

Recommendation

Use Swagger for your APIs

Here we have a very simple API; it’s just a CRUD. For your own API, I recommend you define the API with a tool called Swagger: it makes life easy for many reasons.

We can import/export it into and out of api gateway. You can even use their editor web app to author your APIs.

I’ll cover Swagger in part 2 of this tutorial.

Recap

What the finished goods looks like:

You now have a basic multi-tier architecture up and running on AWS. It is completely serverless:

  1. You have a simple data tier running on DynamoDB that’s highly scalable without any maintenance.
  2. You have a logic tier set up with API gateway and Lambda that are billable as and when used.
  3. You have a static website that’s highly performant running on just a few cents per month.

So, I hope you liked it. Thanks for stopping by, it was quite a long tutorial!

Before you go…

More videos just about serverless on AWS, including part 2 coming soon.

Original article appeared here: https://www.lambdatv.com/Your-first-serverless-multi-tier-web-app-on-AWS-(updated-for-2017)

--

--

Jeshan Babooa
LambdaTV

Serverless Guy. Loves AWS Lambda. Intellij fan(atic).