SlideShare a Scribd company logo
1 of 38
Download to read offline
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Serverless functions deep dive
Danilo Poccia
Principal Evangelist, Serverless
AWS
@danilop
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS operational responsibility models
On-Premises Cloud
Less More
Compute Virtual Machine
EC2 Elastic Beanstalk AWS LambdaFargate
Databases MySQL MySQL on EC2
RDS MySQL RDS Aurora Aurora Serverless DynamoDB
Storage Storage
S3
Messaging ESBs
Amazon MQ Kinesis SQS / SNS
Analytics
Hadoop Hadoop on EC2 EMR Elasticsearch Service Athena
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Serverless applications
Services (anything)
Changes in
data state
Requests to
endpoints
Changes in
resource state
Event source Function
Node.js
Python
Java
C#
Go
Ruby
Runtime API
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
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, more)
import json
def lambda_handler(event, context):
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello World!')
}
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Lambda Layers
Lets functions easily share code: Upload layer
once, reference within any function
Promote separation of responsibilities, lets
developers iterate faster on writing business logic
Built in support for secure sharing by ecosystem
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Using Lambda Layers
• Put common components in a ZIP file and
upload it as a Lambda Layer
• Layers are immutable and can be versioned
to manage updates
• When a version is deleted or permissions to
use it are revoked, functions that used it
previously will continue to work, but you
won’t be able to create new ones
• You can reference up to five layers, one of
which can optionally be a custom runtime
Lambda
Layers
arn:aws:lambda:region:accountId:layer:shared-lib
Lambda
Layers
arn:aws:lambda:region:accountId:layer:shared-lib:2
Lambda
Layers
arn:aws:lambda:region:accountId:layer:shared-lib:3
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Lambda Runtime API
Bring any Linux compatible language runtime
Powered by new Runtime API - Codifies the
runtime calling conventions and integration points
At launch, custom runtimes powering Ruby
support in AWS Lambda, more runtimes from
partners (like Erlang)
Custom runtimes distributed as “layers”
Rule
Stack
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Runtime Bootstrap
• The bootstrap executable act as a bridge
between the Runtime HTTP API and the
Function to be executed
• Bootstrap needs to manage response/error
handling, context creation and function
execution
• Information on the interface endpoint and the
function handler are shared as environment
variables
/runtime API
/invocation/next
/init/error /ID/error
/invocation/ID/response
/invocation/ID/error
bootstrap
Process events/headers
Clean up
Initialize and Invoke function
Response/Error handling
Lambda
Function
Build PCI and HIPAA compliant serverless applications!
Serverless platform services that can be used in both:
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Start with a framework
AWS
Chalice
AWS Amplify
AWS
SAM
AWS: Third-party:
Serverless
Framework
Meet
SAM!
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS Serverless Application Model (SAM)
AWS CloudFormation extension optimized for
serverless
Special serverless resource types: Functions, APIs,
SimpleTables, Layers, and Applications
Supports anything AWS CloudFormation supports
Open specification (Apache 2.0)
https://aws.amazon.com/serverless/sam
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
SAM template
AWSTemplateFormatVersion: '2010-09-09’
Transform: AWS::Serverless-2016-10-31
Resources:
GetFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.get
Runtime: nodejs8.10
CodeUri: src/
Policies:
- DynamoDBReadPolicy:
TableName: !Ref MyTable
Events:
GetResource:
Type: Api
Properties:
Path: /resource/{resourceId}
Method: get
MyTable:
Type: AWS::Serverless::SimpleTable
Just 20 lines to create:
• Lambda function
• IAM role
• API Gateway
• DynamoDB table
O
pen
Source
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS SAM Command Line Interface (AWS SAM CLI)
CLI tool for local development, debugging, testing,
deploying, and monitoring of serverless applications
Supports API Gateway “proxy-style” and Lambda service API
testing
Response object and function logs available on your local
machine
Uses open source docker-lambda images to mimic
Lambda’s execution environment such as timeout, memory
limits, runtimes
Can tail production logs from CloudWatch logs
Can help you build in native dependencies
https://aws.amazon.com/serverless/sam
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
SAM CLI
sam init --name my-app --runtime python
cd my-app/
sam local ...
sam validate # The SAM template
sam build
sam package --s3-bucket my-packages-bucket 
--output-template-file packaged.yaml
sam deploy --template-file packaged.yaml 
--stack-name my-app-prod
sam publish # To the AWS Serverless Application Repository
O
pen
Source
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
With the AWS Serverless Application Repository:
Developers can…
• Discover and deploy ready-made apps and
code samples
• Combine applications in the app repository
with their own via Nested Applications
• Customize open-source apps to get started
quickly
• Share apps privately or publish apps
for public use
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
TweetSource:
Type: AWS::Serverless::Application
Properties:
Location:
ApplicationId: arn:aws:serverlessrepo:...
SemanticVersion: 2.0.0
Parameters:
TweetProcessorFunctionName: !Ref MyFunction
SearchText: '#serverless -filter:nativeretweets'
Nested apps to simplify solving recurring problems
Standard
Component
Custom
Business
Logic
Polling schedule
(CloudWatch
Events rule)
trigger
TwitterProcessor
SearchCheckpoint
TwitterSearchPoller
Twitter
Search API
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS SAM Template Capabilities
• Can mix in other non-SAM CloudFormation
resources in the same template
• i.e. Amazon S3, Amazon Kinesis, AWS Step Functions
• Supports use of Parameters, Mappings,
Outputs, etc
• Supports Intrinsic Functions
• Can use ImportValue
(exceptions for RestApiId, Policies, StageName attributes)
• YAML or JSON
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS Lambda Environment Variables
• Key-value pairs that you can dynamically pass to
your function
• Available via standard environment variable APIs
such as process.env for Node.js or os.environ for
Python
• Can optionally be encrypted via AWS Key
Management Service (KMS)
• Allows you to specify in IAM what roles have access to
the keys to decrypt the information
• Useful for creating environments per stage (i.e.
dev, testing, production)
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Amazon API Gateway Stage Variables
Stage variables act like environment variables
• Use stage variables to store configuration values
• Stage variables are available in the $context object
• Values are accessible from most fields in API
Gateway
• Lambda function ARN
• HTTP endpoint
• Custom authorizer function name
• Parameter mappings
AWS Lambda and Amazon API Gateway Variables + SAM
Parameters:
MyEnvironment:
Type: String
Default: testing
AllowedValues:
- test
- staging
- prod
Description: Environment of this stack of
resources
Mappings:
SpecialFeature1:
test:
status: on
staging:
status: on
prod:
status: off
#Lambda
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
…
Environment:
Variables:
ENVIRONMENT: !Ref: MyEnvironment
Spec_Feature1: !FindInMap [SpecialFeature1,
!Ref MyEnvironment, status]
…
#API Gateway
MyApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
…
Variables:
ENVIRONMENT: !Ref: MyEnvironment
Parameters:
MyEnvironment:
Type: String
Default: testing
AllowedValues:
- testing
- staging
- prod
Description: Environment of this stack of
resources
Mappings:
SpecialFeature1:
testing:
status: on
staging:
status: on
prod:
status: off
#Lambda
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
…
Environment:
Variables:
ENVIRONMENT: !Ref: MyEnvironment
Spec_Feature1: !FindInMap [SpecialFeature1,
!Ref MyEnvironment, status]
…
#API Gateway
MyApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
…
Variables:
ENVIRONMENT: !Ref: MyEnvironment
AWS Lambda and Amazon API Gateway Variables + SAM
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs6.10
AutoPublishAlias: !Ref ENVIRONMENT
DeploymentPreference:
Type: Linear10PercentEvery10Minutes
Alarms:
# A list of alarms that you want to monitor
- !Ref AliasErrorMetricGreaterThanZeroAlarm
- !Ref LatestVersionErrorMetricGreaterThanZeroAlarm
Hooks:
# Validation Lambda functions that are run before & after traffic shifting
PreTraffic: !Ref PreTrafficLambdaFunction
PostTraffic: !Ref PostTrafficLambdaFunction
AWS SAM + Safe Deployments
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS Lambda Alias Traffic Shifting & AWS SAM
AutoPublishAlias
By adding this property and specifying an
alias name, AWS SAM will do the
following:
• Detect when new code is being
deployed based on changes to the
Lambda function's Amazon S3 URI.
• Create and publish an updated version
of that function with the latest code.
• Create an alias with a name you
provide (unless an alias already exists)
and points to the updated version of
the Lambda function.
Deployment Preference Type
Canary10Percent30Minutes
Canary10Percent5Minutes
Canary10Percent10Minutes
Canary10Percent15Minutes
Linear10PercentEvery10Minutes
Linear10PercentEvery1Minute
Linear10PercentEvery2Minutes
Linear10PercentEvery3Minutes
AllAtOnce
In SAM:
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Alarms: # A list of alarms that you want to monitor
- !Ref AliasErrorMetricGreaterThanZeroAlarm
- !Ref LatestVersionErrorMetricGreaterThanZeroAlarm
Hooks: # Validation Lambda functions that are run before & after
traffic shifting
PreTraffic: !Ref PreTrafficLambdaFunction
PostTraffic: !Ref PostTrafficLambdaFunction
AWS Lambda Alias Traffic Shifting & AWS SAM
Note: You can specify a maximum of 10
alarms
In SAM:
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Globals:
Function:
Runtime: nodejs6.10
CodeUri: s3://code-artifacts/pet_app1234.zip
MemorySize: 1024
Timeout: 30
AutoPublishAlias: !Ref ENVIRONMENT
getDogsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: getdogs.handler
Events:
GetDogs:
Type: Api
Properties:
Path: /Dogs
Method: ANY
getCatsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: getCats.handler
Events:
GetCats:
Type: Api
Properties:
Path: /Cats
Method: ANY
getBirdsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: getBirds.handler
Timeout: 15
Events:
GetBirds:
Type: Api
Properties:
Path: /Birds
Method: ANY
AWS SAM Globals
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Lambda permissions model
Fine grained security controls for both
execution and invocation:
Execution policies:
• Define what AWS resources/API calls can this
function access via IAM
• Used in streaming invocations
• E.g. “Lambda function A can read from
DynamoDB table users”
Function policies:
• Used for sync and async invocations
• E.g. “Actions on bucket X can invoke Lambda
function Z”
• Resource policies allow for cross account
configst access
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS SAM Policy Templates
MyQueueFunction:
Type: AWS::Serverless::Function
Properties:
...
Policies:
# Gives permissions to poll an SQS Queue
- SQSPollerPolicy:
queueName: !Ref MyQueue
...
MyQueue:
Type: AWS::SQS::Queue
...
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
SAM Policy Templates
45+ predefined
policies
All found here:
https://bit.ly/2xWycnj
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
Best
Practices
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS SAM Best Practices
• Use Parameters and Mappings when possible
to build dynamic templates based on user
inputs and pseudo parameters such as
AWS::Region
• Use the Globals section to simplify templates
• Use Export & ImportValue to share resource
information across stacks
• Build out multiple environments, such as for
Development, Test, Production and even DR
using the same template, even across
accounts
SAM Template
Source
Control
Dev
Test
Prod
© 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
AWS Cloud Development Kit (CDK)
https://awslabs.github.io/aws-cdk
AWS CDK Toolkit
+
AWS Construct Library
+
@aws-cdk/
aws-serverless
D
eveloper
Preview
S U M M I T © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Thank you!
S U M M I T © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Danilo Poccia
@danilop
S U M M I T © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.

