ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing...

44
Serverless Architectural Patterns and Best Practices Adrian Hornsby, Technical Evangelist @adhorn [email protected]

Transcript of ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing...

Page 1: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

Serverless Architectural Patterns and Best Practices

Adrian Hornsby, Technical Evangelist@adhorn

[email protected]

Page 2: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

2

Agenda

• Serverless characteristics and practices• 3-Tier Web application• Batch processing• Stream processing• Operations automation• Augmentation• IoT actions• Wrap-up/Q&A

Page 3: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

3

Spectrum of AWS offerings

AWSLambda

Amazon Kinesis

AmazonS3

Amazon API Gateway

AmazonSQS

AmazonDynamoDB

AWS IoT

Amazon EMR

Amazon ElastiCache

AmazonRDS

Amazon Redshift

Amazon Elasticsearch

Service

Managed Serverless

Amazon EC2

“On EC2”

Amazon Cognito

Amazon CloudWatch

Page 4: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

4

Serverless patterns built with functions

Functions are the unit of deployment and scaleScales per request—users cannot over or under-provisionNever pay for idleSkip the boring parts; skip the hard parts

Page 5: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

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

Page 6: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

6

Lambda considerations and best practicesCan 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_configimport pymysql

rds_host = "rds-instance" db_name = rds_config.db_nametry: conn = pymysql.connect( except: logger.error("ERROR:def handler(event, context):

with conn.cursor() as cur:Executes with each

invocation

Executes during cold start

Page 7: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

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(); ...

Page 8: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

8

Pattern 1: 3-Tier Web Application

Page 9: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

9

Web application

Data stored in Amazon

DynamoDB

Dynamic content in AWS Lambda

Amazon API Gateway

Browser

Amazon CloudFront

Amazon S3

Page 10: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

10

Amazon API Gateway AWS

LambdaAmazon

DynamoDB

AmazonS3

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

Page 11: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

11

Amazon API Gateway AWS

LambdaAmazon

DynamoDB

AmazonS3

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

Page 12: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

12

Amazon API Gateway

AWSLambda

AmazonDynamoDB

AmazonS3

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

AWSCloudTrail

BrowserCustom CloudWatch

Metrics & Alarms

Page 13: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

13

AWS SAM (Serverless Application Model)AWS

Lambda

Amazon API Gateway

AWS CloudFormation

AmazonS3

AmazonDynamoDB

Package & Deploy

Code/Packages/Swagger

Serverless Template

Serverless Template

w/ CodeUri

package deployCI/CD Tools

Serverless web app lifecycle management

Page 14: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

14

Roo

t /

/{proxy+} ANY Your Node.jsExpress app

Greedy variable, ANY method, proxy integration

Simple yet very powerful:

• Automatically scale to meet demand

• Only pay for the requests you receive

Page 15: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

15

Amazon API Gateway best practices

• Use mock integrations• Signed URL from API Gateway for large or binary file uploads to

S3• Asynchronous calls for Lambda > 30s

Page 16: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

16

Pattern 2: Batch Processing

Page 17: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

17

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

Page 18: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

18

Source data

Source data

Source data

Source data Data Staging Layer/data/source-raw

Data Staging Layer/data/source-validated

Input Validation and Conversion layer

Input Tracking layer

State Management Store

Event-Driven Batch controlled with AWS Lambda

Page 19: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

19

Serverless batch processing

AWS Lambda: Splitter

Amazon S3Object

Amazon DynamoDB: Mapper Results

AWS Lambda: Mappers

….

…. AWS Lambda: Reducer

Amazon S3Results

Page 20: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

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

Page 21: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

21

Pattern 3: Stream Processing

Page 22: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

22

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

Page 23: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

23

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

Page 24: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

24

Amazon Kinesis Analytics

Sensors

Amazon Kinesis:Stream

Amazon Kinesis Analytics: Window Aggregation

Amazon Kinesis StreamsProducer 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

Page 25: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

25

Web ClientsUsers

API Gateway

Kinesis StreamInputJSON payload

Kinesis StreamOutputCSV payload

AWS Lambda

Amazon SNS

Kinesis Analytics

Real-time Clickstream Processing with Amazon Kinesis

Page 26: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

26

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

Page 27: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

27

Monitoring

Amazon Kinesis Stream metric GetRecords.IteratorAgeMilliseconds maximum

Page 28: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

28

Pattern 4: Automation

Page 29: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

29

Automation characteristics

• Respond to alarms or events• Periodic jobs • Auditing and Notification• Extend AWS functionality

Page 30: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

30

Security and Conformity

• “Trust but verify” with high confidence via events.

• Deployments verified with every change.• Lambda guarantees that each instance is in

compliance with defined security rules. • Triggers shutdown of violations and

notifications. • Compliance and readiness rules can be validated

with every resource change.

Page 31: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

31

Auto tagging resources as they start

AWS Lambda: Update Tag

Amazon CloudWatch Events:Rule Triggered

Amazon EC2 InstanceState Changes

Amazon DynamoDB: EC2 Instance Properties

Tag: N/A

Amazon EC2 InstanceState Changes

Tag:Owner=userNamePrincipalID=aws:userid

• AMI• Instances• Snapshot• Volume

Page 32: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

32

Auto Start/Shutdown of Instances

AWS Lambda: Policy & Compliance Rules

Amazon CloudWatch Events:Rules Triggered

Amazon SNS: Alert Notifications

Page 33: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

33

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

Page 34: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

34

Cluster backup using AWS Lambda

AWS Lambda: Backup Rules

Amazon CloudWatch Events:Scheduled Trigger Amazon Redshift Cluster XYZ Snapshot

Page 35: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

35

Dynamic DNS for EC2 instances

AWS Lambda: Update Route53

Amazon CloudWatch Events:Rule Triggered

Amazon EC2 InstanceState Changes

Amazon DynamoDB: EC2 Instance Properties

Amazon Route53: Private Hosted Zone

Tag:CNAME = ‘xyz.example.com’

xyz.example.com A 10.2.0.134

Page 36: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

36

Pattern 5: Augmentation

Page 37: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

37

Augmentation characteristics

• Event-based triggers• Extend AWS functionality• Stitch between services

Page 38: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

38

Apply custom logic to content uploaded to S3

AWS Lambda: Custom Logic

Users upload Content

S3:Source Bucket

S3:Destination Bucket

Triggered on PUTs

• Watermarking/thumbnailing• Transcoding• Indexinganddeduplication• Aggregationandfiltering• Preprocessing• Contentvalidation• WAFupdates

Page 39: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

39

S3 Bucket DynamoDB

ObjectCreateEvent

Put IndexEntry

Source data

Source data

Source data

Source data

Amazon S3 Metadata Index

Page 40: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

40

DynamoDB DynamoDB StreamsPush changes

AWS Lambda

Amazon ElasticsearchService

Index Record

Search Query

Indexing DynamoDB content using ElasticSearch

Page 41: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

41

Pattern 6: IoT Actions

Page 42: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

42

IoT actions characteristics

• Respond to change in state• Alarm, triggers• Predictive maintenance

Page 43: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

43

AWS Lambda

Notifications: Amazon SNS

DynamoDB

AWS IoTSensors Control System

Anomaly Detection Using AWS Lambda

Page 44: ServerlessArchitectural Patterns and Best Practices · PDF fileServerlessstream processing architecture Sensors Amazon Kinesis: Stream Lambda: Stream Processor S3: ... Lambda Amazon

Thanks!@[email protected]

.