SlideShare une entreprise Scribd logo
1  sur  40
Télécharger pour lire hors ligne
© 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Daniel Geske <gesked@amazon.de>
24 August 2017
Serverless Architectural
Patterns and Best Practices
Agenda
Serverless characteristics and practices
3-tier web application
Batch processing
Stream processing
Operations automation
Wrap-up/Q&A
Spectrum of AWS offerings
AWS
Lambda
Amazon
Kinesis
Amazon
S3
Amazon API
Gateway
Amazon
SQS
Amazon
DynamoDB
AWS IoT
Amazon
EMR
Amazon
ElastiCache
Amazon
RDS
Amazon
Redshift
Amazon
Elasticsearch
Service
Managed Serverless
Amazon EC2
“On EC2”
Amazon
Cognito
Amazon
CloudWatch
Serverless patterns built with functions
Functions are the unit of deployment and scale
Scales per request—users cannot over or under-provision
Never pay for idle
Skip the boring parts; skip the hard parts
Lambda considerations and best practices
AWS Lambda is stateless—architect accordingly
• Assume no affinity with underlying compute
infrastructure
• Local filesystem access and child process may not
extend beyond the lifetime of the Lambda request
Lambda considerations and best practices
Can your Lambda functions
survive the cold?
• Instantiate AWS clients and
database clients outside the
scope of the handler to take
advantage of connection re-use.
• Schedule with CloudWatch
Events for warmth
• ENIs for VPC support are
attached during cold start
import sys
import logging
import rds_config
import pymysql
rds_host = "rds-instance"
db_name = rds_config.db_name
try:
conn = pymysql.connect(
except:
logger.error("ERROR:
def handler(event, context):
with conn.cursor() as cur:
Executes with
each invocation
Executes during
cold start
Lambda considerations and best practices
How about a file system?
• Don’t forget about /tmp (512 MB
scratch space)
exports.ffmpeg = function(event,context)
{
new ffmpeg('./thumb.MP4', function (err,
video)
{
if (!err) {
video.fnExtractFrameToJPG('/tmp’)
function (error, files) { … }
…
if (!error)
console.log(files);
context.done();
...
Lambda considerations and best practices
Custom CloudWatch metrics
• 40 KB per POST
• Default Acct Limit of 150 TPS
• Consider aggregating with Kinesis
def put_cstate ( iid, state ):
response = cwclient.put_metric_data(
Namespace='AWSx/DirectConnect',
MetricData=[
{
'MetricName':'ConnectionState',
'Dimensions': [
{
'Name': 'ConnectionId',
'Value': iid
},
],
'Value': state,
'Unit': 'None’
…
Pattern 1: 3-Tier Web Application
Web application
Data stored in
Amazon
DynamoDB
Dynamic content
in AWS Lambda
Amazon API
Gateway
Browser
Amazon
CloudFront
Amazon
S3
Amazon API
Gateway AWS
Lambda
Amazon
DynamoDB
Amazon
S3
Amazon
CloudFront
• Bucket Policies
• ACLs
• OAI
• Geo-Restriction
• Signed Cookies
• Signed URLs
• DDOS
IAM
AuthZ
IAM
Serverless web app security
• Throttling
• Caching
• Usage Plans
Browser
Amazon API
Gateway AWS
Lambda
Amazon
DynamoDB
Amazon
S3
Amazon
CloudFront
• Bucket Policies
• ACLs
• OAI
• Geo-Restriction
• Signed Cookies
• Signed URLs
• DDOS
IAMAuthZ IAM
Serverless web app security
• Throttling
• Caching
• Usage Plans
Browser
Amazon
CloudFront
• HTTPS
• Disable Host
Header Forwarding
AWS WAF
Amazon API
Gateway
AWS
Lambda
Amazon
DynamoDB
Amazon
S3
Amazon
CloudFront
• Access Logs in S3
Bucket• Access Logs in S3 Bucket
• CloudWatch Metrics-
https://aws.amazon.com/
cloudfront/reporting/
Serverless web app monitoring
AWS WAF
• WebACL Testing
• Total Requests
• Allowed/Blocked
Requests by ACL
logslogs
• Invocations
• Invocation Errors
• Duration
• Throttled
Invocations
• Latency
• Throughput
• Throttled Reqs
• Returned Bytes
• Documentation
• Latency
• Count
• Cache Hit/Miss
• 4XX/5XX Errors
Streams
AWS
CloudTrail
Browser
Custom CloudWatch
Metrics & Alarms
Serverless web app lifecycle management
AWS SAM (Serverless Application Model) - blog
AWS
Lambda
Amazon API
Gateway
AWS
CloudFormation
Amazon
S3
Amazon
DynamoDB
Package &
Deploy
Code/Packages/
Swagger
Serverless
Template
Serverless
Template
w/ CodeUri
package deploy
CI/CD Tools
Amazon API Gateway best practices
Use mock integrations
Signed URL from API Gateway for large or binary file
uploads to S3
Use request/response mapping templates for legacy
apps and HTTP response codes
Asynchronous calls for Lambda > 30s
Root/
/{proxy+} ANY Your Node.js
Express app
Greedy variable, ANY method, proxy integration
Simple yet very powerful:
• Automatically scale to meet demand
• Only pay for the requests you receive
Pattern 2: Batch Processing
Characteristics
Large data sets
Periodic or scheduled tasks
Extract Transform Load (ETL) jobs
Usually non-interactive and long running
Many problems fit MapReduce programming model
Serverless batch processing
AWS Lambda:
Splitter
Amazon S3
Object
Amazon DynamoDB:
Mapper Results
AWS Lambda:
Mappers
….
….
AWS Lambda:
Reducer
Amazon S3
Results
Considerations and best practices
Cascade mapper functions
Lambda languages vs. SQL
Speed is directly proportional to the concurrent Lambda
function limit
Use DynamoDB/ElastiCache/S3 for intermediate state of
mapper functions
Lambda MapReduce Reference Architecture
Cost of serverless batch processing
200 GB normalized Google Ngram data-set
Serverless:
• 1000 concurrent Lambda invocations
• Processing time: 9 minutes
• Cost: $7.06
Pattern 3: Stream Processing
Stream processing characteristics
• High ingest rate
• Near real-time processing (low latency from ingest to
process)
• Spiky traffic (lots of devices with intermittent network
connections)
• Message durability
• Message ordering
Serverless stream processing architecture
Sensors
Amazon Kinesis:
Stream
Lambda:
Stream Processor
S3:
Final Aggregated Output
Lambda:
Periodic Dump to S3
CloudWatch Events:
Trigger every 5 minutes
S3:
Intermediate Aggregated
Data
Lambda:
Scheduled Dispatcher
KPL:
Producer
Fan-out pattern
• Number of Amazon Kinesis Streams shards corresponds to concurrent
Lambda invocations
• Trade higher throughput & lower latency vs. strict message ordering
Sensors
Amazon Kinesis:
Stream
Lambda:
Dispatcher
KPL:
Producer Lambda:
Processors
Increase throughput, reduce processing latency
More about fan-out pattern
• Keep up with peak shard capacity
• 1000 records / second, OR
• 1 MB / second
• Consider parallel synchronous Lambda invocations
• Rcoil for JS (https://github.com/sapessi/rcoil) can help
• Dead letter queue to retry failed Lambda invocations
Best practices
• Tune batch size when Lambda is triggered by Amazon
Kinesis Streams – reduce number of Lambda
invocations
• Tune memory setting for your Lambda function – shorten
execution time
• Use KPL to batch messages and saturate Amazon
Kinesis Stream capacity
Monitoring
Amazon Kinesis Stream metric GetRecords.IteratorAgeMilliseconds maximum
Amazon Kinesis Analytics
Sensors
Amazon Kinesis:
Stream
Amazon Kinesis Analytics:
Window Aggregation
Amazon Kinesis Streams
Producer S3:
Aggregated Output
CREATE OR REPLACE PUMP "STREAM_PUMP" AS INSERT INTO
"DESTINATION_SQL_STREAM"
SELECT STREAM "device_id",
FLOOR("SOURCE_SQL_STREAM_001".ROWTIME TO MINUTE) as "round_ts",
SUM("measurement") as "sample_sum",
COUNT(*) AS "sample_count"
FROM "SOURCE_SQL_STREAM_001"
GROUP BY "device_id", FLOOR("SOURCE_SQL_STREAM_001".ROWTIME TO MINUTE);
Aggregation
Time Window
Cost comparison - assumptions
• Variable message rate over 6 hours
• Costs extrapolated over 30 days
20,000
10,000
20,000
50,000
20,000
10,000
1 2 3 4 5 6
MESSAGES/SEC
HOURS
Serverless
• Amazon Kinesis Stream with 5
shards
Cost comparison
Server-based on EC2
• Kafka cluster (3 x m3.large)
• Zookeeper cluster (3 x m3.large)
• Consumer (1 x c4.xlarge)
Service Monthly Cost
Amazon Kinesis Streams $ 58.04
AWS Lambda $259.85
Amazon S3 (Intermediate Files) $ 84.40
Amazon CloudWatch $ 4.72
Total $407.01
Service Monthly Cost
EC2 Kafka Cluster $292.08
EC2 Zookeeper Cluster $292.08
EC2 Consumer $152.99
Total On-Demand $737.15
1-year All Upfront RI $452.42
Compare related services
Amazon Kinesis Streams Amazon SQS Amazon SNS
Message Durability Up to retention period Up to retention period Retry delivery (depends on
destination type)
Maximum Retention Period 7 days 14 days Up to retry delivery limit
Message Ordering Strict within shard Standard - Best effort
FIFO – Strict within Message
Group
None
Delivery semantics Multiple consumers per
shard
Multiple readers per queue (but
one message is only handled
by one reader at a time)
Multiple subscribers per
topic
Scaling By throughput using Shards Automatic Automatic
Iterate over messages Shard iterators No No
Delivery Destination Types Kinesis Consumers SQS Readers HTTP/S, Mobile Push,
SMS, Email, SQS, Lambda
Lambda architecture
Data
Sources
Serving Layer
Speed Layer
AWS Lambda:
Splitter
Amazon S3
Object
Amazon DynamoDB:
Mapper Results
Amazon
S3
AWS Lambda:
Mappers
….
….
AWS Lambda:
Reducer
Amazon S3
Results
Batch Layer
Sensors
Amazon Kinesis:
Stream
Lambda:
Stream Processor
S3:
Final Aggregated Output
Lambda:
Periodic Dump to S3
CloudWatch Events:
Trigger every 5 minutes
S3:
Intermediate Aggregated
Data
Lambda:
Scheduled Dispatcher
KPL:
Producer
Pattern 4: Automation
Automation characteristics
• Respond to alarms or events
• Periodic jobs
• Auditing and Notification
• Extend AWS functionality
…All while being Highly Available and Scalable
Automation: dynamic DNS for EC2 instances
AWS Lambda:
Update Route53
Amazon CloudWatch Events:
Rule Triggered
Amazon EC2 Instance
State Changes
Amazon DynamoDB:
EC2 Instance Properties
Amazon Route53:
Private Hosted Zone
Tag:
CNAME = ‘xyz.example.com’
xyz.example.com A 10.2.0.134
Automation: image thumbnail creation from S3
AWS Lambda:
Resize Images
Users upload photos
S3:
Source Bucket
S3:
Destination Bucket
Triggered on
PUTs
CapitalOne Cloud Custodian
AWS Lambda:
Policy & Compliance Rules
Amazon CloudWatch Events:
Rules Triggered
AWS CloudTrail:
Events
Amazon SNS:
Alert Notifications
Amazon CloudWatch Logs:
Logs
Read more here: http://www.capitalone.io/cloud-custodian/docs/index.html
Best practices
• Document how to disable event triggers for your automation when
troubleshooting
• Gracefully handle API throttling by retrying with an exponential back-
off algorithm (AWS SDKs do this for you)
• Publish custom metrics from your Lambda function that are
meaningful for operations (e.g. number of EBS volumes
snapshotted)
Go build something.
Daniel Geske <gesked@amazon.de>

Contenu connexe

Tendances

Tendances (20)

Protecting your data in aws - Toronto
Protecting your data in aws - TorontoProtecting your data in aws - Toronto
Protecting your data in aws - Toronto
 
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
 
Securing Your AWS Infrastructure with Edge Services - May 2017 AWS Online Tec...
Securing Your AWS Infrastructure with Edge Services - May 2017 AWS Online Tec...Securing Your AWS Infrastructure with Edge Services - May 2017 AWS Online Tec...
Securing Your AWS Infrastructure with Edge Services - May 2017 AWS Online Tec...
 
Getting Started with AWS Security
Getting Started with AWS SecurityGetting Started with AWS Security
Getting Started with AWS Security
 
Getting Started with AWS Security
Getting Started with AWS SecurityGetting Started with AWS Security
Getting Started with AWS Security
 
AWS APAC Webinar Week - Real Time Data Processing with Kinesis
AWS APAC Webinar Week - Real Time Data Processing with KinesisAWS APAC Webinar Week - Real Time Data Processing with Kinesis
AWS APAC Webinar Week - Real Time Data Processing with Kinesis
 
Expanding your Data Center with Hybrid Cloud Infrastructure
Expanding your Data Center with Hybrid Cloud InfrastructureExpanding your Data Center with Hybrid Cloud Infrastructure
Expanding your Data Center with Hybrid Cloud Infrastructure
 
Seeing More Clearly: How Essilor Overcame 3 Common Cloud Security Challenges ...
Seeing More Clearly: How Essilor Overcame 3 Common Cloud Security Challenges ...Seeing More Clearly: How Essilor Overcame 3 Common Cloud Security Challenges ...
Seeing More Clearly: How Essilor Overcame 3 Common Cloud Security Challenges ...
 
SEC306 Using Microsoft Active Directory Across On-Premises and AWS Cloud Wind...
SEC306 Using Microsoft Active Directory Across On-Premises and AWS Cloud Wind...SEC306 Using Microsoft Active Directory Across On-Premises and AWS Cloud Wind...
SEC306 Using Microsoft Active Directory Across On-Premises and AWS Cloud Wind...
 
Protecting Your Data in AWS
Protecting Your Data in AWSProtecting Your Data in AWS
Protecting Your Data in AWS
 
Protecting Our Data on AWS
Protecting Our Data on AWSProtecting Our Data on AWS
Protecting Our Data on AWS
 
Automate Best Practices and Operational Health for your AWS Resources
Automate Best Practices and Operational Health for your AWS ResourcesAutomate Best Practices and Operational Health for your AWS Resources
Automate Best Practices and Operational Health for your AWS Resources
 
Datapipe: Hybrid Cloud in the Trenches – Lessons Learnt
Datapipe: Hybrid Cloud in the Trenches – Lessons LearntDatapipe: Hybrid Cloud in the Trenches – Lessons Learnt
Datapipe: Hybrid Cloud in the Trenches – Lessons Learnt
 
Protecting Your Data in AWS
Protecting Your Data in AWSProtecting Your Data in AWS
Protecting Your Data in AWS
 
Getting Started With AWS Security
Getting Started With AWS SecurityGetting Started With AWS Security
Getting Started With AWS Security
 
AWS Cloud Controls for Security - Usman Shakeel
AWS Cloud Controls for Security  - Usman ShakeelAWS Cloud Controls for Security  - Usman Shakeel
AWS Cloud Controls for Security - Usman Shakeel
 
SRV409 Deep Dive on Microservices and Docker
SRV409 Deep Dive on Microservices and DockerSRV409 Deep Dive on Microservices and Docker
SRV409 Deep Dive on Microservices and Docker
 
Secure Content Delivery Using Amazon CloudFront
Secure Content Delivery Using Amazon CloudFrontSecure Content Delivery Using Amazon CloudFront
Secure Content Delivery Using Amazon CloudFront
 
Customer Case Study: Achieving PCI Compliance in AWS
Customer Case Study: Achieving PCI Compliance in AWSCustomer Case Study: Achieving PCI Compliance in AWS
Customer Case Study: Achieving PCI Compliance in AWS
 
Identify and Access Management: The First Step in AWS Security
Identify and Access Management: The First Step in AWS SecurityIdentify and Access Management: The First Step in AWS Security
Identify and Access Management: The First Step in AWS Security
 

Similaire à Serverless Architectural Patterns and Best Practices | AWS

Real Time Data Processing Using AWS Lambda - DevDay Austin 2017
Real Time Data Processing Using AWS Lambda - DevDay Austin 2017Real Time Data Processing Using AWS Lambda - DevDay Austin 2017
Real Time Data Processing Using AWS Lambda - DevDay Austin 2017
Amazon Web Services
 

Similaire à Serverless Architectural Patterns and Best Practices | AWS (20)

Serverless Architectural Patterns and Best Practices
Serverless Architectural Patterns and Best PracticesServerless Architectural Patterns and Best Practices
Serverless Architectural Patterns and Best Practices
 
AWS re:Invent 2016: Serverless Architectural Patterns and Best Practices (ARC...
AWS re:Invent 2016: Serverless Architectural Patterns and Best Practices (ARC...AWS re:Invent 2016: Serverless Architectural Patterns and Best Practices (ARC...
AWS re:Invent 2016: Serverless Architectural Patterns and Best Practices (ARC...
 
AWS re:Invent 2016: [JK REPEAT] Serverless Architectural Patterns and Best Pr...
AWS re:Invent 2016: [JK REPEAT] Serverless Architectural Patterns and Best Pr...AWS re:Invent 2016: [JK REPEAT] Serverless Architectural Patterns and Best Pr...
AWS re:Invent 2016: [JK REPEAT] Serverless Architectural Patterns and Best Pr...
 
Serverless Architecture Patterns
Serverless Architecture PatternsServerless Architecture Patterns
Serverless Architecture Patterns
 
Serverless Architecture Patterns
Serverless Architecture PatternsServerless Architecture Patterns
Serverless Architecture Patterns
 
serverless_architecture_patterns_london_loft.pdf
serverless_architecture_patterns_london_loft.pdfserverless_architecture_patterns_london_loft.pdf
serverless_architecture_patterns_london_loft.pdf
 
Optimizing the Data Tier for Serverless Web Applications - March 2017 Online ...
Optimizing the Data Tier for Serverless Web Applications - March 2017 Online ...Optimizing the Data Tier for Serverless Web Applications - March 2017 Online ...
Optimizing the Data Tier for Serverless Web Applications - March 2017 Online ...
 
JustGiving – Serverless Data Pipelines, API, Messaging and Stream Processing
JustGiving – Serverless Data Pipelines,  API, Messaging and Stream ProcessingJustGiving – Serverless Data Pipelines,  API, Messaging and Stream Processing
JustGiving – Serverless Data Pipelines, API, Messaging and Stream Processing
 
JustGiving | Serverless Data Pipelines, API, Messaging and Stream Processing
JustGiving | Serverless Data Pipelines, API, Messaging and Stream ProcessingJustGiving | Serverless Data Pipelines, API, Messaging and Stream Processing
JustGiving | Serverless Data Pipelines, API, Messaging and Stream Processing
 
Getting Started with AWS Lambda and the Serverless Cloud
Getting Started with AWS Lambda and the Serverless CloudGetting Started with AWS Lambda and the Serverless Cloud
Getting Started with AWS Lambda and the Serverless Cloud
 
Deep Dive on AWS Lambda - January 2017 AWS Online Tech Talks
Deep Dive on AWS Lambda - January 2017 AWS Online Tech TalksDeep Dive on AWS Lambda - January 2017 AWS Online Tech Talks
Deep Dive on AWS Lambda - January 2017 AWS Online Tech Talks
 
Big data and serverless - AWS UG The Netherlands
Big data and serverless - AWS UG The NetherlandsBig data and serverless - AWS UG The Netherlands
Big data and serverless - AWS UG The Netherlands
 
AWS May Webinar Series - Streaming Data Processing with Amazon Kinesis and AW...
AWS May Webinar Series - Streaming Data Processing with Amazon Kinesis and AW...AWS May Webinar Series - Streaming Data Processing with Amazon Kinesis and AW...
AWS May Webinar Series - Streaming Data Processing with Amazon Kinesis and AW...
 
Real Time Data Processing Using AWS Lambda - DevDay Austin 2017
Real Time Data Processing Using AWS Lambda - DevDay Austin 2017Real Time Data Processing Using AWS Lambda - DevDay Austin 2017
Real Time Data Processing Using AWS Lambda - DevDay Austin 2017
 
Big Data adoption success using AWS Big Data Services - Pop-up Loft TLV 2017
Big Data adoption success using AWS Big Data Services - Pop-up Loft TLV 2017Big Data adoption success using AWS Big Data Services - Pop-up Loft TLV 2017
Big Data adoption success using AWS Big Data Services - Pop-up Loft TLV 2017
 
Messaging in the AWS Cloud
Messaging in the AWS CloudMessaging in the AWS Cloud
Messaging in the AWS Cloud
 
AWS re:Invent 2016: Building Complex Serverless Applications (GPST404)
AWS re:Invent 2016: Building Complex Serverless Applications (GPST404)AWS re:Invent 2016: Building Complex Serverless Applications (GPST404)
AWS re:Invent 2016: Building Complex Serverless Applications (GPST404)
 
Real Time Data Processing Using AWS Lambda - DevDay Los Angeles 2017
Real Time Data Processing Using AWS Lambda - DevDay Los Angeles 2017Real Time Data Processing Using AWS Lambda - DevDay Los Angeles 2017
Real Time Data Processing Using AWS Lambda - DevDay Los Angeles 2017
 
Real-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS LambdaReal-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS Lambda
 
Real-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS LambdaReal-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS Lambda
 

Plus de AWS Germany

Plus de AWS Germany (20)

Analytics Web Day | From Theory to Practice: Big Data Stories from the Field
Analytics Web Day | From Theory to Practice: Big Data Stories from the FieldAnalytics Web Day | From Theory to Practice: Big Data Stories from the Field
Analytics Web Day | From Theory to Practice: Big Data Stories from the Field
 
Analytics Web Day | Query your Data in S3 with SQL and optimize for Cost and ...
Analytics Web Day | Query your Data in S3 with SQL and optimize for Cost and ...Analytics Web Day | Query your Data in S3 with SQL and optimize for Cost and ...
Analytics Web Day | Query your Data in S3 with SQL and optimize for Cost and ...
 
Modern Applications Web Day | Impress Your Friends with Your First Serverless...
Modern Applications Web Day | Impress Your Friends with Your First Serverless...Modern Applications Web Day | Impress Your Friends with Your First Serverless...
Modern Applications Web Day | Impress Your Friends with Your First Serverless...
 
Modern Applications Web Day | Manage Your Infrastructure and Configuration on...
Modern Applications Web Day | Manage Your Infrastructure and Configuration on...Modern Applications Web Day | Manage Your Infrastructure and Configuration on...
Modern Applications Web Day | Manage Your Infrastructure and Configuration on...
 
Modern Applications Web Day | Container Workloads on AWS
Modern Applications Web Day | Container Workloads on AWSModern Applications Web Day | Container Workloads on AWS
Modern Applications Web Day | Container Workloads on AWS
 
Modern Applications Web Day | Continuous Delivery to Amazon EKS with Spinnaker
Modern Applications Web Day | Continuous Delivery to Amazon EKS with SpinnakerModern Applications Web Day | Continuous Delivery to Amazon EKS with Spinnaker
Modern Applications Web Day | Continuous Delivery to Amazon EKS with Spinnaker
 
Building Smart Home skills for Alexa
Building Smart Home skills for AlexaBuilding Smart Home skills for Alexa
Building Smart Home skills for Alexa
 
Hotel or Taxi? "Sorting hat" for travel expenses with AWS ML infrastructure
Hotel or Taxi? "Sorting hat" for travel expenses with AWS ML infrastructureHotel or Taxi? "Sorting hat" for travel expenses with AWS ML infrastructure
Hotel or Taxi? "Sorting hat" for travel expenses with AWS ML infrastructure
 
Wild Rydes with Big Data/Kinesis focus: AWS Serverless Workshop
Wild Rydes with Big Data/Kinesis focus: AWS Serverless WorkshopWild Rydes with Big Data/Kinesis focus: AWS Serverless Workshop
Wild Rydes with Big Data/Kinesis focus: AWS Serverless Workshop
 
Log Analytics with AWS
Log Analytics with AWSLog Analytics with AWS
Log Analytics with AWS
 
Deep Dive into Concepts and Tools for Analyzing Streaming Data on AWS
Deep Dive into Concepts and Tools for Analyzing Streaming Data on AWS Deep Dive into Concepts and Tools for Analyzing Streaming Data on AWS
Deep Dive into Concepts and Tools for Analyzing Streaming Data on AWS
 
AWS Programme für Nonprofits
AWS Programme für NonprofitsAWS Programme für Nonprofits
AWS Programme für Nonprofits
 
Microservices and Data Design
Microservices and Data DesignMicroservices and Data Design
Microservices and Data Design
 
Serverless vs. Developers – the real crash
Serverless vs. Developers – the real crashServerless vs. Developers – the real crash
Serverless vs. Developers – the real crash
 
Query your data in S3 with SQL and optimize for cost and performance
Query your data in S3 with SQL and optimize for cost and performanceQuery your data in S3 with SQL and optimize for cost and performance
Query your data in S3 with SQL and optimize for cost and performance
 
Secret Management with Hashicorp’s Vault
Secret Management with Hashicorp’s VaultSecret Management with Hashicorp’s Vault
Secret Management with Hashicorp’s Vault
 
EKS Workshop
 EKS Workshop EKS Workshop
EKS Workshop
 
Scale to Infinity with ECS
Scale to Infinity with ECSScale to Infinity with ECS
Scale to Infinity with ECS
 
Containers on AWS - State of the Union
Containers on AWS - State of the UnionContainers on AWS - State of the Union
Containers on AWS - State of the Union
 
Deploying and Scaling Your First Cloud Application with Amazon Lightsail
Deploying and Scaling Your First Cloud Application with Amazon LightsailDeploying and Scaling Your First Cloud Application with Amazon Lightsail
Deploying and Scaling Your First Cloud Application with Amazon Lightsail
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Serverless Architectural Patterns and Best Practices | AWS

  • 1. © 2016, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Daniel Geske <gesked@amazon.de> 24 August 2017 Serverless Architectural Patterns and Best Practices
  • 2. Agenda Serverless characteristics and practices 3-tier web application Batch processing Stream processing Operations automation Wrap-up/Q&A
  • 3. Spectrum of AWS offerings AWS Lambda Amazon Kinesis Amazon S3 Amazon API Gateway Amazon SQS Amazon DynamoDB AWS IoT Amazon EMR Amazon ElastiCache Amazon RDS Amazon Redshift Amazon Elasticsearch Service Managed Serverless Amazon EC2 “On EC2” Amazon Cognito Amazon CloudWatch
  • 4. Serverless patterns built with functions Functions are the unit of deployment and scale Scales per request—users cannot over or under-provision Never pay for idle Skip the boring parts; skip the hard parts
  • 5. Lambda considerations and best practices AWS Lambda is stateless—architect accordingly • Assume no affinity with underlying compute infrastructure • Local filesystem access and child process may not extend beyond the lifetime of the Lambda request
  • 6. Lambda considerations and best practices Can your Lambda functions survive the cold? • Instantiate AWS clients and database clients outside the scope of the handler to take advantage of connection re-use. • Schedule with CloudWatch Events for warmth • ENIs for VPC support are attached during cold start import sys import logging import rds_config import pymysql rds_host = "rds-instance" db_name = rds_config.db_name try: conn = pymysql.connect( except: logger.error("ERROR: def handler(event, context): with conn.cursor() as cur: Executes with each invocation Executes during cold start
  • 7. Lambda considerations and best practices How about a file system? • Don’t forget about /tmp (512 MB scratch space) exports.ffmpeg = function(event,context) { new ffmpeg('./thumb.MP4', function (err, video) { if (!err) { video.fnExtractFrameToJPG('/tmp’) function (error, files) { … } … if (!error) console.log(files); context.done(); ...
  • 8. Lambda considerations and best practices Custom CloudWatch metrics • 40 KB per POST • Default Acct Limit of 150 TPS • Consider aggregating with Kinesis def put_cstate ( iid, state ): response = cwclient.put_metric_data( Namespace='AWSx/DirectConnect', MetricData=[ { 'MetricName':'ConnectionState', 'Dimensions': [ { 'Name': 'ConnectionId', 'Value': iid }, ], 'Value': state, 'Unit': 'None’ …
  • 9. Pattern 1: 3-Tier Web Application
  • 10. Web application Data stored in Amazon DynamoDB Dynamic content in AWS Lambda Amazon API Gateway Browser Amazon CloudFront Amazon S3
  • 11. Amazon API Gateway AWS Lambda Amazon DynamoDB Amazon S3 Amazon CloudFront • Bucket Policies • ACLs • OAI • Geo-Restriction • Signed Cookies • Signed URLs • DDOS IAM AuthZ IAM Serverless web app security • Throttling • Caching • Usage Plans Browser
  • 12. Amazon API Gateway AWS Lambda Amazon DynamoDB Amazon S3 Amazon CloudFront • Bucket Policies • ACLs • OAI • Geo-Restriction • Signed Cookies • Signed URLs • DDOS IAMAuthZ IAM Serverless web app security • Throttling • Caching • Usage Plans Browser Amazon CloudFront • HTTPS • Disable Host Header Forwarding AWS WAF
  • 13. Amazon API Gateway AWS Lambda Amazon DynamoDB Amazon S3 Amazon CloudFront • Access Logs in S3 Bucket• Access Logs in S3 Bucket • CloudWatch Metrics- https://aws.amazon.com/ cloudfront/reporting/ Serverless web app monitoring AWS WAF • WebACL Testing • Total Requests • Allowed/Blocked Requests by ACL logslogs • Invocations • Invocation Errors • Duration • Throttled Invocations • Latency • Throughput • Throttled Reqs • Returned Bytes • Documentation • Latency • Count • Cache Hit/Miss • 4XX/5XX Errors Streams AWS CloudTrail Browser Custom CloudWatch Metrics & Alarms
  • 14. Serverless web app lifecycle management AWS SAM (Serverless Application Model) - blog AWS Lambda Amazon API Gateway AWS CloudFormation Amazon S3 Amazon DynamoDB Package & Deploy Code/Packages/ Swagger Serverless Template Serverless Template w/ CodeUri package deploy CI/CD Tools
  • 15. Amazon API Gateway best practices Use mock integrations Signed URL from API Gateway for large or binary file uploads to S3 Use request/response mapping templates for legacy apps and HTTP response codes Asynchronous calls for Lambda > 30s
  • 16. Root/ /{proxy+} ANY Your Node.js Express app Greedy variable, ANY method, proxy integration Simple yet very powerful: • Automatically scale to meet demand • Only pay for the requests you receive
  • 17. Pattern 2: Batch Processing
  • 18. Characteristics Large data sets Periodic or scheduled tasks Extract Transform Load (ETL) jobs Usually non-interactive and long running Many problems fit MapReduce programming model
  • 19. Serverless batch processing AWS Lambda: Splitter Amazon S3 Object Amazon DynamoDB: Mapper Results AWS Lambda: Mappers …. …. AWS Lambda: Reducer Amazon S3 Results
  • 20. Considerations and best practices Cascade mapper functions Lambda languages vs. SQL Speed is directly proportional to the concurrent Lambda function limit Use DynamoDB/ElastiCache/S3 for intermediate state of mapper functions Lambda MapReduce Reference Architecture
  • 21. Cost of serverless batch processing 200 GB normalized Google Ngram data-set Serverless: • 1000 concurrent Lambda invocations • Processing time: 9 minutes • Cost: $7.06
  • 22. Pattern 3: Stream Processing
  • 23. Stream processing characteristics • High ingest rate • Near real-time processing (low latency from ingest to process) • Spiky traffic (lots of devices with intermittent network connections) • Message durability • Message ordering
  • 24. Serverless stream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: Final Aggregated Output Lambda: Periodic Dump to S3 CloudWatch Events: Trigger every 5 minutes S3: Intermediate Aggregated Data Lambda: Scheduled Dispatcher KPL: Producer
  • 25. Fan-out pattern • Number of Amazon Kinesis Streams shards corresponds to concurrent Lambda invocations • Trade higher throughput & lower latency vs. strict message ordering Sensors Amazon Kinesis: Stream Lambda: Dispatcher KPL: Producer Lambda: Processors Increase throughput, reduce processing latency
  • 26. More about fan-out pattern • Keep up with peak shard capacity • 1000 records / second, OR • 1 MB / second • Consider parallel synchronous Lambda invocations • Rcoil for JS (https://github.com/sapessi/rcoil) can help • Dead letter queue to retry failed Lambda invocations
  • 27. Best practices • Tune batch size when Lambda is triggered by Amazon Kinesis Streams – reduce number of Lambda invocations • Tune memory setting for your Lambda function – shorten execution time • Use KPL to batch messages and saturate Amazon Kinesis Stream capacity
  • 28. Monitoring Amazon Kinesis Stream metric GetRecords.IteratorAgeMilliseconds maximum
  • 29. Amazon Kinesis Analytics Sensors Amazon Kinesis: Stream Amazon Kinesis Analytics: Window Aggregation Amazon Kinesis Streams Producer S3: Aggregated Output CREATE OR REPLACE PUMP "STREAM_PUMP" AS INSERT INTO "DESTINATION_SQL_STREAM" SELECT STREAM "device_id", FLOOR("SOURCE_SQL_STREAM_001".ROWTIME TO MINUTE) as "round_ts", SUM("measurement") as "sample_sum", COUNT(*) AS "sample_count" FROM "SOURCE_SQL_STREAM_001" GROUP BY "device_id", FLOOR("SOURCE_SQL_STREAM_001".ROWTIME TO MINUTE); Aggregation Time Window
  • 30. Cost comparison - assumptions • Variable message rate over 6 hours • Costs extrapolated over 30 days 20,000 10,000 20,000 50,000 20,000 10,000 1 2 3 4 5 6 MESSAGES/SEC HOURS
  • 31. Serverless • Amazon Kinesis Stream with 5 shards Cost comparison Server-based on EC2 • Kafka cluster (3 x m3.large) • Zookeeper cluster (3 x m3.large) • Consumer (1 x c4.xlarge) Service Monthly Cost Amazon Kinesis Streams $ 58.04 AWS Lambda $259.85 Amazon S3 (Intermediate Files) $ 84.40 Amazon CloudWatch $ 4.72 Total $407.01 Service Monthly Cost EC2 Kafka Cluster $292.08 EC2 Zookeeper Cluster $292.08 EC2 Consumer $152.99 Total On-Demand $737.15 1-year All Upfront RI $452.42
  • 32. Compare related services Amazon Kinesis Streams Amazon SQS Amazon SNS Message Durability Up to retention period Up to retention period Retry delivery (depends on destination type) Maximum Retention Period 7 days 14 days Up to retry delivery limit Message Ordering Strict within shard Standard - Best effort FIFO – Strict within Message Group None Delivery semantics Multiple consumers per shard Multiple readers per queue (but one message is only handled by one reader at a time) Multiple subscribers per topic Scaling By throughput using Shards Automatic Automatic Iterate over messages Shard iterators No No Delivery Destination Types Kinesis Consumers SQS Readers HTTP/S, Mobile Push, SMS, Email, SQS, Lambda
  • 33. Lambda architecture Data Sources Serving Layer Speed Layer AWS Lambda: Splitter Amazon S3 Object Amazon DynamoDB: Mapper Results Amazon S3 AWS Lambda: Mappers …. …. AWS Lambda: Reducer Amazon S3 Results Batch Layer Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: Final Aggregated Output Lambda: Periodic Dump to S3 CloudWatch Events: Trigger every 5 minutes S3: Intermediate Aggregated Data Lambda: Scheduled Dispatcher KPL: Producer
  • 35. Automation characteristics • Respond to alarms or events • Periodic jobs • Auditing and Notification • Extend AWS functionality …All while being Highly Available and Scalable
  • 36. Automation: dynamic DNS for EC2 instances AWS Lambda: Update Route53 Amazon CloudWatch Events: Rule Triggered Amazon EC2 Instance State Changes Amazon DynamoDB: EC2 Instance Properties Amazon Route53: Private Hosted Zone Tag: CNAME = ‘xyz.example.com’ xyz.example.com A 10.2.0.134
  • 37. Automation: image thumbnail creation from S3 AWS Lambda: Resize Images Users upload photos S3: Source Bucket S3: Destination Bucket Triggered on PUTs
  • 38. CapitalOne Cloud Custodian AWS Lambda: Policy & Compliance Rules Amazon CloudWatch Events: Rules Triggered AWS CloudTrail: Events Amazon SNS: Alert Notifications Amazon CloudWatch Logs: Logs Read more here: http://www.capitalone.io/cloud-custodian/docs/index.html
  • 39. Best practices • Document how to disable event triggers for your automation when troubleshooting • Gracefully handle API throttling by retrying with an exponential back- off algorithm (AWS SDKs do this for you) • Publish custom metrics from your Lambda function that are meaningful for operations (e.g. number of EBS volumes snapshotted)
  • 40. Go build something. Daniel Geske <gesked@amazon.de>