More Related Content

What's hot

What's hot (20)

Get hands-on with AWS DeepRacer and compete in the AWS DeepRacer League - AIM...
Get hands-on with AWS DeepRacer and compete in the AWS DeepRacer League - AIM...Get hands-on with AWS DeepRacer and compete in the AWS DeepRacer League - AIM...
Get hands-on with AWS DeepRacer and compete in the AWS DeepRacer League - AIM...
 
Scalable serverless architectures using event-driven design - MAD301 - Atlant...
Scalable serverless architectures using event-driven design - MAD301 - Atlant...Scalable serverless architectures using event-driven design - MAD301 - Atlant...
Scalable serverless architectures using event-driven design - MAD301 - Atlant...
 
Introducing-AWS-Hong-Kong-Region
Introducing-AWS-Hong-Kong-RegionIntroducing-AWS-Hong-Kong-Region
Introducing-AWS-Hong-Kong-Region
 
Machine learning at the edge for industrial applications - SVC302 - New York ...
Machine learning at the edge for industrial applications - SVC302 - New York ...Machine learning at the edge for industrial applications - SVC302 - New York ...
Machine learning at the edge for industrial applications - SVC302 - New York ...
 
AWS Fargate deep dive - MAD303 - Chicago AWS Summit
AWS Fargate deep dive - MAD303 - Chicago AWS SummitAWS Fargate deep dive - MAD303 - Chicago AWS Summit
AWS Fargate deep dive - MAD303 - Chicago AWS Summit
 
