Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Victor Hazbun
Victor Hazbun

Posted on • Edited on

     

Serverless Node apps on AWS Lambda

What is Serverless?

Functions as services (FaaS). These consist of ephemeral containers that auto-scale and have a pay-per-execution pricing.

Still confused?

It runs your functions in the cloud without the need of a server PERIOD.

Pros

  • Low-Price, the cost of this functions being executed are way lower than having your own custom host.
  • Auto-scale, you don't need to worry about scaling the server since you don't really have a server. AWS Lambda will do it automatically for you as the function receives more and more requests.
  • Zero maintainability, you don't need to maintain the server hosting your functions.

Cons

  • Hot-cold fashioned, the functions are turned off and then on after a request has been made, this will result in a delay on the response.
  • Environment blocked, you can't install additional packages or software, so if your function depends on a third party package, you can forget about using AWS Lambda.
  • Different environments, the changes you have made in one instance will not be guaranteed to be persisted in the next instance. All will be wiped out (randomly).

How to battle against Cons

Hot-cold fashioned

You can useWarmUP

Environment blocked

You could tell your function to consume an API that host the software you depend on.

Different environments

You could store the files you need to persist using AWS S3

Setup

Visit AWS AIM console, create a new User, next give him access to Programmatic access and finally give himAdministratorAccess. Once confirmed, store theAccess key ID and theSecret access key.

Finally install the AWS CLI, and setup the access keyAccess key ID and theSecret access key.

brew install awscli

aws configure

Serverless Framework

Install the serverless framework.

npm install -g serverless

Manual setup

Let's setup the serverless framework in our app manually. And expose two API endpoints,create user andget one user.

serverless create --template aws-nodejs --path api

cd api

mkdir todos

//api/package.json{"name":"api-todos","version":"1.0.0","description":"Create and Get one Todo","author":"","license":"MIT","dependencies":{"uuid":"^2.0.3"}}
Enter fullscreen modeExit fullscreen mode

Install our dependenciesnpm install (AWS Lambda will install the dependencies as well).

# api/serverless.ymlservice:apiprovider:name:awsruntime:nodejs8.10environment:DYNAMODB_TABLE:${self:service}-${opt:stage, self:provider.stage}iamRoleStatements:-Effect:AllowAction:-dynamodb:GetItem-dynamodb:PutItemResource:"arn:aws:dynamodb:${opt:region,self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"functions:create:handler:todos/create.createevents:-http:path:todosmethod:postcors:trueget:handler:todos/get.getevents:-http:path:todos/{id}method:getcors:trueresources:Resources:TodosDynamoDbTable:Type:'AWS::DynamoDB::Table'DeletionPolicy:RetainProperties:AttributeDefinitions:-AttributeName:idAttributeType:SKeySchema:-AttributeName:idKeyType:HashProvisionedThroughput:ReadCapacityUnits:1WriteCapacityUnits:1TableName:${self:provider.environment.DYNAMODB_TABLE}
Enter fullscreen modeExit fullscreen mode

Next create each function file.

// api/todos/create.js'use strict';constAWS=require("aws-sdk");constuuid=require("uuid/v4");constclient=newAWS.DynamoDB.documentClient();module.exports.create=async(event)=>{constdata=JSON.parse(event.body);constparams={TableName:"todos"'    Item: {      id: uuid(),      text: data.text,      checked: false    }  };  await client.put(params).promise();  return{    statusCode: 200,    body: JSON.stringify(data)  };};
Enter fullscreen modeExit fullscreen mode
// api/todos/get.js'use strict';constAWS=require("aws-sdk");constdynamoDb=newAWS.DynamoDB.DocumentClient();module.exports.get=async(event)=>{constparams={TableName:"todos",Key:{id:event.pathParameters.id}};constresult=awaitdynamoDb.get(params).promise();if(result.Item){return{statusCode:200,body:JSON.stringify(result.Item)};}else{return{statusCode:404,body:JSON.stringify({message:"Couldn't find the todo item."})};}}
Enter fullscreen modeExit fullscreen mode
  • event is an object containing the request data.
  • context is an object containing the AWS info.
  • callback is a function that will be invoked with an error response as first argument or a valid response as second argument.

Deploy

Deploying is one of the coolest part.

sls deploy

Once deployed you can test the function.

Create a Todo

curl -X POST https://XXXXXXX.execute-api.us-east-1.amazonaws.com/dev/todos --data '{ "text": "Learn Serverless" }'

Output:

{"text":"Learn Serverless","id":"ee6490d0-aa11e6-9ede-afdfa051af86","createdAt":1479138570824,"checked":false,"updatedAt":1479138570824}%

Get one Todo

# Replace the <id> part with a real id from your todos table
curl https://XXXXXXX.execute-api.us-east-1.amazonaws.com/dev/todos/<id>

Output:

{"text":"Learn Serverless","id":"ee6490d0-aa11e6-9ede-afdfa051af86","createdAt":1479138570824,"checked":false,"updatedAt":1479138570824}%

More about deployment

You can also deploy JUST the function (This is pretty fast).

serverless deploy function -f create

DynamoDB

When you create a table, you specify how much provisioned throughput capacity you want to reserve for reads and writes. DynamoDB will reserve the necessary resources to meet your throughput needs while ensuring consistent, low-latency performance. You can change the provisioned throughput and increasing or decreasing capacity as needed.

Concurrent executions

By default, AWS Lambda limits the total concurrent executions across all functions within a given region to 100. The default limit is a safety limit that protects you from costs due to potential runaway or recursive functions during initial development and testing. To increase this limit above the default, follow the steps inTo request a limit increase for concurrent executions.

Handling lots of traffic

If you expect to have a lot of traffic it's recommended to switch tothe auto scaling option for DynamoDB.

Real world use cases

AWS Lambda or any other Lambda could be used for multiple purposes, like:

  • Data processing
  • Backends
  • IoT
  • Bots

Learn more about use cases

Final thoughts

No more servers? Well, certainly no. This will not replacement for serves (at least not now). However, it's a great tool to develop micro-services and many other things.

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
nadav96 profile image
Nadav Goldstein
  • Joined

Hi! Awesome read :)
I too use AWS to deploy microservices, and in the past used serverless cli.
unfortunately I found it to be very limiting cli, while AWS cli was too broad.

I came up with an alternative which takes the best from both worlds, called Rocketsam!

github.com/nadav96/rocketsam

If you find this tool useful, please let me know! :P

CollapseExpand
 
victorhazbun profile image
Victor Hazbun
Founder at @BonsaiLabs

Here are some other options:

  • AWS Amplify
  • Netlify
  • Azure functions

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Founder at @BonsaiLabs
  • Location
    Colombia
  • Work
    Software engineer at Bonsai Labs
  • Joined

More fromVictor Hazbun

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp