Best Practices and Hard Lessons of Serverless- AWS Startup Day Toronto- Diego Magalhaes

Amazon Web Services
Amazon Web ServicesAmazon Web Services
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Diego Magalhães – Sr. Solutions Architect
The Best Practices and
Hard Lessons Learned of
Serverless Applications
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
https://secure.flickr.com/photos/mgifford/4525333972
Why are we
here today?
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
No servers to provision
or manage
Scales with usage
Never pay for idle Availability and fault
tolerance built in
Serverless means…
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
SERVICES (ANYTHING)
Changes in
data state
Requests to
endpoints
Changes in
resource state
EVENT SOURCE FUNCTION
Node.js
Python
Java
C#
Go
Serverless applications
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Anatomy of a Lambda function
Your
function
Language
runtime
Execution
Environment
Compute
substrate
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Anatomy of a Lambda function
Your
function
Language
runtime
Execution
Environment
Compute
substrate
Places where
you can
impact
performance
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Anatomy of a Lambda function
Your
function
Language
runtime
Execution
Environment
Compute
substrate
Places where
you can
impact
performance
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
The function lifecycle
Bootstrap
the runtime
Start your
code
Full
cold start
Partial
cold start
Warm
start
Download
your code
Start new
container
AWS optimization Your optimization
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS X-Ray Integration with Serverless
• Lambda instruments incoming
requests for all supported
languages
• Lambda runs the X-Ray daemon on
all languages with an SDK
var AWSXRay = require(‘aws-xray-sdk-core‘);
AWSXRay.middleware.setSamplingRules(‘sampling-rules.json’);
var AWS = AWSXRay.captureAWS(require(‘aws-sdk’));
S3Client = AWS.S3();
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Seeing a cold start in AWS X-Ray
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Tweak your function’s computer power
Lambda exposes only a memory control, with the % of CPU
core and network capacity allocated to a function
proportionally
Is your code CPU, Network or memory-bound? If so, it could be cheaper
to choose more memory.
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Smart resource allocation
Match resource allocation (up to 3 GB!) to logic
Stats for Lambda function that calculates 1000 times all prime numbers
<= 1000000
128 MB 11.722965sec $0.024628
256 MB 6.678945sec $0.028035
512 MB 3.194954sec $0.026830
1024 MB 1.465984sec $0.024638
Green==Best Red==Worst
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Smart resource allocation
Match resource allocation (up to 3 GB!) to logic
Stats for Lambda function that calculates 1000 times all prime numbers
<= 1000000
128 MB 11.722965sec $0.024628
256 MB 6.678945sec $0.028035
512 MB 3.194954sec $0.026830
1024 MB 1.465984sec $0.024638
Green==Best Red==Worst
+$0.00001-10.256981sec
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Compute power: Don’t “guesstimate”
alexcasalboni
aws-lambda-power-tuning
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Impact of a memory change
50% increase
in memory
95th percentile
changes from
3s to 2.1s
https://blog.newrelic.com/2017/06/20/lambda-functions-xray-traces-custom-serverless-metrics/
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Multithreading? Maybe!
• <1.8GB is still single core
• CPU bound workloads won’t see gains – processes share same
resources
• >1.8GB is multi core
• CPU bound workloads will gains, but need to multi thread
• I/O bound workloads WILL likely see gains
• e.g. parallel calculations to return
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
The function lifestyle with VPC
Download
your code
Start new
container
Start your
code
Create
VPC ENI
Attach
VPC ENI
Full
cold start
Warm
start
Bootstrap
runtime
Partial
cold start
AWS optimization Your optimization
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Do I need a VPC?
Should my
Lambda
function be
in a VPC?
Does my function
need to access any
specific resources in
a VPC?
Does it also need to
access resources or
services in the public
internet?
Don’t put the
function in a
VPC
Put the
function in a
private subnet
Put the
function in a
subnet with a
NAT’d route
to the
internet
Yes Yes
No No
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
VPC vs. Resilience
• ALWAYS configure a minimum of 2 Availability
Zones
• Give your Lambda functions their own subnets
• Give your Lambda subnets a large IP range to
handle potential scale
• If your functions need to talk to a resource on
the internet, you need a NAT!
• ENIs are a pain, we know, we’re working on it 🤓
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CloudWatch Events ”ping” hack
Largely unnecessary, but if cold starts have a
visible impact on your overall performance:
• Use CloudWatch Events’ scheduled events to
invoke (“ping”) a Lambda function via API call
to the Lambda service
• DO NOT add an unnecessary API Gateway,
for example
• Pass in a payload that you can test for as not
a real payload
• Have a function in your code that handles and
replies accordingly
Lambda
function
event
(time-based)
Amazon API
Gateway
Amazon
Kinesis
Normal
application
logic
“ping”
logic
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Anatomy of a Lambda function
Your
function
Language
runtime
Execution
Environment
Compute
substrate
Places where
you can
impact
performance
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Anatomy of a Lambda function
Handler() function
Function to be executed upon
invocation
Event object
Data sent during Lambda
Function Invocation
Context object
Methods available to interact
with runtime information
(request ID, log group, etc.)
public String handleRequest(Book book, Context context) {
saveBook(book);
return book.getName() + " saved!";
}
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Ephemeral function environment
• Lambda processes a single event
per-container
• No need for non-blocking execution
on the frontend
• REMEMBER – containers are reused
• Lazily load variables in the global
scope
• Don’t load it if you don’t need it – cold
starts are affected
import boto3
client = None
def my_handler(event, context):
global client
if not client:
client =
boto3.client("s3")
# process
const aws = require('aws-sdk');
const gm = require('gm').subClass({imageMagick: true});
const path = require('path');
const s3 = new aws.S3();
const destBucket = process.env.DEST_BUCKET;
exports.handler = function main(event, context) {
...
for (let i = 0; i < event.Records.length; i++) {
tasks.push(conversionPromise(event.Records[i], destBucket));
}
Promise.all(tasks)
.then(() => { context.succeed(); })
.catch((err) => { context.fail(err); });
};
function conversionPromise(record, destBucket) {
...
}
function get(srcBucket, srcKey) {
...
}
function put(destBucket, destKey, data) {
...
Taken from: Sepai App in AWS Serverless Application Repository
https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverl
essrepo:us-east-1:233054207705:applications~sepia
const aws = require('aws-sdk');
const gm = require('gm').subClass({imageMagick: true});
const path = require('path');
const s3 = new aws.S3();
const destBucket = process.env.DEST_BUCKET;
exports.handler = function main(event, context) {
...
for (let i = 0; i < event.Records.length; i++) {
tasks.push(conversionPromise(event.Records[i], destBucket));
}
Promise.all(tasks)
.then(() => { context.succeed(); })
.catch((err) => { context.fail(err); });
};
function conversionPromise(record, destBucket) {
...
}
function get(srcBucket, srcKey) {
...
}
function put(destBucket, destKey, data) {
...
Taken from: Sepai App in AWS Serverless Application Repository
https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverl
essrepo:us-east-1:233054207705:applications~sepia
Load dependencies and create DB/service connections pre-handler
Handler function contains minimal logic
Business logic in their own functions
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Concise function logic
• Separate Lambda handler (entry point) from core logic
• Use functions to TRANSFORM, not TRANSPORT
• Dynamic logic via configuration
• Per function – Environment variables
• Cross function – Amazon Parameter Store/Secrets Manager
• Read only what you need. For example:
• Properly indexed databases
• Query filters in Aurora
• Use S3 select
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
No orchestration in codeSTARTJOB
JOB#XSTARTED
HTTPPOST
HTTPPOST
AREWETHEREYET?
NOPE!
WE’REDONE!
ZzZz
OR
time.sleep(10)
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
No orchestration in code – use AWS Step Functions!
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
theburningmonk.com/2017/07/applying-the-saga-pattern-with-aws-lambda-and-step-functions
Applying Saga pattern with AWS Step Functions
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Efficient function code
• Avoid “fat”/monolithic functions
• Control the dependencies in your
function's deployment package
• Optimize for your language
• Node – Browserfy, Minify
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Lambda execution models
Asynchronous (event)
Amazon
SNS
AWS Lambda
function
Amazon
S3
reqs
Poll-based
Amazon
DynamoDB
Amazon
Kinesis
changes
AWS Lambda
service
function
Synchronous (push)
Amazon
API Gateway
AWS Lambda
function
/order
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Gateways and routers
• Choose suitable entry point for client
applications
• Single, custom client? Use the
AWS SDK
• Not end user facing? use
regional endpoints on API
Gateway
• Discard uninteresting events ASAP
• S3 – Event prefix
• SNS – Message filtering
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Concurrency controls
• Concurrency is a shared pool by default
• Separate using per function concurrency settings
• Acts as reservation
• Also acts as max concurrency per function
• Especially critical for data sources like RDS
• “Kill switch” – set per function concurrency to zero
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
How do I figure out what’s wrong?
These tools are here, so use them!
1. Turn on X-Ray now
1. look at wrapping your own calls with it via the X-Ray SDKs
2. Don’t underestimate the power of logging in Lambda
1. Simple “debug: in functionX” statements work great and are easy to
find in CloudWatch Logs
3. The most valuable metrics are the ones closest to your
customer/use-case
1. How many gizmos did this function call/create/process/etc
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Lambda Dead Letter Queues
“By default, a failed Lambda function invoked asynchronously
is retried twice, and then the event is discarded. Using Dead
Letter Queues (DLQ), you can indicate to Lambda that
unprocessed events should be sent to an Amazon SQS queue
or Amazon SNS topic instead, where you can take further
action.” –
https://docs.aws.amazon.com/lambda/latest/dg/dlq.html
• Turn this on! (for async use-cases)
• Monitor it via an SQS Queue length metric/alarm
• If you use SNS, send the messages to something durable
and/or a trusted endpoint for processing
• Can send to Lambda functions in other regions
• If and when things go “boom” DLQ can save your
invocation event information
☠️
✉️
Q
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Lambda Dead Letter Queues
“By default, a failed Lambda function invoked asynchronously
is retried twice, and then the event is discarded. Using Dead
Letter Queues (DLQ), you can indicate to Lambda that
unprocessed events should be sent to an Amazon SQS queue
or Amazon SNS topic instead, where you can take further
action.” –
https://docs.aws.amazon.com/lambda/latest/dg/dlq.html
• Turn this on! (for async use-cases)
• Monitor it via an SQS Queue length metric/alarm
• If you use SNS, send the messages to something durable
and/or a trusted endpoint for processing
• Can send to Lambda functions in other regions
• If and when things go “boom” DLQ can save your
invocation event information
☠️
✉️
Q
As of June 28 2018 you can
now directly subscribe a
Lambda function to an SQS
Queue to automatically react
DLQ’d messages!
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Lambda execution models
Poll-Based
Amazon
SQS
messages
AWS Lambda
service
function
NEW! NEW!
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Deployment best practices – Multi-acct
aws.amazon.com/blogs/compute/managing-cross-account-serverless-microservices/
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Deployment best practices – Safe deployments
AWS Lambda Function
AWS Lambda Function
AWS CodeDeploy
Updates Lambda
Weighted Aliases
Configuration
10% of Traffic
Every 5 min
Every 10 min
Every 15 min
….
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
aws.amazon.com/serverless
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Diego Magalhães
diegogm@amazon.com
@dgomesbrhttps://www.flickr.com/photos/theredproject/3302110152/
© 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
?
https://secure.flickr.com/photos/dullhunk/202872717/
1 of 43

Recommended

High Performance Web Pages - 20 new best practices by
High Performance Web Pages - 20 new best practicesHigh Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesStoyan Stefanov
50.1K views76 slides
深入淺出 AWS 混合式雲端架構 by
深入淺出 AWS 混合式雲端架構 深入淺出 AWS 混合式雲端架構
深入淺出 AWS 混合式雲端架構 Amazon Web Services
2.5K views44 slides
Deep Dive - Amazon Relational Database Services_AWSPSSummit_Singapore by
Deep Dive - Amazon Relational Database Services_AWSPSSummit_SingaporeDeep Dive - Amazon Relational Database Services_AWSPSSummit_Singapore
Deep Dive - Amazon Relational Database Services_AWSPSSummit_SingaporeAmazon Web Services
120 views37 slides
AWS Summit Stockholm 2014 – T2 – Understanding AWS security by
AWS Summit Stockholm 2014 – T2 – Understanding AWS securityAWS Summit Stockholm 2014 – T2 – Understanding AWS security
AWS Summit Stockholm 2014 – T2 – Understanding AWS securityAmazon Web Services
1.6K views81 slides
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13 by
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #1320210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13
20210127 今日から始めるイベントドリブンアーキテクチャ AWS Expert Online #13Amazon Web Services Japan
3.6K views102 slides
국내 미디어 고객사의 AWS 활용 사례 - POOQ 서비스, 콘텐츠연합플랫폼::조휘열::AWS Summit Seoul 2018 by
국내 미디어 고객사의 AWS 활용 사례 - POOQ 서비스, 콘텐츠연합플랫폼::조휘열::AWS Summit Seoul 2018국내 미디어 고객사의 AWS 활용 사례 - POOQ 서비스, 콘텐츠연합플랫폼::조휘열::AWS Summit Seoul 2018
국내 미디어 고객사의 AWS 활용 사례 - POOQ 서비스, 콘텐츠연합플랫폼::조휘열::AWS Summit Seoul 2018Amazon Web Services Korea
3K views46 slides

More Related Content

What's hot

遷移到 AWS 雲端旅程的方法與工具 by
遷移到 AWS 雲端旅程的方法與工具遷移到 AWS 雲端旅程的方法與工具
遷移到 AWS 雲端旅程的方法與工具Amazon Web Services
974 views52 slides
[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ... by
[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ...[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ...
[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ...Amazon Web Services Korea
1.4K views47 slides
Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -... by
Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -...Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -...
Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -...Amazon Web Services
372 views37 slides
Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A... by
Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A...Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A...
Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A...Amazon Web Services Korea
2.3K views109 slides
20200331 AWS Black Belt Online Seminar AWS Elemental MediaConvert by
20200331 AWS Black Belt Online Seminar AWS Elemental MediaConvert20200331 AWS Black Belt Online Seminar AWS Elemental MediaConvert
20200331 AWS Black Belt Online Seminar AWS Elemental MediaConvertAmazon Web Services Japan
4.7K views72 slides
AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018 by
AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018
AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018Amazon Web Services Korea
2.1K views30 slides

What's hot(20)

[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ... by Amazon Web Services Korea
[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ...[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ...
[AWS Media Symposium 2019] Perfecting the Media Experience with AWS - Bhavik ...
Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -... by Amazon Web Services
Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -...Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -...
Move Your Desktops and Apps to AWS with Amazon WorkSpaces and AppStream 2.0 -...
Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A... by Amazon Web Services Korea
Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A...Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A...
Airbnb가 직접 들려주는 Kubernetes 환경 구축 이야기 - Melanie Cebula 소프트웨어 엔지니어, Airbnb :: A...
AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018 by Amazon Web Services Korea
AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018
AWS Serverless 활용 네트워크 보안 아키텍처::함인용 실장, 이성현 매니저, 솔트웨어::AWS Summit Seoul 2018
High Performance Computing in AWS, Immersion Day Huntsville 2019 by Amazon Web Services
High Performance Computing in AWS, Immersion Day Huntsville 2019High Performance Computing in AWS, Immersion Day Huntsville 2019
High Performance Computing in AWS, Immersion Day Huntsville 2019
Computação de Alta Performance (HPC) na AWS - CMP201 - Sao Paulo Summit by Amazon Web Services
Computação de Alta Performance (HPC) na AWS -  CMP201 - Sao Paulo SummitComputação de Alta Performance (HPC) na AWS -  CMP201 - Sao Paulo Summit
Computação de Alta Performance (HPC) na AWS - CMP201 - Sao Paulo Summit
AWS Partner Engagement Opportunities for DoD, Immersion Day Huntsville 2019 by Amazon Web Services
AWS Partner Engagement Opportunities for DoD, Immersion Day Huntsville 2019AWS Partner Engagement Opportunities for DoD, Immersion Day Huntsville 2019
AWS Partner Engagement Opportunities for DoD, Immersion Day Huntsville 2019
AWS Cloud Value Framework - ENT202 - Sao Paulo Summit by Amazon Web Services
AWS Cloud Value Framework -  ENT202 - Sao Paulo SummitAWS Cloud Value Framework -  ENT202 - Sao Paulo Summit
AWS Cloud Value Framework - ENT202 - Sao Paulo Summit
초보 개발자도 바로 따라할 수 있는 AWS 미디어 서비스를 이용한 Live/VOD 서비스 구축 – 현륜식 AWS 솔루션즈 아키텍트:: A... by Amazon Web Services Korea
초보 개발자도 바로 따라할 수 있는 AWS 미디어 서비스를 이용한 Live/VOD 서비스 구축 – 현륜식 AWS  솔루션즈 아키텍트:: A...초보 개발자도 바로 따라할 수 있는 AWS 미디어 서비스를 이용한 Live/VOD 서비스 구축 – 현륜식 AWS  솔루션즈 아키텍트:: A...
초보 개발자도 바로 따라할 수 있는 AWS 미디어 서비스를 이용한 Live/VOD 서비스 구축 – 현륜식 AWS 솔루션즈 아키텍트:: A...
Set Up a Million-Core Cluster to Accelerate HPC Workloads (CMP404) - AWS re:I... by Amazon Web Services
Set Up a Million-Core Cluster to Accelerate HPC Workloads (CMP404) - AWS re:I...Set Up a Million-Core Cluster to Accelerate HPC Workloads (CMP404) - AWS re:I...
Set Up a Million-Core Cluster to Accelerate HPC Workloads (CMP404) - AWS re:I...
Amazon Web Services1.4K views
Running a High-Performance Kubernetes Cluster with Amazon EKS (CON318-R1) - A... by Amazon Web Services
Running a High-Performance Kubernetes Cluster with Amazon EKS (CON318-R1) - A...Running a High-Performance Kubernetes Cluster with Amazon EKS (CON318-R1) - A...
Running a High-Performance Kubernetes Cluster with Amazon EKS (CON318-R1) - A...
Amazon Web Services5.8K views
Aws container webinar day 1 by HoseokSeo7
Aws container webinar day 1Aws container webinar day 1
Aws container webinar day 1
HoseokSeo7167 views
Aws container webinar day 2 by HoseokSeo7
Aws container webinar day 2Aws container webinar day 2
Aws container webinar day 2
HoseokSeo7140 views
Secured API Acceleration with Engineers from Amazon CloudFront and Slack by Amazon Web Services
Secured API Acceleration with Engineers from Amazon CloudFront and SlackSecured API Acceleration with Engineers from Amazon CloudFront and Slack
Secured API Acceleration with Engineers from Amazon CloudFront and Slack
Amazon Web Services18.5K views

Similar to Best Practices and Hard Lessons of Serverless- AWS Startup Day Toronto- Diego Magalhaes

The Best Practices and Hard Lessons Learned of Serverless Applications by
The Best Practices and Hard Lessons Learned of Serverless ApplicationsThe Best Practices and Hard Lessons Learned of Serverless Applications
The Best Practices and Hard Lessons Learned of Serverless ApplicationsAmazon Web Services LATAM
153 views40 slides
AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser... by
AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser...AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser...
AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser...Amazon Web Services
146 views41 slides
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ... by
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...Amazon Web Services
518 views41 slides
AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o... by
AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o...AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o...
AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o...Chris Munns
670 views41 slides
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl... by
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...Chris Munns
477 views39 slides
Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW... by
Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW...Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW...
Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW...Amazon Web Services
2.9K views64 slides

Similar to Best Practices and Hard Lessons of Serverless- AWS Startup Day Toronto- Diego Magalhaes(20)

AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser... by Amazon Web Services
AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser...AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser...
AWS18 Startup Day Toronto- The Best Practices and Hard Lessons Learned of Ser...
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ... by Amazon Web Services
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
The Best Practices and Hard Lessons Learned of Serverless Applications - AWS ...
AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o... by Chris Munns
AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o...AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o...
AWS Startup Day - Boston 2018 - The Best Practices and Hard Lessons Learned o...
Chris Munns670 views
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl... by Chris Munns
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
Chris Munns477 views
Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW... by Amazon Web Services
Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW...Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW...
Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW...
Amazon Web Services2.9K views
Serverless on AWS: Architectural Patterns and Best Practices by Vladimir Simek
Serverless on AWS: Architectural Patterns and Best PracticesServerless on AWS: Architectural Patterns and Best Practices
Serverless on AWS: Architectural Patterns and Best Practices
Vladimir Simek422 views
AWS Lambda use cases and best practices - Builders Day Israel by Amazon Web Services
AWS Lambda use cases and best practices - Builders Day IsraelAWS Lambda use cases and best practices - Builders Day Israel
AWS Lambda use cases and best practices - Builders Day Israel
Amazon Web Services2.2K views
2018 10-19-jc conf-embrace-legacy-java-ee-by-aws-serverless by Kim Kao
2018 10-19-jc conf-embrace-legacy-java-ee-by-aws-serverless2018 10-19-jc conf-embrace-legacy-java-ee-by-aws-serverless
2018 10-19-jc conf-embrace-legacy-java-ee-by-aws-serverless
Kim Kao279 views
Driving Innovation with Serverless Applications (GPSBUS212) - AWS re:Invent 2018 by Amazon Web Services
Driving Innovation with Serverless Applications (GPSBUS212) - AWS re:Invent 2018Driving Innovation with Serverless Applications (GPSBUS212) - AWS re:Invent 2018
Driving Innovation with Serverless Applications (GPSBUS212) - AWS re:Invent 2018
Practical Guidance for Increasing your Serverless Application's Security by Chris Munns
Practical Guidance for Increasing your Serverless Application's SecurityPractical Guidance for Increasing your Serverless Application's Security
Practical Guidance for Increasing your Serverless Application's Security
Chris Munns433 views
使用 AWS Step Functions 靈活調度 AWS Lambda (Level:200) by Amazon Web Services
使用 AWS Step Functions 靈活調度 AWS Lambda (Level:200)使用 AWS Step Functions 靈活調度 AWS Lambda (Level:200)
使用 AWS Step Functions 靈活調度 AWS Lambda (Level:200)
Serverless Architectural Patterns and Best Practices by Amazon Web Services
Serverless Architectural Patterns and Best PracticesServerless Architectural Patterns and Best Practices
Serverless Architectural Patterns and Best Practices
Building Advanced Serverless Workflows with AWS Step Functions | AWS Floor28 by Amazon Web Services
Building Advanced Serverless Workflows with AWS Step Functions | AWS Floor28Building Advanced Serverless Workflows with AWS Step Functions | AWS Floor28
Building Advanced Serverless Workflows with AWS Step Functions | AWS Floor28
Amazon Web Services1.8K views
Design and Implement a Serverless Media-Processing Workflow - SRV328 - Atlant... by Amazon Web Services
Design and Implement a Serverless Media-Processing Workflow - SRV328 - Atlant...Design and Implement a Serverless Media-Processing Workflow - SRV328 - Atlant...
Design and Implement a Serverless Media-Processing Workflow - SRV328 - Atlant...
Serverless use cases with AWS Lambda - More Serverless Event by Boaz Ziniman
Serverless use cases with AWS Lambda - More Serverless EventServerless use cases with AWS Lambda - More Serverless Event
Serverless use cases with AWS Lambda - More Serverless Event
Boaz Ziniman481 views
Serverless best practices plus design principles 20m version by Heitor Lessa
Serverless   best practices plus design principles 20m versionServerless   best practices plus design principles 20m version
Serverless best practices plus design principles 20m version
Heitor Lessa448 views

More from Amazon Web Services

Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn... by
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Amazon Web Services
26.5K views46 slides
Big Data per le Startup: come creare applicazioni Big Data in modalità Server... by
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Amazon Web Services
5.6K views44 slides
Esegui pod serverless con Amazon EKS e AWS Fargate by
Esegui pod serverless con Amazon EKS e AWS FargateEsegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS FargateAmazon Web Services
4.1K views62 slides
Costruire Applicazioni Moderne con AWS by
Costruire Applicazioni Moderne con AWSCostruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSAmazon Web Services
2.8K views61 slides
Come spendere fino al 90% in meno con i container e le istanze spot by
Come spendere fino al 90% in meno con i container e le istanze spot Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot Amazon Web Services
1.8K views21 slides
Open banking as a service by
Open banking as a serviceOpen banking as a service
Open banking as a serviceAmazon Web Services
7.1K views14 slides

More from Amazon Web Services(20)

Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn... by Amazon Web Services
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Amazon Web Services26.5K views
Big Data per le Startup: come creare applicazioni Big Data in modalità Server... by Amazon Web Services
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Amazon Web Services5.6K views
Esegui pod serverless con Amazon EKS e AWS Fargate by Amazon Web Services
Esegui pod serverless con Amazon EKS e AWS FargateEsegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS Fargate
Amazon Web Services4.1K views
Come spendere fino al 90% in meno con i container e le istanze spot by Amazon Web Services
Come spendere fino al 90% in meno con i container e le istanze spot Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot
Amazon Web Services1.8K views
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea... by Amazon Web Services
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Amazon Web Services3.3K views
OpsWorks Configuration Management: automatizza la gestione e i deployment del... by Amazon Web Services
OpsWorks Configuration Management: automatizza la gestione e i deployment del...OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
Amazon Web Services2.6K views
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads by Amazon Web Services
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Amazon Web Services1.7K views
Database Oracle e VMware Cloud on AWS i miti da sfatare by Amazon Web Services
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatare
Amazon Web Services1.3K views
Crea la tua prima serverless ledger-based app con QLDB e NodeJS by Amazon Web Services
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Amazon Web Services1.9K views
API moderne real-time per applicazioni mobili e web by Amazon Web Services
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e web
Amazon Web Services1.5K views
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare by Amazon Web Services
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Amazon Web Services1.5K views
AWS_HK_StartupDay_Building Interactive websites while automating for efficien... by Amazon Web Services
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
Introduzione a Amazon Elastic Container Service by Amazon Web Services
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container Service
Amazon Web Services2.7K views

Best Practices and Hard Lessons of Serverless- AWS Startup Day Toronto- Diego Magalhaes

  • 1. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Diego Magalhães – Sr. Solutions Architect The Best Practices and Hard Lessons Learned of Serverless Applications
  • 2. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. https://secure.flickr.com/photos/mgifford/4525333972 Why are we here today?
  • 3. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. No servers to provision or manage Scales with usage Never pay for idle Availability and fault tolerance built in Serverless means…
  • 4. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. SERVICES (ANYTHING) Changes in data state Requests to endpoints Changes in resource state EVENT SOURCE FUNCTION Node.js Python Java C# Go Serverless applications
  • 5. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Anatomy of a Lambda function Your function Language runtime Execution Environment Compute substrate
  • 6. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Anatomy of a Lambda function Your function Language runtime Execution Environment Compute substrate Places where you can impact performance
  • 7. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Anatomy of a Lambda function Your function Language runtime Execution Environment Compute substrate Places where you can impact performance
  • 8. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. The function lifecycle Bootstrap the runtime Start your code Full cold start Partial cold start Warm start Download your code Start new container AWS optimization Your optimization
  • 9. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. AWS X-Ray Integration with Serverless • Lambda instruments incoming requests for all supported languages • Lambda runs the X-Ray daemon on all languages with an SDK var AWSXRay = require(‘aws-xray-sdk-core‘); AWSXRay.middleware.setSamplingRules(‘sampling-rules.json’); var AWS = AWSXRay.captureAWS(require(‘aws-sdk’)); S3Client = AWS.S3();
  • 10. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Seeing a cold start in AWS X-Ray
  • 11. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Tweak your function’s computer power Lambda exposes only a memory control, with the % of CPU core and network capacity allocated to a function proportionally Is your code CPU, Network or memory-bound? If so, it could be cheaper to choose more memory.
  • 12. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Smart resource allocation Match resource allocation (up to 3 GB!) to logic Stats for Lambda function that calculates 1000 times all prime numbers <= 1000000 128 MB 11.722965sec $0.024628 256 MB 6.678945sec $0.028035 512 MB 3.194954sec $0.026830 1024 MB 1.465984sec $0.024638 Green==Best Red==Worst
  • 13. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Smart resource allocation Match resource allocation (up to 3 GB!) to logic Stats for Lambda function that calculates 1000 times all prime numbers <= 1000000 128 MB 11.722965sec $0.024628 256 MB 6.678945sec $0.028035 512 MB 3.194954sec $0.026830 1024 MB 1.465984sec $0.024638 Green==Best Red==Worst +$0.00001-10.256981sec
  • 14. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Compute power: Don’t “guesstimate” alexcasalboni aws-lambda-power-tuning
  • 15. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Impact of a memory change 50% increase in memory 95th percentile changes from 3s to 2.1s https://blog.newrelic.com/2017/06/20/lambda-functions-xray-traces-custom-serverless-metrics/
  • 16. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Multithreading? Maybe! • <1.8GB is still single core • CPU bound workloads won’t see gains – processes share same resources • >1.8GB is multi core • CPU bound workloads will gains, but need to multi thread • I/O bound workloads WILL likely see gains • e.g. parallel calculations to return
  • 17. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. The function lifestyle with VPC Download your code Start new container Start your code Create VPC ENI Attach VPC ENI Full cold start Warm start Bootstrap runtime Partial cold start AWS optimization Your optimization
  • 18. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Do I need a VPC? Should my Lambda function be in a VPC? Does my function need to access any specific resources in a VPC? Does it also need to access resources or services in the public internet? Don’t put the function in a VPC Put the function in a private subnet Put the function in a subnet with a NAT’d route to the internet Yes Yes No No
  • 19. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. VPC vs. Resilience • ALWAYS configure a minimum of 2 Availability Zones • Give your Lambda functions their own subnets • Give your Lambda subnets a large IP range to handle potential scale • If your functions need to talk to a resource on the internet, you need a NAT! • ENIs are a pain, we know, we’re working on it 🤓
  • 20. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. CloudWatch Events ”ping” hack Largely unnecessary, but if cold starts have a visible impact on your overall performance: • Use CloudWatch Events’ scheduled events to invoke (“ping”) a Lambda function via API call to the Lambda service • DO NOT add an unnecessary API Gateway, for example • Pass in a payload that you can test for as not a real payload • Have a function in your code that handles and replies accordingly Lambda function event (time-based) Amazon API Gateway Amazon Kinesis Normal application logic “ping” logic
  • 21. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Anatomy of a Lambda function Your function Language runtime Execution Environment Compute substrate Places where you can impact performance
  • 22. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Anatomy of a Lambda function Handler() function Function to be executed upon invocation Event object Data sent during Lambda Function Invocation Context object Methods available to interact with runtime information (request ID, log group, etc.) public String handleRequest(Book book, Context context) { saveBook(book); return book.getName() + " saved!"; }
  • 23. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Ephemeral function environment • Lambda processes a single event per-container • No need for non-blocking execution on the frontend • REMEMBER – containers are reused • Lazily load variables in the global scope • Don’t load it if you don’t need it – cold starts are affected import boto3 client = None def my_handler(event, context): global client if not client: client = boto3.client("s3") # process
  • 24. const aws = require('aws-sdk'); const gm = require('gm').subClass({imageMagick: true}); const path = require('path'); const s3 = new aws.S3(); const destBucket = process.env.DEST_BUCKET; exports.handler = function main(event, context) { ... for (let i = 0; i < event.Records.length; i++) { tasks.push(conversionPromise(event.Records[i], destBucket)); } Promise.all(tasks) .then(() => { context.succeed(); }) .catch((err) => { context.fail(err); }); }; function conversionPromise(record, destBucket) { ... } function get(srcBucket, srcKey) { ... } function put(destBucket, destKey, data) { ... Taken from: Sepai App in AWS Serverless Application Repository https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverl essrepo:us-east-1:233054207705:applications~sepia
  • 25. const aws = require('aws-sdk'); const gm = require('gm').subClass({imageMagick: true}); const path = require('path'); const s3 = new aws.S3(); const destBucket = process.env.DEST_BUCKET; exports.handler = function main(event, context) { ... for (let i = 0; i < event.Records.length; i++) { tasks.push(conversionPromise(event.Records[i], destBucket)); } Promise.all(tasks) .then(() => { context.succeed(); }) .catch((err) => { context.fail(err); }); }; function conversionPromise(record, destBucket) { ... } function get(srcBucket, srcKey) { ... } function put(destBucket, destKey, data) { ... Taken from: Sepai App in AWS Serverless Application Repository https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverl essrepo:us-east-1:233054207705:applications~sepia Load dependencies and create DB/service connections pre-handler Handler function contains minimal logic Business logic in their own functions
  • 26. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Concise function logic • Separate Lambda handler (entry point) from core logic • Use functions to TRANSFORM, not TRANSPORT • Dynamic logic via configuration • Per function – Environment variables • Cross function – Amazon Parameter Store/Secrets Manager • Read only what you need. For example: • Properly indexed databases • Query filters in Aurora • Use S3 select
  • 27. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. No orchestration in codeSTARTJOB JOB#XSTARTED HTTPPOST HTTPPOST AREWETHEREYET? NOPE! WE’REDONE! ZzZz OR time.sleep(10)
  • 28. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. No orchestration in code – use AWS Step Functions!
  • 29. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. theburningmonk.com/2017/07/applying-the-saga-pattern-with-aws-lambda-and-step-functions Applying Saga pattern with AWS Step Functions
  • 30. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Efficient function code • Avoid “fat”/monolithic functions • Control the dependencies in your function's deployment package • Optimize for your language • Node – Browserfy, Minify
  • 31. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda execution models Asynchronous (event) Amazon SNS AWS Lambda function Amazon S3 reqs Poll-based Amazon DynamoDB Amazon Kinesis changes AWS Lambda service function Synchronous (push) Amazon API Gateway AWS Lambda function /order
  • 32. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Gateways and routers • Choose suitable entry point for client applications • Single, custom client? Use the AWS SDK • Not end user facing? use regional endpoints on API Gateway • Discard uninteresting events ASAP • S3 – Event prefix • SNS – Message filtering
  • 33. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Concurrency controls • Concurrency is a shared pool by default • Separate using per function concurrency settings • Acts as reservation • Also acts as max concurrency per function • Especially critical for data sources like RDS • “Kill switch” – set per function concurrency to zero
  • 34. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. How do I figure out what’s wrong? These tools are here, so use them! 1. Turn on X-Ray now 1. look at wrapping your own calls with it via the X-Ray SDKs 2. Don’t underestimate the power of logging in Lambda 1. Simple “debug: in functionX” statements work great and are easy to find in CloudWatch Logs 3. The most valuable metrics are the ones closest to your customer/use-case 1. How many gizmos did this function call/create/process/etc
  • 35. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda Dead Letter Queues “By default, a failed Lambda function invoked asynchronously is retried twice, and then the event is discarded. Using Dead Letter Queues (DLQ), you can indicate to Lambda that unprocessed events should be sent to an Amazon SQS queue or Amazon SNS topic instead, where you can take further action.” – https://docs.aws.amazon.com/lambda/latest/dg/dlq.html • Turn this on! (for async use-cases) • Monitor it via an SQS Queue length metric/alarm • If you use SNS, send the messages to something durable and/or a trusted endpoint for processing • Can send to Lambda functions in other regions • If and when things go “boom” DLQ can save your invocation event information ☠️ ✉️ Q
  • 36. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda Dead Letter Queues “By default, a failed Lambda function invoked asynchronously is retried twice, and then the event is discarded. Using Dead Letter Queues (DLQ), you can indicate to Lambda that unprocessed events should be sent to an Amazon SQS queue or Amazon SNS topic instead, where you can take further action.” – https://docs.aws.amazon.com/lambda/latest/dg/dlq.html • Turn this on! (for async use-cases) • Monitor it via an SQS Queue length metric/alarm • If you use SNS, send the messages to something durable and/or a trusted endpoint for processing • Can send to Lambda functions in other regions • If and when things go “boom” DLQ can save your invocation event information ☠️ ✉️ Q As of June 28 2018 you can now directly subscribe a Lambda function to an SQS Queue to automatically react DLQ’d messages!
  • 37. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Lambda execution models Poll-Based Amazon SQS messages AWS Lambda service function NEW! NEW!
  • 38. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Deployment best practices – Multi-acct aws.amazon.com/blogs/compute/managing-cross-account-serverless-microservices/
  • 39. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Deployment best practices – Safe deployments AWS Lambda Function AWS Lambda Function AWS CodeDeploy Updates Lambda Weighted Aliases Configuration 10% of Traffic Every 5 min Every 10 min Every 15 min ….
  • 40. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. aws.amazon.com/serverless
  • 41. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
  • 42. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Diego Magalhães diegogm@amazon.com @dgomesbrhttps://www.flickr.com/photos/theredproject/3302110152/
  • 43. © 2018, Amazon Web Services, Inc. or its Affiliates. All rights reserved. ? https://secure.flickr.com/photos/dullhunk/202872717/