AWS App Mesh: Manage services mesh discovery, recovery, and monitoring - MAD3...
AWS App Mesh: Manage services mesh discovery, recovery, and monitoring - MAD3...AWS App Mesh: Manage services mesh discovery, recovery, and monitoring - MAD3...
AWS App Mesh: Manage services mesh discovery, recovery, and monitoring - MAD3...
 
A tale of two customers - Simplified data protection with Veeam, N2WS & AWS -...
A tale of two customers - Simplified data protection with Veeam, N2WS & AWS -...A tale of two customers - Simplified data protection with Veeam, N2WS & AWS -...
A tale of two customers - Simplified data protection with Veeam, N2WS & AWS -...
 
Deep dive on storage offerings: What to use, where, and why - STG303 - New Yo...
Deep dive on storage offerings: What to use, where, and why - STG303 - New Yo...Deep dive on storage offerings: What to use, where, and why - STG303 - New Yo...
Deep dive on storage offerings: What to use, where, and why - STG303 - New Yo...
 
Build intelligent applications quickly with AWS AI services - AIM301 - New Yo...
Build intelligent applications quickly with AWS AI services - AIM301 - New Yo...Build intelligent applications quickly with AWS AI services - AIM301 - New Yo...
Build intelligent applications quickly with AWS AI services - AIM301 - New Yo...
 
