Module 7: Developing Event-Driven Serverless Solutions
AWS Academy Cloud Developing
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Section 1: Introduction
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Module objectives
At the end of this module, you should be able to:
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
3
Module overview
Sections
Demonstration
Lab
�
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
4
Knowledge check
Café business requirement
Sofía finished using the mock endpoints to test the API, and now she wants to launch the dynamic version of the café website. She needs to update the API integration to connect to the backend database.
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
5
Serverless as part of developing a cloud application
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
6
Section 2: Introducing serverless computing
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Serverless computing
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
8
Focus on business logic
Level of abstraction
On premises
Virtual servers in the cloud
Containers
Serverless
Building modern serverless applications
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
9
Serverless compute and event-driven patterns
Serverless,�purpose-built data stores
Managed services for integration
Deployment frameworks
Small pieces, �loosely joined
Purpose-built �data stores
Specialized services for integration
Automation by using �code
Moving away from a monolithic application
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
10
Monolith
Does everything�
Microservice
Does one thing
Section 3: Introducing Lambda
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
AWS Lambda
Lambda is a serverless compute service that you can use to run code without provisioning or managing servers.
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
12
AWS Lambda
How Lambda works
Upload your code to Lambda or write code in the Lambda editor
Set up your code to run when events occur in other AWS services, at HTTP endpoints, or as part of in-app activity
Lambda runs your code only when it is activated by an event and uses only the compute resources that are needed
Pay only for the compute time that you use
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
13
!
!
!
Lambda features
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
14
Offers the ability to bring your own code
Integrates with and �extends other AWS services
Offers flexible resource and �concurrency models
Offers a flexible permissions model
Provides built-in availability �and fault tolerance
Reduces the need to pay for idle resources
Example use cases for Lambda
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
15
Amazon S3
The front-end code for the weather app is hosted on Amazon S3
Website
A user chooses a link for local weather information
API Gateway
The app makes a REST API call to the endpoint
Lambda
Lambda runs code to get the weather data from DynamoDB and returns the data
DynamoDB
DynamoDB contains the weather data that the app uses
Web app
Kinesis
A social media stream is loaded into Kinesis in real time
Lambda
Lambda runs code that generates hashtag trend data
DynamoDB
Hashtag trend data is stored in DynamoDB
Real-time stream processing
!
An endpoint call invokes Lambda
Social media trend data is immediately available for business users to query
!
Stream events invoke Lambda
Lambda functions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
16
Access �permissions
Initiating
events
Lambda
Lambda function
Configuration
Application �code
Dependencies�and libraries
Runtime and deployment package
Lambda functions run in on-demand ephemeral environments
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
17
Concurrency:
1
2
3
4
Invocation requests
Concurrency: The number of function invocations that are running at one time
AWS Lambda
Section 3 key takeaways
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
18
Section 4: Invoking Lambda functions
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Push and pull models
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
20
Lambda
Lambda function�(custom code)
Pull (polling) event
Push �event
Lambda polls �for events and invokes �the Lambda function with batches of records
An AWS service �directly invokes the�Lambda function
Push event types
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
21
Synchronous
/order
API Gateway
Lambda�function
No retry built in
Invoke via API:�RequestResponse
Asynchronous
3 tries
Amazon S3
Lambda�function
0–2 retries
Invoke via API:�Event
The other service �waits for a �response from �your function.
Lambda �queues the event �before passing it �to your function.
Pull (polling) event types
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
22
shard
Lambda polls a stream
Lambda polls a queue
Amazon �DynamoDB Streams
Amazon Kinesis
Data Streams
Records from the stream
Lambda �function
Lambda
Records from the queue
Lambda�function
Lambda
Amazon Simple Queue Service (Amazon SQS)
Errors in a shard �block further�processing
Errors in a batch�are returned to�the queue
Invoking a function synchronously
aws lambda invoke \�--function-name my-function \�--payload '{ "name": "Bob" }' \�response.json
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
23
{"ExecutedVersion": "$LATEST","StatusCode": 200}
Response
Invoke
Invoking a function asynchronously
aws lambda invoke \�--function-name my-function \�--invocation-type Event \�--payload '{ "name": "Bob" }' \�response.json
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
24
{"StatusCode": 202}
Ack
Invoke
Section 4 key takeaways
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
25
Section 5: Setting permissions for Lambda
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Lambda permissions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
27
Initiating�event
Event sources need �permissions to invoke�a Lambda function
Lambda functions need �permissions to interact �with other services
Lambda function
Event source
AWS service or resource
Allowed�action
Invocation permissions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
28
Initiating event
Lambda function
An IAM resource policy gives permissions to invoke the function.
Resource policy:
Amazon S3 bucket
Example resource (function) policy
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
29
{
"Version": "2012-10-17",
"Id": "default",
"Statement": [
{
"Sid": "lambda-fd269e28-988b-4d2b-96ae-eabcd7dc399c",
"Effect": "Allow",
"Principal": {
"Service": "s3.amazonaws.com"
},
"Action": "lambda:InvokeFunction",
"Resource": "arn:aws:lambda:function:myFirstFunction",
"Condition": {
"ArnLike": {
"AWS:SourceARN": "arn:aws:s3:::myBucket1"
}
}
}
]
}
Lambda execution role
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
30
The Lambda execution role specifies what the Lambda function is permitted to do.
Lambda function
Allowed action
Execution role
Amazon �S3
DynamoDB
Amazon SQS
Upload a file
Read from a table
Poll a queue
CloudWatch
Write CloudWatch logs
Execution role example
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
31
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
}
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
IAM policy
Trust policy
Adding permissions by using the AWS CLI
aws lambda add-permission \�--function-name my-function \�--action lambda:InvokeFunction \�--statement-id sns \�--principal sns.amazonaws.com
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
32
{�"Statement":�{�"Sid":"sns",�"Effect":"Allow",�"Principal":{�"Service":"sns.amazonaws.com"�},�"Action":"lambda:InvokeFunction",�"Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function"�}�}
Output
Give Amazon SNS permissions to invoke a function
Section 5 key takeaways
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
33
Section 6: Authoring and configuring Lambda functions
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
The function handler
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
35
Event object�
Handler (event, context) method
Context object�
Lambda function handler example
{
"first_name": "John",
"last_name": "Smith"
}
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
36
{
"message": "Hello John Smith!"
}
Handler
event object
def lambda_handler(event, context):
message = 'Hello {} {}!'.format(event['first_name'],
event['last_name'])
return {
'message' : message
}
response
Example testing from the console
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
37
Create test event
Review results
Performance-related configurations
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
38
Configuration | Description |
Memory | Set the amount of memory and proportional CPU that is allocated to the function. Lambda allocates CPU power linearly in proportion to the memory that you set. Values from 128 MB–10,240 MB. |
Timeout | Choose the maximum amount of time to let a function run before ending it if it has not completed. Values from 1 second up to 15 minutes. |
Concurrency | Number of invocations of a function that can run at the same time. By default, you can have 1,000 concurrency invocations per Region for an account. This limit is a soft limit. Per function, you can set a limit to prevent overwhelming a downstream system or to reserve capacity from within the account pool for the function. |
Provisioned concurrency | Number of Lambda environments to keep warm. When Lambda creates the temporary environment for your function, it will attempt to reuse it for additional invocations. This approach saves startup time. When Lambda must initialize new environments to run a function, an invocation might get a cold start, which creates startup latency. Use provisioned concurrency to avoid cold starts. Provisioned concurrency is priced separately. |
Monitoring and operations | Settings to enable X-Ray (active tracing) and CloudWatch Lambda Insights (collect and aggregate Lambda function runtime performance metrics and logs). |
Resource-related configurations
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
39
Configuration | Description |
Triggers | Event sources that invoke a function. |
Permissions | The resources that have permissions to invoke the function and the permissions that the function has to interact with other resources. |
Destinations | An SNS topic, SQS queue, other Lambda function, or EventBridge event bus. It receives invocation records from a function when it is successful (on success) or when it fails (on failure). |
Asynchronous invocation | Settings for number of retry attempts on async invocations (0–2) and how long to keep an event waiting to be invoked (up to 6 hours). Also, configuration of a dead-letter queue for functions that continue to fail. |
VPC | Settings to enable your Lambda function to access resources in a custom VPC. A custom VPC defines a private network of resources, such as databases, cache instances, or internal services. |
State machines | Step Functions state machines that can invoke your function directly in at least one of the steps. |
Database proxies | Settings that are used when connecting to an Amazon Relational Database Service (Amazon RDS) instance. These settings are used to set up a database proxy to manage connection pooling for database connections. |
File systems | Settings to connect an Amazon Elastic File System (Amazon EFS) file system so that the function can access the file system at runtime. |
Code-related configurations
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
40
Configuration | Description |
Runtime | Runtime that the function will use or language that the code will be written in. Choose from supported runtimes that are listed in the AWS Lambda Developer Guide or use a custom runtime. |
Environment variables | Key-value pairs that are accessible from your function code. Environment variables are useful to store configuration settings without the need to change function code. |
Tags | Labels that you assign to an AWS resource. Each tag consists of a key and an optional value. You can use tags to search and filter your resources or track your AWS costs. |
Code signing | Option to ensure that code has been signed by an approved source and has not been altered. |
Design a Lambda function: Best practices for a Lambda environment
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
41
Design a Lambda function: Best practices for writing code
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
42
Tuning your function
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
43
Example results for two CPU-intensive functions, which become cheaper and faster with more power
Section 6 key takeaways
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
44
Section 7: Deploying Lambda functions
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Deployment options
.zip archive
Container image
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
46
Uploading .zip deployment packages
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
47
Developer
Integrated development environment (IDE)
Write and edit in the�Lambda console editor
Lambda
Test and �debug
Lambda �console
Local test �and debug
AWS Cloud
1
Upload the deployment package directly from your IDE
2
3
Compress (.zip) and upload to the S3 bucket
S3 bucket
Deploying as a container image
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
48
docker push
Amazon ECR
Container image
Upload the image to the registry
Invoke
Status: ACTIVE
Ready to invoke
Lambda
function
Container image
CreateFunction
Container image
Status: PENDING
Lambda
Versioning
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
49
Lambda function�(version $LATEST)
arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST
arn:aws:lambda:aws-region:acct-id:function:helloworld:1
Snapshot of �Lambda function�(version 1)
1
Publish
Aliases
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
50
Lambda function�(version $LATEST)
Lambda function�(version 2)
2
Lambda function�(version 1)
1
Lambda function test alias:
arn:aws:lambda:aws-region:acct-id:function:helloworld:test
Dev
Test
Prod
Example of using versioning and aliases
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
51
arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST
Amazon S3
Event source mapping that uses the Lambda function ARN �(update with each version)
Lambda function�(version $LATEST)
Snapshot of �Lambda function�(version 1)
1
Publish
arn:aws:lambda:aws-region:acct-id:function:helloworld:1
Without aliases:
arn:aws:lambda:aws-region:acct-id:function:helloworld:PROD
Amazon S3
With aliases:
Event source mapping that uses the alias ARN �(don’t need to update with each version)
Custom runtimes
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
52
Lambda layers
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
53
Centrally manage code and data that are shared across multiple functions
Example deploying from the AWS CLI
aws lambda create-function \�--function-name my-function \�--runtime nodejs10.x \�--zip-file fileb://my-function.zip \�--handler my-function.handler \�--role arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-tges6bf4
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
54
{�"TracingConfig": {�"Mode": "PassThrough"�},�"CodeSha256": "PFn4S+er27qk+UuZSTKEQfNKG/XNn7QJs90mJgq6oH8=",�"FunctionName": "my-function",�"CodeSize": 308,�"RevisionId": "873282ed-4cd3-4dc8-a069-d0c647e470c6",�"MemorySize": 128,�"FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",�"Version": "$LATEST",�"Role": "arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-zgur6bf4",�"Timeout": 3,�"LastModified": "2019-08-14T22:26:11.234+0000",�"Handler": "my-function.handler",�"Runtime": "nodejs10.x",�}
Output
Create function
Example of updating a function from the AWS CLI
aws lambda update-function-code \�--function-name my-function \�--zip-file fileb://my-function.zip
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
55
{�"FunctionName": "my-function",�"LastModified": "2019-09-26T20:28:40.438+0000",�"RevisionId": "e52502d4-9320-4688-9cd6-152a6ab7490d",�"MemorySize": 256,�"Version": "$LATEST",�"Role": "arn:aws:iam::123456789012:role/service-role/my-function-role-uy3l9qyq",�"Timeout": 3,�"Runtime": "nodejs10.x",�"TracingConfig": {�"Mode": "PassThrough"�},�"CodeSha256": "5tT2qgzYUHaqwR716pZ2dpkn/0J1FrzJmlKidWoaCgk=",�"CodeSize": 304,�"FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",�"Handler": "index.handler"�}
Output
Update function
Section 7 key takeaways
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
56
Section 8: Monitoring and debugging tools for application developers
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Modern applications challenge traditional monitoring approaches
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
58
Faster release velocity
User experience
More devices, services, and data
Short-lived resources
Amazon CloudWatch
CloudWatch collects monitoring and operational data in the form of logs, metrics, and events.
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
59
Amazon CloudWatch
Example of Lambda logging
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
60
Time | Message |
19:35:32 | START RequestId: 41c8dcf0-ff10-4d96-af2a-1ab5e346c937 Version: $LATEST |
19:35:32 | 2020-08-27T19:35:32.553Z 41c8dcf0-ff10-4d96-af2a-1ab5e346c937 INFO … |
19:35:32 | 2020-08-27T19:35:32.575Z 41c8dcf0-ff10-4d96-af2a-1ab5e346c937 INFO … |
19:35:32 | END RequestId: 41c8dcf0-ff10-4d96-af2a-1ab5e346c937 |
19:35:32 | REPORT RequestId: 41c8dcf0-ff10-4d96-af2a-1ab5e346c937 Duration: 64.40 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 68 MB Init Duration: 162.85 ms |
19:35:36 | START RequestId: a23cbea6-3053-4b51-8721-ff11aba24e33 Version: $LATEST |
… | |
CloudWatch > Log Groups > /aws/lambda/FAQ > 2020/08/27/[$LATEST]05419d29f9014fc3b1634b1e9968ef28
Log group
Log stream
Log events
AWS X-Ray
X-Ray traces requests that travel through your application and shows a map of your application’s underlying component.
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
61
AWS X-Ray
Parts of an X-Ray trace
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
62
Element | Description |
Segments | Data about the work done by compute resources that run your application, including:
|
Subsegments | Breakdown of segment data into greater detail, including:
|
Annotations | Key-value pairs that can be indexed and used with filter expressions to group traces in the console for easier analysis |
Metadata | Key-value pairs of any type that are not indexed but can be used to store data in the trace that you won’t use for searching traces |
Example X-Ray trace
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
63
Segments�
Subsegments�
Annotations�
Demonstration: Using X-Ray with Lambda
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
64
Section 8 key takeaways
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
65
Lab 7.1: Creating Lambda Functions Using the AWS SDK for Python��
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
66
Lab: Scenario
In this lab, you again play the role of Sofía. You replace the mock endpoints that you created in the previous lab with real endpoints so that the web application can connect to the database. You will use Lambda to make this connection between the REST API and the data that is stored in DynamoDB.
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
67
Lab: Tasks
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
68
Lab: Final product
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
69
API Gateway
products
endpoint
DynamoDB
FoodProducts
Table (stores menu information)
Lambda
An S3 bucket
hosts the café website HTML and JavaScript pages
A café website user chooses a link on the website
1
2
3
The endpoint invokes the Lambda function
4
Lambda queries the database table
A café website user loads the café home page
create_report
endpoint
get_all_products
function
Data is returned
5
create_report
function
Begin Lab 7.1: �Creating Lambda Functions Using the AWS SDK for Python
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
70
~ 90 minutes
Lab debrief: �Key takeaways
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
71
Module wrap-up
Module 7: Developing Event-Driven Serverless Solutions
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
Module summary
In summary, in this module, you learned how to:
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
73
Complete the knowledge check
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
74
Sample exam question
A developer is testing an application locally and has deployed it to Lambda. To remain under the package size limit, they did not include the dependencies in the deployment file. When testing the application remotely, the function does not run because of missing dependencies.
Which approach would best resolve the issue?
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
75
Additional resources
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
76
Thank you
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved. This work may not be reproduced or redistributed, in whole or in part, without prior written permission from Amazon Web Services, Inc. Commercial copying, lending, or selling is prohibited. Corrections, feedback, or other questions? Contact us at https://support.aws.amazon.com/#/contacts/aws-training. All trademarks are the property of their owners.
Serverless as part of developing a cloud application
© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.
78
Café employees
Elastic Beanstalk
ECR hosts Docker image
EC2 instance with Docker container runs coffee supplier website
Aurora Serverless on RDS stores supplier database
AWS WAF �secures API endpoint
Café employees
Refresh cache per settings
CloudFront distribution
ElastiCache �for Memcached
AWS WAF �secures website
SNS
SQS
Suppliers
Coffee inventory
updates
Lambda
Step Functions �retrieves data from RDS and posts report to S3 with presigned URL
Amazon Cognito provides token for report requests
Amazon S3�
Developers
AWS Cloud9
CloudShell
AWS CLI
SDK for Python
Console
�bucket hosts café website
Café website users
Webpage �requests
Bucket policy
DynamoDB database stores products table
API Gateway REST API
Lambda function �does database lookups