SlideShare a Scribd company logo
1 of 39
Download to read offline
AWS Lambda: Best Practices
and Common Mistakes
Given by Derek C. Ashmore
DevOps West
June 5, 2019
©2018 Derek C. Ashmore, All Rights Reserved 1
Who am I?
• Professional Geek
since 1987
• Java/J2EE/Java EE
since 1999
• AWS since 2010
• Specialties
• Cloud
Workshops
• Cloud-native
Applications
• Yes – I still code!
©2018 Derek C. Ashmore, All Rights Reserved 2
Discussion Resources
• This slide deck
– https://www.slideshare.net/derekashmore/presentations
• Sample code on my Github
– https://github.com/Derek-Ashmore/
• Slide deck has hyper-links!
– Don’t bother writing down URLs
©2018 Derek C. Ashmore, All Rights Reserved 3
Agenda
The
“What”
and “Why”
of AWS
Lambda
Code-Level
Tips
Operation
and Design
Habits
When to
use
Lambdas
Summary /
Q&A
©2016 Derek C. Ashmore, All Rights Reserved 4
What are AWS Lambdas?
• You provide custom code -> AWS runs it
– Java, Go, PowerShell, Node.js, C#, Python, and Ruby
• Computing power with less management
– AWS manages that hardware
– AWS autoscales that hardware
– AWS maintains that hardware
• Lambdas are event driven
– API Gateway (e.g. RESTful Web Service call)
– Many more
• Lambdas are stateless
• Not to be confused with “Lambda Expressions” in Java 8
©2016 Derek C. Ashmore, All Rights Reserved 5
Lambda Event Sources
• API Gateway
• SNS Messaging
Subscriptions
• Schedule
• Storage writes
– S3, DynamoDB, Kenesis
©2016 Derek C. Ashmore, All Rights Reserved 6
• SES Email receipt
• Cloudwatch
– Schedule, Events, log entries
• Cognito (Security)
• CloudFormation
– Creation script
What’s the Business Benefit
• Less Maintenance Hassle
• Unlimited* Parallelism
• Current cost advantage
– Don’t pay for idle
– CPU cost currently lower
• Free tier
– 1 M executions and 400K compute seconds per month
– Memory allocated determines allowed free-tier runtime
• 20 cents per 1 M executions + memory/runtime cost
– Administration cost
• No O/S upgrades, server backups, etc.
©2016 Derek C. Ashmore, All Rights Reserved 7
There’s no free lunch
• Less control over environment
– Harder to tune
– Memory and time limits on execution
• Few Environment amenities
– No connection pooling, session support, caching
• Proprietary Interface
– Potential Technical Lock-in
• No Guarantee that AWS cost will be constant
– Potential Business Risk
• Modern version of CGI
©2016 Derek C. Ashmore, All Rights Reserved 8
Agenda
The
“What”
and “Why”
of AWS
Lambda
Code-Level
Tips
Operation
and Design
Habits
When to
use
Lambdas
Summary /
Q&A
©2016 Derek C. Ashmore, All Rights Reserved 9
What Makes a “Best Practice”?
• Makes Support Easier
• Increases Reuse
• Increases Performance
• Minimizes Resource Consumption
– Labor
– Runtime
©2018 Derek C. Ashmore, All Rights Reserved 10
Let’s start with Low-Hanging Fruit
©2018 Derek C. Ashmore, All Rights Reserved 11
Report Inputs/Env on Exception
• Place a Try / Catch in your handler
– Python Example
– Java Example
• Also check your arguments with a clear error message
©2018 Derek C. Ashmore, All Rights Reserved 12
def crossAccountHandler(event, context):
try:
………………
except Exception as e:
e.args += (event,vars(context))
raise
Check Arguments Up Front
• Check your arguments with a clear error message
– Python Example
– Java Example
©2018 Derek C. Ashmore, All Rights Reserved 13
def crossAccountHandler(event, context):
try:
if 'Assumed_Role' in event:
…………………
else:
raise Exception('Assumed_Role not provided as argument')
except Exception as e:
Specify Lambda Source Repo
• Explicitly put the source repository name in the Lambda comments
– In most organizations, the repository name isn’t obvious
– Others changing your code need it
– You don’t want source control to be out of date
©2018 Derek C. Ashmore, All Rights Reserved 14
"""
secretLambda.py
……………
Source Control: https://github.com/Derek-Ashmore/AWSDevOpsUtilities
"""
Separate Lambda from Business Logic
• Make business logic reusable
– Callable by other applications
– Usable on premises
• Easier to locally develop and debug
– Lambda-specific logic is thin!
©2018 Derek C. Ashmore, All Rights Reserved 15
def startStopHandler(event, context):
try:
executeStopStart(datetime.datetime.now()
, os.getenv('Scheduled_StartTime', ‘’)
, os.getenv('Scheduled_StopTime', ‘’)
, os.getenv('Scheduled_StartStop_Days', 'M,T,W,R,F’))
……………
return 0;
This is low-hanging fruit that will be appreciated by
your fellow developers!
©2018 Derek C. Ashmore, All Rights Reserved 16
• Log All Inputs and Environment on
Exception
• Check all arguments up front
• Document the source repo at the top.
• Repo readme can have other
developer specifics
• Separate Lambda code from business
logic
• Now let’s talk design and operations….
Agenda
The
“What”
and “Why”
of AWS
Lambda
Code-Level
Tips
Operation
and Design
Habits
When to
use
Lambdas
Summary /
Q&A
©2016 Derek C. Ashmore, All Rights Reserved 17
Automate builds and deployments!
©2018 Derek C. Ashmore, All Rights Reserved 18
Lambda Copies Everywhere!
• Changes / Bug Fixes need to be deployed everywhere
• Solving with automation solves the wrong problem!
©2018 Derek C. Ashmore, All Rights Reserved 19
One Copy for All!
• Scalable – only need to add accounts over time
• Bugfixes in one place
• Configuration usually in common DynamoDB table(s)
• Sample in Python here
©2018 Derek C. Ashmore, All Rights Reserved 20
Cross-Account Execution
• Algorithm is
– Assume a remote-account role using STS
• The response has temporary credentials
– Create a session using the remote account creds
– Do work in the remote account
• Example here: Derek-Ashmore/AWSDevOpsUtilities (Github)
©2018 Derek C. Ashmore, All Rights Reserved 21
For workloads over 5 min
• Executor that invokes lambda asynchronously for
each account
• Sample in Python here
©2018 Derek C. Ashmore, All Rights Reserved 22
Limit Custom Nesting to One Level
• Debugging with nested executions is
– Time consuming and difficult
– Can’t do locally
– Absolutely requires unique correlation id for the entire transaction
• Allows you to tell invocation history for one logical transaction
– Instead of deep custom nesting, use AWS Step Functions
• Use Step Functions if you need more
©2018 Derek C. Ashmore, All Rights Reserved 23
Nested Calls using AWS Step Functions
• AWS Step Functions
– Uses a State Machine model
• Think turn-style to get access to train
– States are “Locked” and “Unlocked”
– Locked → Payment input allowed, then “Unlocked”
– Unlocked → One person allowed through, then “Locked”
– Automatically provides correlation between invocations
• Unified logs for the entire transaction
©2018 Derek C. Ashmore, All Rights Reserved 24
Operations and Design Habits
©2018 Derek C. Ashmore, All Rights Reserved 25
• Automate Builds and Deployments
• Only install Lambda’s Once
• Limit Lambda nesting to One Level
• Step functions if you need more
• Now let’s talk dependencies and secrets
Use Configuration Injection
• No environment specifics hardcoded in the Lambda deployment
• Use Environment Variables on the Lambda Definition
– No un-encrypted secrets (e.g. database password)
• Use Arguments in the triggering event
– No un-encrypted secrets
• Anti-Example
– Splunk forwarding Lambda with hard-coded Splunk channels
©2018 Derek C. Ashmore, All Rights Reserved 26
Providing Secrets to Lambdas
• Secrets are needed items like credentials of any type.
• Use IAM Roles to grant permission to read secrets
• Options are:
– Use KMS
• Encrypt credential and base64 encode it
– Place encrypted version in environment variable
• Sample Lambda and Encryption Script (here)
– Use a Digital Vault (e.g. AWS Secrets Manager)
• Sample Lambda here
©2018 Derek C. Ashmore, All Rights Reserved 27
AWS Secrets Manager
• Use IAM Roles to grant
permission to read secrets
• You don’t need a “secret” to
get a “secret”!
©2018 Derek C. Ashmore, All Rights Reserved 28
Avoid Heavy-Footprint Dependencies
• Minimizes load time
– Mitigates cold-start problem
• Java
– Use Guice over Spring
• Python
– Use AWS provided deps first (list is
here)
©2018 Derek C. Ashmore, All Rights Reserved 29
Don’t Hog Resources
• 512 Mb temp space per invocation
• 1,024 file descriptors
• 1,024 Threads and processes
(combined)
• 6 MB payload size (synchronous)
• 128 KB payload size (asynchronous)
• 1000 concurrent lambda executions
per account per region
©2018 Derek C. Ashmore, All Rights Reserved 30
Idempotence
• Possible for your Lambda to be invoked multiple times for the same event
– Prevent repeat actions from having a different effect.
• Options
– Record the event id –> Skip repeated events
• Most event sources provide a unique request id
– Lambda invoking lambda does not!
• Negatively affects performance
– 1 extra read
– 1 extra write
• Need to roll-off old events
– Insure that the effect is the same each time
• Not perfect → You don’t control invocation order
©2018 Derek C. Ashmore, All Rights Reserved 31
Agenda
The
“What”
and “Why”
of AWS
Lambda
Code-Level
Tips
Operation
and Design
Habits
When to
use
Lambdas
Summary /
Q&A
©2016 Derek C. Ashmore, All Rights Reserved 32
Suitable workloads for Lambda’s
• Workloads that
– Take less than 15 min
– Are stateless
– Idempotent
• Evaluate cost with calculator: https://dashbird.io/lambda-cost-calculator/
• Typical examples
– Streaming data processors
– Dynamo DB Change Processors
– AWS-specific DevOps Tasks
• Security Enforcement
• Uptime Scheduling
• AWS Change Event processing
– CloudFormation Macros
©2018 Derek C. Ashmore, All Rights Reserved 33
Lambda can herd the cats!
• Using Lambda to enforce security
– Automatic Remediation
• Unlike AWS Config, Lambdas can take action!
• Unwanted port exposures
– Unauthorized exposure of 0.0.0.0/0 to the world
• Decentralized Management
– Empowers the organization
– Improves speed to market
• Less bottleneck by admin groups
– Still keeps the enterprise secure
©2018 Derek C. Ashmore, All Rights Reserved 34
Lambdas and Microservices
©2016 Derek C. Ashmore, All Rights Reserved 35
Using Lambdas as Microservices
• Lambda / API Gateway is a deployment option for microservices
– No differences in design principles
• Single purpose
• Self-contained
– Still design for failure
• Don’t “assume” that Lambda outages can’t happen
– A Lambda might need external resources that aren’t available
• Off Limits: Coding patterns that use state
– Lambdas must be stateless
– Fail fast patterns
• Service Call Mediator
• Circuit Breaker
– Performance Patterns
• Expiring Cache (API Gateway allows request caching)
©2016 Derek C. Ashmore, All Rights Reserved 36
Lambda Alternatives
• Use Kubernetes
– Operates as a Lambda type service in Kubernetes
– Functions get shut down when not used – like Lambda behind the
scenes
– Serverless workloads are Containerized
• Run on premises or on any Cloud
– Examples
• Fission
• Knative
• Kubeless
©2018 Derek C. Ashmore, All Rights Reserved 37
Further Reading
• This slide deck
– https://www.slideshare.net/derekashmore/presentations
• AWS Lambda Reading List
– http://www.derekashmore.com/2016/04/aws-lambda-reading-list.html
• Amazon’s Published Best Practice List
– https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html
©2018 Derek C. Ashmore, All Rights Reserved 38
Questions?
• Derek Ashmore:
– Blog: www.derekashmore.com
– LinkedIn: www.linkedin.com/in/derekashmore
• Connect Invites from attendees welcome
– Twitter: https://twitter.com/Derek_Ashmore
– GitHub: https://github.com/Derek-Ashmore
– Book: http://dvtpress.com/
©2018 Derek C. Ashmore, All Rights Reserved 39

More Related Content

What's hot

Building Serverless Web Applications - DevDay Austin 2017
Building Serverless Web Applications - DevDay Austin 2017Building Serverless Web Applications - DevDay Austin 2017
Building Serverless Web Applications - DevDay Austin 2017
Amazon Web Services
 
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Amazon Web Services
 

What's hot (20)

Design Patterns for Developers - Technical 201
Design Patterns for Developers - Technical 201Design Patterns for Developers - Technical 201
Design Patterns for Developers - Technical 201
 
Serverless Architecture Patterns
Serverless Architecture PatternsServerless Architecture Patterns
Serverless Architecture Patterns
 
Edge Services as a Critical AWS Infrastructure Component - August 2017 AWS On...
Edge Services as a Critical AWS Infrastructure Component - August 2017 AWS On...Edge Services as a Critical AWS Infrastructure Component - August 2017 AWS On...
Edge Services as a Critical AWS Infrastructure Component - August 2017 AWS On...
 
AWS Lambda support for AWS X-Ray
AWS Lambda support for AWS X-RayAWS Lambda support for AWS X-Ray
AWS Lambda support for AWS X-Ray
 
Building Serverless Web Applications - DevDay Austin 2017
Building Serverless Web Applications - DevDay Austin 2017Building Serverless Web Applications - DevDay Austin 2017
Building Serverless Web Applications - DevDay Austin 2017
 
2016 Utah Cloud Summit: Big Data Architectural Patterns and Best Practices on...
2016 Utah Cloud Summit: Big Data Architectural Patterns and Best Practices on...2016 Utah Cloud Summit: Big Data Architectural Patterns and Best Practices on...
2016 Utah Cloud Summit: Big Data Architectural Patterns and Best Practices on...
 
Building Cost-Aware Cloud Architectures - Jinesh Varia (AWS) and Adrian Cockc...
Building Cost-Aware Cloud Architectures - Jinesh Varia (AWS) and Adrian Cockc...Building Cost-Aware Cloud Architectures - Jinesh Varia (AWS) and Adrian Cockc...
Building Cost-Aware Cloud Architectures - Jinesh Varia (AWS) and Adrian Cockc...
 
SEC304 Advanced Techniques for DDoS Mitigation and Web Application Defense
SEC304 Advanced Techniques for DDoS Mitigation and Web Application DefenseSEC304 Advanced Techniques for DDoS Mitigation and Web Application Defense
SEC304 Advanced Techniques for DDoS Mitigation and Web Application Defense
 
Secure Content Delivery Using Amazon CloudFront and AWS WAF
Secure Content Delivery Using Amazon CloudFront and AWS WAFSecure Content Delivery Using Amazon CloudFront and AWS WAF
Secure Content Delivery Using Amazon CloudFront and AWS WAF
 
AWS Certified Cloud Practitioner Course S7-S10
AWS Certified Cloud Practitioner Course S7-S10AWS Certified Cloud Practitioner Course S7-S10
AWS Certified Cloud Practitioner Course S7-S10
 
Running your Windows Enterprise Workloads on AWS - Technical 201
Running your Windows Enterprise Workloads on AWS - Technical 201Running your Windows Enterprise Workloads on AWS - Technical 201
Running your Windows Enterprise Workloads on AWS - Technical 201
 
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
Getting Started with Serverless Architectures with Microservices_AWSPSSummit_...
 
AWS APAC Webinar Week - Maintaining Performance & Availability While Lowering...
AWS APAC Webinar Week - Maintaining Performance & Availability While Lowering...AWS APAC Webinar Week - Maintaining Performance & Availability While Lowering...
AWS APAC Webinar Week - Maintaining Performance & Availability While Lowering...
 
Getting Started with AWS Lambda and the Serverless Cloud - AWS Summit Cape T...
 Getting Started with AWS Lambda and the Serverless Cloud - AWS Summit Cape T... Getting Started with AWS Lambda and the Serverless Cloud - AWS Summit Cape T...
Getting Started with AWS Lambda and the Serverless Cloud - AWS Summit Cape T...
 
Running Containerised Applications at Scale on AWS
Running Containerised Applications at Scale on AWSRunning Containerised Applications at Scale on AWS
Running Containerised Applications at Scale on AWS
 
把您的 Amazon Lex Chatbot 與訊息服務集成
把您的 Amazon Lex Chatbot 與訊息服務集成把您的 Amazon Lex Chatbot 與訊息服務集成
把您的 Amazon Lex Chatbot 與訊息服務集成
 
Picking the right AWS backend for your Java application (May 2017)
Picking the right AWS backend for your Java application (May 2017)Picking the right AWS backend for your Java application (May 2017)
Picking the right AWS backend for your Java application (May 2017)
 
SMC305 Building CI/CD Pipelines for Serverless Applications
SMC305 Building CI/CD Pipelines for Serverless ApplicationsSMC305 Building CI/CD Pipelines for Serverless Applications
SMC305 Building CI/CD Pipelines for Serverless Applications
 
State of serverless
State of serverlessState of serverless
State of serverless
 
Introduction to Serverless Computing and AWS Lambda - AWS IL Meetup
Introduction to Serverless Computing and AWS Lambda - AWS IL MeetupIntroduction to Serverless Computing and AWS Lambda - AWS IL Meetup
Introduction to Serverless Computing and AWS Lambda - AWS IL Meetup
 

Similar to AWS Lambda: Best Practices and Common Mistakes - Dev Ops West 2019

Similar to AWS Lambda: Best Practices and Common Mistakes - Dev Ops West 2019 (20)

AWS Community Day - Derek C. Ashmore - AWS Lambda: Best Practices
AWS Community Day  - Derek C. Ashmore - AWS Lambda: Best Practices AWS Community Day  - Derek C. Ashmore - AWS Lambda: Best Practices
AWS Community Day - Derek C. Ashmore - AWS Lambda: Best Practices
 
AWS Lambda: Best Practices and Common Mistakes - Chicago Cloud Conference 2020
AWS Lambda: Best Practices and Common Mistakes - Chicago Cloud Conference 2020AWS Lambda: Best Practices and Common Mistakes - Chicago Cloud Conference 2020
AWS Lambda: Best Practices and Common Mistakes - Chicago Cloud Conference 2020
 
AWS Lambda for Architects - Chicago Coder Conference -2016-06-07
AWS Lambda for Architects - Chicago Coder Conference -2016-06-07AWS Lambda for Architects - Chicago Coder Conference -2016-06-07
AWS Lambda for Architects - Chicago Coder Conference -2016-06-07
 
AWS Lambda Deployments: Best Practices and Common Mistakes O'Reilly Software...
AWS Lambda Deployments:  Best Practices and Common Mistakes O'Reilly Software...AWS Lambda Deployments:  Best Practices and Common Mistakes O'Reilly Software...
AWS Lambda Deployments: Best Practices and Common Mistakes O'Reilly Software...
 
Aws Lambda for Java Architects - Illinois VJug -2016-05-03
Aws Lambda for Java Architects - Illinois VJug -2016-05-03Aws Lambda for Java Architects - Illinois VJug -2016-05-03
Aws Lambda for Java Architects - Illinois VJug -2016-05-03
 
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
Aws Lambda for Java Architects - Illinois JUG-Northwest -2016-08-02
 
Aws Lambda for Java Architects - JavaOne -2016-09-19
Aws Lambda for Java Architects - JavaOne -2016-09-19Aws Lambda for Java Architects - JavaOne -2016-09-19
Aws Lambda for Java Architects - JavaOne -2016-09-19
 
Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30Aws Lambda for Java Architects CJug-Chicago 2016-08-30
Aws Lambda for Java Architects CJug-Chicago 2016-08-30
 
Microservices with Terraform, Docker and the Cloud. DevOps Wet 2018
Microservices with Terraform, Docker and the Cloud. DevOps Wet 2018Microservices with Terraform, Docker and the Cloud. DevOps Wet 2018
Microservices with Terraform, Docker and the Cloud. DevOps Wet 2018
 
Get the EDGE to scale: Using Cloudfront along with edge compute to scale your...
Get the EDGE to scale: Using Cloudfront along with edge compute to scale your...Get the EDGE to scale: Using Cloudfront along with edge compute to scale your...
Get the EDGE to scale: Using Cloudfront along with edge compute to scale your...
 
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...
Gluecon 2018 - The Best Practices and Hard Lessons Learned of Serverless Appl...
 
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...
Become a Serverless Black Belt - Optimizing Your Serverless Applications - AW...
 
Event Detection Pipelines with Apache Kafka
Event Detection Pipelines with Apache KafkaEvent Detection Pipelines with Apache Kafka
Event Detection Pipelines with Apache Kafka
 
AWS re:Invent 2016: Accenture Cloud Platform Serverless Journey (ARC202)
AWS re:Invent 2016: Accenture Cloud Platform Serverless Journey (ARC202)AWS re:Invent 2016: Accenture Cloud Platform Serverless Journey (ARC202)
AWS re:Invent 2016: Accenture Cloud Platform Serverless Journey (ARC202)
 
Meetup callback
Meetup callbackMeetup callback
Meetup callback
 
Infrastructure Is Code with the AWS Cloud Development Kit (DEV372) - AWS re:I...
Infrastructure Is Code with the AWS Cloud Development Kit (DEV372) - AWS re:I...Infrastructure Is Code with the AWS Cloud Development Kit (DEV372) - AWS re:I...
Infrastructure Is Code with the AWS Cloud Development Kit (DEV372) - AWS re:I...
 
AWS Serverless patterns & best-practices in AWS
AWS Serverless  patterns & best-practices in AWSAWS Serverless  patterns & best-practices in AWS
AWS Serverless patterns & best-practices in AWS
 
Using Containers and Serverless to Deploy Microservices (ARC214) - AWS re:Inv...
Using Containers and Serverless to Deploy Microservices (ARC214) - AWS re:Inv...Using Containers and Serverless to Deploy Microservices (ARC214) - AWS re:Inv...
Using Containers and Serverless to Deploy Microservices (ARC214) - AWS re:Inv...
 
Stephen Liedig: Building Serverless Backends with AWS Lambda and API Gateway
Stephen Liedig: Building Serverless Backends with AWS Lambda and API GatewayStephen Liedig: Building Serverless Backends with AWS Lambda and API Gateway
Stephen Liedig: Building Serverless Backends with AWS Lambda and API Gateway
 
Building serverless backends - Tech talk 5 May 2017
Building serverless backends - Tech talk 5 May 2017Building serverless backends - Tech talk 5 May 2017
Building serverless backends - Tech talk 5 May 2017
 

Recently uploaded

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Recently uploaded (20)

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

AWS Lambda: Best Practices and Common Mistakes - Dev Ops West 2019

  • 1. AWS Lambda: Best Practices and Common Mistakes Given by Derek C. Ashmore DevOps West June 5, 2019 ©2018 Derek C. Ashmore, All Rights Reserved 1
  • 2. Who am I? • Professional Geek since 1987 • Java/J2EE/Java EE since 1999 • AWS since 2010 • Specialties • Cloud Workshops • Cloud-native Applications • Yes – I still code! ©2018 Derek C. Ashmore, All Rights Reserved 2
  • 3. Discussion Resources • This slide deck – https://www.slideshare.net/derekashmore/presentations • Sample code on my Github – https://github.com/Derek-Ashmore/ • Slide deck has hyper-links! – Don’t bother writing down URLs ©2018 Derek C. Ashmore, All Rights Reserved 3
  • 4. Agenda The “What” and “Why” of AWS Lambda Code-Level Tips Operation and Design Habits When to use Lambdas Summary / Q&A ©2016 Derek C. Ashmore, All Rights Reserved 4
  • 5. What are AWS Lambdas? • You provide custom code -> AWS runs it – Java, Go, PowerShell, Node.js, C#, Python, and Ruby • Computing power with less management – AWS manages that hardware – AWS autoscales that hardware – AWS maintains that hardware • Lambdas are event driven – API Gateway (e.g. RESTful Web Service call) – Many more • Lambdas are stateless • Not to be confused with “Lambda Expressions” in Java 8 ©2016 Derek C. Ashmore, All Rights Reserved 5
  • 6. Lambda Event Sources • API Gateway • SNS Messaging Subscriptions • Schedule • Storage writes – S3, DynamoDB, Kenesis ©2016 Derek C. Ashmore, All Rights Reserved 6 • SES Email receipt • Cloudwatch – Schedule, Events, log entries • Cognito (Security) • CloudFormation – Creation script
  • 7. What’s the Business Benefit • Less Maintenance Hassle • Unlimited* Parallelism • Current cost advantage – Don’t pay for idle – CPU cost currently lower • Free tier – 1 M executions and 400K compute seconds per month – Memory allocated determines allowed free-tier runtime • 20 cents per 1 M executions + memory/runtime cost – Administration cost • No O/S upgrades, server backups, etc. ©2016 Derek C. Ashmore, All Rights Reserved 7
  • 8. There’s no free lunch • Less control over environment – Harder to tune – Memory and time limits on execution • Few Environment amenities – No connection pooling, session support, caching • Proprietary Interface – Potential Technical Lock-in • No Guarantee that AWS cost will be constant – Potential Business Risk • Modern version of CGI ©2016 Derek C. Ashmore, All Rights Reserved 8
  • 9. Agenda The “What” and “Why” of AWS Lambda Code-Level Tips Operation and Design Habits When to use Lambdas Summary / Q&A ©2016 Derek C. Ashmore, All Rights Reserved 9
  • 10. What Makes a “Best Practice”? • Makes Support Easier • Increases Reuse • Increases Performance • Minimizes Resource Consumption – Labor – Runtime ©2018 Derek C. Ashmore, All Rights Reserved 10
  • 11. Let’s start with Low-Hanging Fruit ©2018 Derek C. Ashmore, All Rights Reserved 11
  • 12. Report Inputs/Env on Exception • Place a Try / Catch in your handler – Python Example – Java Example • Also check your arguments with a clear error message ©2018 Derek C. Ashmore, All Rights Reserved 12 def crossAccountHandler(event, context): try: ……………… except Exception as e: e.args += (event,vars(context)) raise
  • 13. Check Arguments Up Front • Check your arguments with a clear error message – Python Example – Java Example ©2018 Derek C. Ashmore, All Rights Reserved 13 def crossAccountHandler(event, context): try: if 'Assumed_Role' in event: ………………… else: raise Exception('Assumed_Role not provided as argument') except Exception as e:
  • 14. Specify Lambda Source Repo • Explicitly put the source repository name in the Lambda comments – In most organizations, the repository name isn’t obvious – Others changing your code need it – You don’t want source control to be out of date ©2018 Derek C. Ashmore, All Rights Reserved 14 """ secretLambda.py …………… Source Control: https://github.com/Derek-Ashmore/AWSDevOpsUtilities """
  • 15. Separate Lambda from Business Logic • Make business logic reusable – Callable by other applications – Usable on premises • Easier to locally develop and debug – Lambda-specific logic is thin! ©2018 Derek C. Ashmore, All Rights Reserved 15 def startStopHandler(event, context): try: executeStopStart(datetime.datetime.now() , os.getenv('Scheduled_StartTime', ‘’) , os.getenv('Scheduled_StopTime', ‘’) , os.getenv('Scheduled_StartStop_Days', 'M,T,W,R,F’)) …………… return 0;
  • 16. This is low-hanging fruit that will be appreciated by your fellow developers! ©2018 Derek C. Ashmore, All Rights Reserved 16 • Log All Inputs and Environment on Exception • Check all arguments up front • Document the source repo at the top. • Repo readme can have other developer specifics • Separate Lambda code from business logic • Now let’s talk design and operations….
  • 17. Agenda The “What” and “Why” of AWS Lambda Code-Level Tips Operation and Design Habits When to use Lambdas Summary / Q&A ©2016 Derek C. Ashmore, All Rights Reserved 17
  • 18. Automate builds and deployments! ©2018 Derek C. Ashmore, All Rights Reserved 18
  • 19. Lambda Copies Everywhere! • Changes / Bug Fixes need to be deployed everywhere • Solving with automation solves the wrong problem! ©2018 Derek C. Ashmore, All Rights Reserved 19
  • 20. One Copy for All! • Scalable – only need to add accounts over time • Bugfixes in one place • Configuration usually in common DynamoDB table(s) • Sample in Python here ©2018 Derek C. Ashmore, All Rights Reserved 20
  • 21. Cross-Account Execution • Algorithm is – Assume a remote-account role using STS • The response has temporary credentials – Create a session using the remote account creds – Do work in the remote account • Example here: Derek-Ashmore/AWSDevOpsUtilities (Github) ©2018 Derek C. Ashmore, All Rights Reserved 21
  • 22. For workloads over 5 min • Executor that invokes lambda asynchronously for each account • Sample in Python here ©2018 Derek C. Ashmore, All Rights Reserved 22
  • 23. Limit Custom Nesting to One Level • Debugging with nested executions is – Time consuming and difficult – Can’t do locally – Absolutely requires unique correlation id for the entire transaction • Allows you to tell invocation history for one logical transaction – Instead of deep custom nesting, use AWS Step Functions • Use Step Functions if you need more ©2018 Derek C. Ashmore, All Rights Reserved 23
  • 24. Nested Calls using AWS Step Functions • AWS Step Functions – Uses a State Machine model • Think turn-style to get access to train – States are “Locked” and “Unlocked” – Locked → Payment input allowed, then “Unlocked” – Unlocked → One person allowed through, then “Locked” – Automatically provides correlation between invocations • Unified logs for the entire transaction ©2018 Derek C. Ashmore, All Rights Reserved 24
  • 25. Operations and Design Habits ©2018 Derek C. Ashmore, All Rights Reserved 25 • Automate Builds and Deployments • Only install Lambda’s Once • Limit Lambda nesting to One Level • Step functions if you need more • Now let’s talk dependencies and secrets
  • 26. Use Configuration Injection • No environment specifics hardcoded in the Lambda deployment • Use Environment Variables on the Lambda Definition – No un-encrypted secrets (e.g. database password) • Use Arguments in the triggering event – No un-encrypted secrets • Anti-Example – Splunk forwarding Lambda with hard-coded Splunk channels ©2018 Derek C. Ashmore, All Rights Reserved 26
  • 27. Providing Secrets to Lambdas • Secrets are needed items like credentials of any type. • Use IAM Roles to grant permission to read secrets • Options are: – Use KMS • Encrypt credential and base64 encode it – Place encrypted version in environment variable • Sample Lambda and Encryption Script (here) – Use a Digital Vault (e.g. AWS Secrets Manager) • Sample Lambda here ©2018 Derek C. Ashmore, All Rights Reserved 27
  • 28. AWS Secrets Manager • Use IAM Roles to grant permission to read secrets • You don’t need a “secret” to get a “secret”! ©2018 Derek C. Ashmore, All Rights Reserved 28
  • 29. Avoid Heavy-Footprint Dependencies • Minimizes load time – Mitigates cold-start problem • Java – Use Guice over Spring • Python – Use AWS provided deps first (list is here) ©2018 Derek C. Ashmore, All Rights Reserved 29
  • 30. Don’t Hog Resources • 512 Mb temp space per invocation • 1,024 file descriptors • 1,024 Threads and processes (combined) • 6 MB payload size (synchronous) • 128 KB payload size (asynchronous) • 1000 concurrent lambda executions per account per region ©2018 Derek C. Ashmore, All Rights Reserved 30
  • 31. Idempotence • Possible for your Lambda to be invoked multiple times for the same event – Prevent repeat actions from having a different effect. • Options – Record the event id –> Skip repeated events • Most event sources provide a unique request id – Lambda invoking lambda does not! • Negatively affects performance – 1 extra read – 1 extra write • Need to roll-off old events – Insure that the effect is the same each time • Not perfect → You don’t control invocation order ©2018 Derek C. Ashmore, All Rights Reserved 31
  • 32. Agenda The “What” and “Why” of AWS Lambda Code-Level Tips Operation and Design Habits When to use Lambdas Summary / Q&A ©2016 Derek C. Ashmore, All Rights Reserved 32
  • 33. Suitable workloads for Lambda’s • Workloads that – Take less than 15 min – Are stateless – Idempotent • Evaluate cost with calculator: https://dashbird.io/lambda-cost-calculator/ • Typical examples – Streaming data processors – Dynamo DB Change Processors – AWS-specific DevOps Tasks • Security Enforcement • Uptime Scheduling • AWS Change Event processing – CloudFormation Macros ©2018 Derek C. Ashmore, All Rights Reserved 33
  • 34. Lambda can herd the cats! • Using Lambda to enforce security – Automatic Remediation • Unlike AWS Config, Lambdas can take action! • Unwanted port exposures – Unauthorized exposure of 0.0.0.0/0 to the world • Decentralized Management – Empowers the organization – Improves speed to market • Less bottleneck by admin groups – Still keeps the enterprise secure ©2018 Derek C. Ashmore, All Rights Reserved 34
  • 35. Lambdas and Microservices ©2016 Derek C. Ashmore, All Rights Reserved 35
  • 36. Using Lambdas as Microservices • Lambda / API Gateway is a deployment option for microservices – No differences in design principles • Single purpose • Self-contained – Still design for failure • Don’t “assume” that Lambda outages can’t happen – A Lambda might need external resources that aren’t available • Off Limits: Coding patterns that use state – Lambdas must be stateless – Fail fast patterns • Service Call Mediator • Circuit Breaker – Performance Patterns • Expiring Cache (API Gateway allows request caching) ©2016 Derek C. Ashmore, All Rights Reserved 36
  • 37. Lambda Alternatives • Use Kubernetes – Operates as a Lambda type service in Kubernetes – Functions get shut down when not used – like Lambda behind the scenes – Serverless workloads are Containerized • Run on premises or on any Cloud – Examples • Fission • Knative • Kubeless ©2018 Derek C. Ashmore, All Rights Reserved 37
  • 38. Further Reading • This slide deck – https://www.slideshare.net/derekashmore/presentations • AWS Lambda Reading List – http://www.derekashmore.com/2016/04/aws-lambda-reading-list.html • Amazon’s Published Best Practice List – https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html ©2018 Derek C. Ashmore, All Rights Reserved 38
  • 39. Questions? • Derek Ashmore: – Blog: www.derekashmore.com – LinkedIn: www.linkedin.com/in/derekashmore • Connect Invites from attendees welcome – Twitter: https://twitter.com/Derek_Ashmore – GitHub: https://github.com/Derek-Ashmore – Book: http://dvtpress.com/ ©2018 Derek C. Ashmore, All Rights Reserved 39