AWS storage solutions for business-critical applications - STG301 - Chicago A...
AWS storage solutions for business-critical applications - STG301 - Chicago A...AWS storage solutions for business-critical applications - STG301 - Chicago A...
AWS storage solutions for business-critical applications - STG301 - Chicago A...
 
How Millennium Management achieves provable security with AWS Zelkova - FSV30...
How Millennium Management achieves provable security with AWS Zelkova - FSV30...How Millennium Management achieves provable security with AWS Zelkova - FSV30...
How Millennium Management achieves provable security with AWS Zelkova - FSV30...
 
Build scalable applications with a serverless relational database - ADB211 - ...
Build scalable applications with a serverless relational database - ADB211 - ...Build scalable applications with a serverless relational database - ADB211 - ...
Build scalable applications with a serverless relational database - ADB211 - ...
 
[NEW LAUNCH!] Introducti[NEW LAUNCH!] Introduction to event-driven architectu...
[NEW LAUNCH!] Introducti[NEW LAUNCH!] Introduction to event-driven architectu...[NEW LAUNCH!] Introducti[NEW LAUNCH!] Introduction to event-driven architectu...
[NEW LAUNCH!] Introducti[NEW LAUNCH!] Introduction to event-driven architectu...
 
Progetta, crea e gestisci Modern Application per web e mobile su AWS
Progetta, crea e gestisci Modern Application per web e mobile su AWSProgetta, crea e gestisci Modern Application per web e mobile su AWS
Progetta, crea e gestisci Modern Application per web e mobile su AWS
 
Software delivery best practices: Lessons from Amazon and our customers - MAD...
Software delivery best practices: Lessons from Amazon and our customers - MAD...Software delivery best practices: Lessons from Amazon and our customers - MAD...
Software delivery best practices: Lessons from Amazon and our customers - MAD...
 
Migliora la disponibilità e le prestazioni delle tue applicazioni con Amazon ...
Migliora la disponibilità e le prestazioni delle tue applicazioni con Amazon ...Migliora la disponibilità e le prestazioni delle tue applicazioni con Amazon ...
Migliora la disponibilità e le prestazioni delle tue applicazioni con Amazon ...
 
Architetture per l'analisi di flussi di dati in tempo reale
Architetture per l'analisi di flussi di dati in tempo realeArchitetture per l'analisi di flussi di dati in tempo reale
Architetture per l'analisi di flussi di dati in tempo reale
 
