Migrate your Existing Express Apps to AWS Lambda and Amazon API Gateway

Download Migrate your Existing Express Apps to AWS Lambda and Amazon API Gateway

Post on 06-Jan-2017

716 views

Category:

Technology

0 download

TRANSCRIPT

Stefano Buliani, Specialist Solutions Architect, Serverless@sapessi11/02/2016Migrate Express Apps to ServerlessUsing AWS Lambda and Amazon API Gateway

2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved.

AgendaBenefits of Amazon API GatewayBenefits of AWS LambdaAPI-first migration to the cloudNew features in API Gatewayaws-serverless-express in GithubDemoBest practices

2

Benefits of Amazon API GatewayCreate a unified API frontend for multiple micro-services

Authenticate and authorize requests to a backend

DDoS protection and throttling for your backend

Throttle, meter, and monetize API usage by 3rd party developers

3

Code is all you needEvent driven scalingNever pay for idleAvailability and fault tolerance built inBenefits of AWS Lambda

4

Customer use case:API-first migration to the cloud

1. Use API Gateway to front existing backends

Internet

Client

API Gateway

Hosted service 1

Hosted service 2

AWS cloud

corporate data center

2. Lift & shift service to AWS

Internet

Client

API Gateway

Hosted service 1Service 2on EC2

AWS cloud

corporate data center

3. Lift & re-architect

Internet

Client

API GatewayService 2on EC2

AWS cloud

Microservice 1

Microservice 2

Microservice 3Re-architected Service 1

Simplified migration:New features in API Gateway

Catch-all resource pathsANY http methodPROXY integrationsThree new features in Amazon API Gateway

Catch-all resource pathsDefine the entire API structureUse path variables for individual path parts: {id}Use the Swagger toolkit to generate documentation and SDKsQuickly catch all sub-resourcesUse catch-all paths to identify separate servicesVery quick to configure but less well defined for doc and SDK generation

Catch-all resource paths using Swagger{ "Swagger": "2.0", "paths": { "/{proxy+}": { } }}

ANY HTTP methodDefine methods individuallyFlexible because each method can use a different integrationUse the Swagger toolkit to generate documentation and SDKsIntercepts any HTTP verbVery quick to configure but less well defined for doc and SDK generation Works well with catch-all resource paths

ANY HTTP method using Swagger{ "Swagger": "2.0", "paths": { "/{proxy+}": { "x-amazon-apigateway-any-method": { } } }}

Proxy integrationsHTTP_PROXYNo input/output mappings!Sends entire request to the HTTP backend and returns the unmodified responseAWS_PROXYNo input/output mappings!Automatically generate event with the entire requestWell defined return interface that is automatically transformed into an HTTP response

Proxy integrations

Store Lambda Function

HTTP service on EC2Automatic request mapping{ resource: /orders/{path+}, path: /orders/1423, httpVerb: GET, headers: { Content-Type: application/json, x-custom-header : 1 }, queryStringParameters: { limit: 10 }, pathParameters: { path: 1423 }, requestContext: { apiId: xxxxxx, apiKey: xxxxxxxxxxxxxxxxxxxx, identity: { sourceIp: xxx.xxx.xxx.xxx, cognitoIdentityId: xxxxxxxxxxx } }, stageVariables: { } body : }Default response structure{ statusCode: int, body: string, headers: { "Content-Type": "application/json", "x-Custom-Header" : 1" }};Full request/response passthrough

Proxy integrations using Swagger{ "Swagger": "2.0", "paths": { "/{proxy+}": { "x-amazon-apigateway-any-method": { "x-amazon-apigateway-integration": { "type": aws_proxy" } } } }}

Your Node.js Express appThe simplest possible APISimple yet very powerful:Automatically scale to meet demandOnly pay for the requests your receive

Using the API Gateway console

1. Select proxy resource when creating a new resource

Using the API Gateway consoleThe ANY method is created automaticallyConfigure the integration

Running Express applications:The aws-serverless-express libraryhttps://github.com/awslabs/aws-serverless-express

How it works

AWS_PROXY integrations apply a default mapping to requests

And expect a well defined return interfaceAutomatic request mapping{ resource: /orders/{path+}, path: /orders/1423, httpVerb: GET, headers: { Content-Type: application/json, x-custom-header : 1 }, queryStringParameters: { limit: 10 }, pathParameters: { path: 1423 }, requestContext: { }, stageVariables: { } body : }Default response structure{ statusCode: int, body: string, headers: { "Content-Type": "application/json", "x-Custom-Header" : 1" }};

How it works

Mobile apps

Start Lambda function

API GatewayTransform request into event JSON

aws-serverless-express receives the event

ExpressIf not started start express server on local socket

Transform event JSON into HTTP request and send it to local socket

Receive response from local socket and transform it into return value

Your Express code executes

Transform return value into HTTP response

Migrating an Express app

Five simple stepsPull dependencies from npm (include aws-serverless-express)Create JavaScript wrapperZip folder contents including node-modulesCreate Lambda functionCreate API Gateway endpoint as proxy resource

The JavaScript wrapper'use strictconst awsServerlessExpress = require('aws-serverless-express')const app = require('./app')const server = awsServerlessExpress.createServer(app)

exports.handler = (event, context) => { awsServerlessExpress.proxy(server, event, context)}

DEMO

Express on ServerlessAutomatically scales to handle demandOnly pay for requests Unit test your Express app locally just like you do nowUse your code and middlewares, no changes required

We demoed Express, you can do the same with any framework / supported languageSpring bootJerseyFlask

If you are starting from scratch, take a look at some serverless-native frameworksServerless 1.0 - https://serverless.com/Claudia.js - http://bit.ly/claudiajsChalice - http://bit.ly/aws-chaliceZappa - http://bit.ly/py-zappa

30

Best practices

Using AWS Lambda 1:1 Mapping: Every API call triggers a stateless Lambda function - Each express instance will only handle one requests at a time. Dont worry too much about concurrencyMemory: CPU proportional to the memory configured - Increasing memory makes your code execute and start faster (if CPU bound)Lazily load resources: The global scope helps you cache values, load them only when you need them to avoid impacting startup timeOffload tasks to the Gateway: Authorization and metering can be offloaded to Amazon API Gateway. You can also use your middlewares in Express

32

Stefano Buliani@sapessiAWS serverless Express libraryhttp://bit.ly/serverless-expressProxy resources in API Gatewayhttp://bit.ly/proxy-resources-doc

Thank you!