Searching for patterns: Log analytics using Amazon ES - ADB205 - New York AWS...
Searching for patterns: Log analytics using Amazon ES - ADB205 - New York AWS...Searching for patterns: Log analytics using Amazon ES - ADB205 - New York AWS...
Searching for patterns: Log analytics using Amazon ES - ADB205 - New York AWS...
 
AWSome Day Nairobi 2019
AWSome Day Nairobi 2019AWSome Day Nairobi 2019
AWSome Day Nairobi 2019
 
Storing data long term with Amazon S3 Glacier Deep Archive - STG302 - Chicago...
Storing data long term with Amazon S3 Glacier Deep Archive - STG302 - Chicago...Storing data long term with Amazon S3 Glacier Deep Archive - STG302 - Chicago...
Storing data long term with Amazon S3 Glacier Deep Archive - STG302 - Chicago...
 

Similar to Serverless Functions Deep Dive

Similar to Serverless Functions Deep Dive (20)

Serverless functions deep dive
Serverless functions deep diveServerless functions deep dive
Serverless functions deep dive
 
Devops on serverless
Devops on serverlessDevops on serverless
Devops on serverless
 
Twelve-Factor serverless applications - MAD311 - Chicago AWS Summit
Twelve-Factor serverless applications - MAD311 - Chicago AWS SummitTwelve-Factor serverless applications - MAD311 - Chicago AWS Summit
Twelve-Factor serverless applications - MAD311 - Chicago AWS Summit
 
Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019
Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019
Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019
 
Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019
Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019
Building a fully serverless application on AWS | AWS Summit Tel Aviv 2019
 
Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...
Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...
Best Practices for CI/CD with AWS Lambda and Amazon API Gateway (SRV355-R1) -...
 
Building CICD Pipelines for Serverless Applications
Building CICD Pipelines for Serverless ApplicationsBuilding CICD Pipelines for Serverless Applications
Building CICD Pipelines for Serverless Applications
 
Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...Productionize Serverless Application Building and Deployments with AWS SAM - ...
Productionize Serverless Application Building and Deployments with AWS SAM - ...
 
Lambda Layers & Runtime API
Lambda Layers & Runtime APILambda Layers & Runtime API
Lambda Layers & Runtime API
 
Twelve-factor serverless applications - MAD302 - Santa Clara AWS Summit
Twelve-factor serverless applications - MAD302 - Santa Clara AWS SummitTwelve-factor serverless applications - MAD302 - Santa Clara AWS Summit
Twelve-factor serverless applications - MAD302 - Santa Clara AWS Summit
 
Favorire l'innovazione passando da applicazioni monolitiche ad architetture m...
Favorire l'innovazione passando da applicazioni monolitiche ad architetture m...Favorire l'innovazione passando da applicazioni monolitiche ad architetture m...
Favorire l'innovazione passando da applicazioni monolitiche ad architetture m...
 
Twelve-Factor Serverless Applications
Twelve-Factor Serverless ApplicationsTwelve-Factor Serverless Applications
Twelve-Factor Serverless Applications
 
Serverless workshop with Amazon Web Services
Serverless workshop with Amazon Web ServicesServerless workshop with Amazon Web Services
Serverless workshop with Amazon Web Services
 
The family - presentation on AWS Serverless
The family - presentation on AWS ServerlessThe family - presentation on AWS Serverless
The family - presentation on AWS Serverless
 
Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...
Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...
Unlocking Agility with the AWS Serverless Application Model (SAM) - AWS Summi...
 
.NET on AWS
.NET on AWS.NET on AWS
.NET on AWS
 
Serverless Developer Experience I AWS Dev Day 2018
Serverless Developer Experience I AWS Dev Day 2018Serverless Developer Experience I AWS Dev Day 2018
Serverless Developer Experience I AWS Dev Day 2018
 
Twelve-Factor serverless applications - MAD307 - New York AWS Summit
Twelve-Factor serverless applications - MAD307 - New York AWS SummitTwelve-Factor serverless applications - MAD307 - New York AWS Summit
Twelve-Factor serverless applications - MAD307 - New York AWS Summit
 
Meet AWS SAM
Meet AWS SAMMeet AWS SAM
Meet AWS SAM
 
Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...
Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...
Build and Deploy Serverless Applications with AWS SAM - SRV316 - Chicago AWS ...
 

More from Amazon Web Services

Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
Amazon Web Services
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
Amazon Web Services
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
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...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
Amazon Web Services
 

More from Amazon Web Services (20)

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...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
 
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...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
 
Esegui pod serverless con Amazon EKS e AWS Fargate
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
 
Costruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSCostruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWS
 
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
Come spendere fino al 90% in meno con i container e le istanze spot
 
Open banking as a service
Open banking as a serviceOpen banking as a service
Open banking as a service
 
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...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
 
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...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
 
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
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
 
Computer Vision con AWS
Computer Vision con AWSComputer Vision con AWS
Computer Vision con AWS
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
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
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
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
 
API moderne real-time per applicazioni mobili e web
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
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
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
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
 
Fundraising Essentials
Fundraising EssentialsFundraising Essentials
Fundraising Essentials
 
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...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container Service
 

Serverless Functions Deep Dive

  • 1. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Serverless functions deep dive Danilo Poccia Principal Evangelist, Serverless AWS @danilop
  • 2. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS operational responsibility models On-Premises Cloud Less More Compute Virtual Machine EC2 Elastic Beanstalk AWS LambdaFargate Databases MySQL MySQL on EC2 RDS MySQL RDS Aurora Aurora Serverless DynamoDB Storage Storage S3 Messaging ESBs Amazon MQ Kinesis SQS / SNS Analytics Hadoop Hadoop on EC2 EMR Elasticsearch Service Athena
  • 3. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
  • 4. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
  • 5. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Serverless applications Services (anything) Changes in data state Requests to endpoints Changes in resource state Event source Function Node.js Python Java C# Go Ruby Runtime API
  • 6. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T 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, more) import json def lambda_handler(event, context): # TODO implement return { 'statusCode': 200, 'body': json.dumps('Hello World!') }
  • 7. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Lambda Layers Lets functions easily share code: Upload layer once, reference within any function Promote separation of responsibilities, lets developers iterate faster on writing business logic Built in support for secure sharing by ecosystem
  • 8. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Using Lambda Layers • Put common components in a ZIP file and upload it as a Lambda Layer • Layers are immutable and can be versioned to manage updates • When a version is deleted or permissions to use it are revoked, functions that used it previously will continue to work, but you won’t be able to create new ones • You can reference up to five layers, one of which can optionally be a custom runtime Lambda Layers arn:aws:lambda:region:accountId:layer:shared-lib Lambda Layers arn:aws:lambda:region:accountId:layer:shared-lib:2 Lambda Layers arn:aws:lambda:region:accountId:layer:shared-lib:3
  • 9. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Lambda Runtime API Bring any Linux compatible language runtime Powered by new Runtime API - Codifies the runtime calling conventions and integration points At launch, custom runtimes powering Ruby support in AWS Lambda, more runtimes from partners (like Erlang) Custom runtimes distributed as “layers” Rule Stack
  • 10. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Runtime Bootstrap • The bootstrap executable act as a bridge between the Runtime HTTP API and the Function to be executed • Bootstrap needs to manage response/error handling, context creation and function execution • Information on the interface endpoint and the function handler are shared as environment variables /runtime API /invocation/next /init/error /ID/error /invocation/ID/response /invocation/ID/error bootstrap Process events/headers Clean up Initialize and Invoke function Response/Error handling Lambda Function
  • 11. Build PCI and HIPAA compliant serverless applications! Serverless platform services that can be used in both:
  • 12. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Start with a framework AWS Chalice AWS Amplify AWS SAM AWS: Third-party: Serverless Framework
  • 14. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS Serverless Application Model (SAM) AWS CloudFormation extension optimized for serverless Special serverless resource types: Functions, APIs, SimpleTables, Layers, and Applications Supports anything AWS CloudFormation supports Open specification (Apache 2.0) https://aws.amazon.com/serverless/sam
  • 15. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T SAM template AWSTemplateFormatVersion: '2010-09-09’ Transform: AWS::Serverless-2016-10-31 Resources: GetFunction: Type: AWS::Serverless::Function Properties: Handler: index.get Runtime: nodejs8.10 CodeUri: src/ Policies: - DynamoDBReadPolicy: TableName: !Ref MyTable Events: GetResource: Type: Api Properties: Path: /resource/{resourceId} Method: get MyTable: Type: AWS::Serverless::SimpleTable Just 20 lines to create: • Lambda function • IAM role • API Gateway • DynamoDB table O pen Source
  • 16. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS SAM Command Line Interface (AWS SAM CLI) CLI tool for local development, debugging, testing, deploying, and monitoring of serverless applications Supports API Gateway “proxy-style” and Lambda service API testing Response object and function logs available on your local machine Uses open source docker-lambda images to mimic Lambda’s execution environment such as timeout, memory limits, runtimes Can tail production logs from CloudWatch logs Can help you build in native dependencies https://aws.amazon.com/serverless/sam
  • 17. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T SAM CLI sam init --name my-app --runtime python cd my-app/ sam local ... sam validate # The SAM template sam build sam package --s3-bucket my-packages-bucket --output-template-file packaged.yaml sam deploy --template-file packaged.yaml --stack-name my-app-prod sam publish # To the AWS Serverless Application Repository O pen Source
  • 18. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T
  • 19. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T With the AWS Serverless Application Repository: Developers can… • Discover and deploy ready-made apps and code samples • Combine applications in the app repository with their own via Nested Applications • Customize open-source apps to get started quickly • Share apps privately or publish apps for public use
  • 20. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T TweetSource: Type: AWS::Serverless::Application Properties: Location: ApplicationId: arn:aws:serverlessrepo:... SemanticVersion: 2.0.0 Parameters: TweetProcessorFunctionName: !Ref MyFunction SearchText: '#serverless -filter:nativeretweets' Nested apps to simplify solving recurring problems Standard Component Custom Business Logic Polling schedule (CloudWatch Events rule) trigger TwitterProcessor SearchCheckpoint TwitterSearchPoller Twitter Search API
  • 21. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS SAM Template Capabilities • Can mix in other non-SAM CloudFormation resources in the same template • i.e. Amazon S3, Amazon Kinesis, AWS Step Functions • Supports use of Parameters, Mappings, Outputs, etc • Supports Intrinsic Functions • Can use ImportValue (exceptions for RestApiId, Policies, StageName attributes) • YAML or JSON
  • 22. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS Lambda Environment Variables • Key-value pairs that you can dynamically pass to your function • Available via standard environment variable APIs such as process.env for Node.js or os.environ for Python • Can optionally be encrypted via AWS Key Management Service (KMS) • Allows you to specify in IAM what roles have access to the keys to decrypt the information • Useful for creating environments per stage (i.e. dev, testing, production)
  • 23. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Amazon API Gateway Stage Variables Stage variables act like environment variables • Use stage variables to store configuration values • Stage variables are available in the $context object • Values are accessible from most fields in API Gateway • Lambda function ARN • HTTP endpoint • Custom authorizer function name • Parameter mappings
  • 24. AWS Lambda and Amazon API Gateway Variables + SAM Parameters: MyEnvironment: Type: String Default: testing AllowedValues: - test - staging - prod Description: Environment of this stack of resources Mappings: SpecialFeature1: test: status: on staging: status: on prod: status: off #Lambda MyFunction: Type: 'AWS::Serverless::Function' Properties: … Environment: Variables: ENVIRONMENT: !Ref: MyEnvironment Spec_Feature1: !FindInMap [SpecialFeature1, !Ref MyEnvironment, status] … #API Gateway MyApiGatewayApi: Type: AWS::Serverless::Api Properties: … Variables: ENVIRONMENT: !Ref: MyEnvironment
  • 25. Parameters: MyEnvironment: Type: String Default: testing AllowedValues: - testing - staging - prod Description: Environment of this stack of resources Mappings: SpecialFeature1: testing: status: on staging: status: on prod: status: off #Lambda MyFunction: Type: 'AWS::Serverless::Function' Properties: … Environment: Variables: ENVIRONMENT: !Ref: MyEnvironment Spec_Feature1: !FindInMap [SpecialFeature1, !Ref MyEnvironment, status] … #API Gateway MyApiGatewayApi: Type: AWS::Serverless::Api Properties: … Variables: ENVIRONMENT: !Ref: MyEnvironment AWS Lambda and Amazon API Gateway Variables + SAM
  • 26. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T MyLambdaFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs6.10 AutoPublishAlias: !Ref ENVIRONMENT DeploymentPreference: Type: Linear10PercentEvery10Minutes Alarms: # A list of alarms that you want to monitor - !Ref AliasErrorMetricGreaterThanZeroAlarm - !Ref LatestVersionErrorMetricGreaterThanZeroAlarm Hooks: # Validation Lambda functions that are run before & after traffic shifting PreTraffic: !Ref PreTrafficLambdaFunction PostTraffic: !Ref PostTrafficLambdaFunction AWS SAM + Safe Deployments
  • 27. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS Lambda Alias Traffic Shifting & AWS SAM AutoPublishAlias By adding this property and specifying an alias name, AWS SAM will do the following: • Detect when new code is being deployed based on changes to the Lambda function's Amazon S3 URI. • Create and publish an updated version of that function with the latest code. • Create an alias with a name you provide (unless an alias already exists) and points to the updated version of the Lambda function. Deployment Preference Type Canary10Percent30Minutes Canary10Percent5Minutes Canary10Percent10Minutes Canary10Percent15Minutes Linear10PercentEvery10Minutes Linear10PercentEvery1Minute Linear10PercentEvery2Minutes Linear10PercentEvery3Minutes AllAtOnce In SAM:
  • 28. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Alarms: # A list of alarms that you want to monitor - !Ref AliasErrorMetricGreaterThanZeroAlarm - !Ref LatestVersionErrorMetricGreaterThanZeroAlarm Hooks: # Validation Lambda functions that are run before & after traffic shifting PreTraffic: !Ref PreTrafficLambdaFunction PostTraffic: !Ref PostTrafficLambdaFunction AWS Lambda Alias Traffic Shifting & AWS SAM Note: You can specify a maximum of 10 alarms In SAM:
  • 29. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Globals: Function: Runtime: nodejs6.10 CodeUri: s3://code-artifacts/pet_app1234.zip MemorySize: 1024 Timeout: 30 AutoPublishAlias: !Ref ENVIRONMENT getDogsFunction: Type: AWS::Serverless::Function Properties: Handler: getdogs.handler Events: GetDogs: Type: Api Properties: Path: /Dogs Method: ANY getCatsFunction: Type: AWS::Serverless::Function Properties: Handler: getCats.handler Events: GetCats: Type: Api Properties: Path: /Cats Method: ANY getBirdsFunction: Type: AWS::Serverless::Function Properties: Handler: getBirds.handler Timeout: 15 Events: GetBirds: Type: Api Properties: Path: /Birds Method: ANY AWS SAM Globals
  • 30. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Lambda permissions model Fine grained security controls for both execution and invocation: Execution policies: • Define what AWS resources/API calls can this function access via IAM • Used in streaming invocations • E.g. “Lambda function A can read from DynamoDB table users” Function policies: • Used for sync and async invocations • E.g. “Actions on bucket X can invoke Lambda function Z” • Resource policies allow for cross account configst access
  • 31. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS SAM Policy Templates MyQueueFunction: Type: AWS::Serverless::Function Properties: ... Policies: # Gives permissions to poll an SQS Queue - SQSPollerPolicy: queueName: !Ref MyQueue ... MyQueue: Type: AWS::SQS::Queue ...
  • 32. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T SAM Policy Templates 45+ predefined policies All found here: https://bit.ly/2xWycnj
  • 33. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T Best Practices
  • 34. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS SAM Best Practices • Use Parameters and Mappings when possible to build dynamic templates based on user inputs and pseudo parameters such as AWS::Region • Use the Globals section to simplify templates • Use Export & ImportValue to share resource information across stacks • Build out multiple environments, such as for Development, Test, Production and even DR using the same template, even across accounts SAM Template Source Control Dev Test Prod
  • 35. © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.S U M M I T AWS Cloud Development Kit (CDK) https://awslabs.github.io/aws-cdk AWS CDK Toolkit + AWS Construct Library + @aws-cdk/ aws-serverless D eveloper Preview
  • 36. S U M M I T © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.
  • 37. Thank you! S U M M I T © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved. Danilo Poccia @danilop
  • 38. S U M M I T © 2019, Amazon Web Services, Inc. or its affiliates. All rights reserved.