1 of 78

Module 7: Developing Event-Driven Serverless Solutions

AWS Academy Cloud Developing

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

2 of 78

Section 1: Introduction

Module 7: Developing Event-Driven Serverless Solutions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

3 of 78

Module objectives

At the end of this module, you should be able to:

  • Explain serverless computing
  • Describe how AWS Lambda works
  • Recognize Lambda invocation models
  • Identify how to use AWS Identity and Access Management (IAM) to grant Lambda permissions
  • Indicate the steps to author and configure a Lambda function
  • Explain how to deploy Lambda functions
  • Identify why AWS X-Ray is a critical developer tool 
  • Create Lambda functions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

3

4 of 78

Module overview

Sections

  1. Introduction
  2. Introducing serverless computing
  3. Introducing Lambda
  4. Invoking Lambda functions
  5. Setting permissions for Lambda
  6. Authoring and configuring Lambda functions
  7. Deploying Lambda functions
  8. Monitoring and debugging tools for application developers

Demonstration

  • Using X-Ray with Lambda

Lab

  • Creating Lambda Functions Using the AWS SDK for Python

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

4

Knowledge check

5 of 78

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

6 of 78

Serverless as part of developing a cloud application

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

6

7 of 78

Section 2: Introducing serverless computing

Module 7: Developing Event-Driven Serverless Solutions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

8 of 78

Serverless computing

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

8

Focus on business logic

Level of abstraction

  • Heavy capital expense
  • Guessed capacity
  • Deployed in months
  • Years of maintenance
  • Low innovation factor

On premises

  • Hardware independence
  • Elastic resources and scale
  • Faster provisioning
  • Reduced maintenance

Virtual servers in the cloud

  • Platform independence
  • Higher resource utilization
  • Easier and faster deployments
  • Isolation and sandboxing

Containers

  • No OS instances to manage
  • Flexible scaling
  • Pay per usage
  • Built-in fault tolerance
  • Zero maintenance

Serverless

9 of 78

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

10 of 78

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

11 of 78

Section 3: Introducing Lambda

Module 7: Developing Event-Driven Serverless Solutions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

12 of 78

AWS Lambda

Lambda is a serverless compute service that you can use to run code without provisioning or managing servers.

  • Invokes your code in response to events
  • Scales automatically
  • Provides built-in code monitoring and logging with Amazon CloudWatch

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

12

AWS Lambda

13 of 78

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

!

!

!

14 of 78

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

15 of 78

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

16 of 78

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

17 of 78

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

18 of 78

Section 3 key takeaways

  • Lambda is a serverless compute service that integrates with other AWS services.
  • You can use Lambda for many use cases including web applications, backends, and data processing.
  • Lambda functions run in on-demand temporary environments.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

18

19 of 78

Section 4: Invoking Lambda functions

Module 7: Developing Event-Driven Serverless Solutions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

20 of 78

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

21 of 78

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.

22 of 78

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

23 of 78

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

24 of 78

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

25 of 78

Section 4 key takeaways

  • Lambda invokes Lambda functions by using one of these invocation models:
    • Synchronous
    • Asynchronous
    • Polling (event source mapping)
  • Lambda has built-in handling that differs by event source type.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

25

26 of 78

Section 5: Setting permissions for Lambda

Module 7: Developing Event-Driven Serverless Solutions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

27 of 78

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

28 of 78

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:

  • Associated with synchronous or asynchronous event source
  • Allows the event source to take the lambda:InvokeFunction action

Amazon S3 bucket

29 of 78

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"

}

}

}

]

}

30 of 78

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

  • IAM policy
  • Trust policy

Execution role

Amazon �S3

DynamoDB

Amazon SQS

Upload a file

Read from a table

Poll a queue

CloudWatch

Write CloudWatch logs

31 of 78

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

32 of 78

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

33 of 78

Section 5 key takeaways

  • Lambda functions require permissions to be invoked and permissions to interact with other services.
  • Both types of permissions are defined by using IAM or trust policies.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

33

34 of 78

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.

35 of 78

The function handler

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

35

Event object

  • Passes event information to the handler
  • Uses a predefined object format for AWS integrations and events
  • Can be tested with user-defined custom objects

Handler (event, context) method

Context object

  • Passes runtime information to the handler
  • Includes, at a minimum, these methods or properties:
    • awsRequestId
    • getRemainingTimeInMillis()
    • logStreamName

36 of 78

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

37 of 78

Example testing from the console

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

37

Create test event

Review results

38 of 78

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

39 of 78

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.

40 of 78

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.

41 of 78

Design a Lambda function: Best practices for a Lambda environment

  • Treat functions as stateless.
  • Include only what you need.
  • Reuse the temporary runtime environment.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

41

42 of 78

Design a Lambda function: Best practices for writing code

  • Separate the core business logic (outside of the handler method).
  • Write modular functions.
  • Include logging statements.
  • Include results information.
  • Use environment variables.
  • Avoid recursive code.
  • Don't call one function from another.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

42

43 of 78

Tuning your function

  • Higher memory configurations have a higher per-1-millisecond cost but might decrease duration costs and concurrency needs.
  • Find the balance that optimizes for speed and cost.

© 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

44 of 78

Section 6 key takeaways

  • Lambda supports different languages and runtimes.
  • The function handler is the entry point into the Lambda function.
  • You can configure attributes including the amount of memory and function timeout.
  • Follow best coding practices to create efficient Lambda functions.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

44

45 of 78

Section 7: Deploying Lambda functions

Module 7: Developing Event-Driven Serverless Solutions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

46 of 78

Deployment options

.zip archive

  • Choose a runtime when you create the function.
  • Compress files for application code and dependencies, and upload them to Lambda.

Container image

  • Choose a runtime and linux distribution when creating the image.
  • Package your code and dependencies as a container image.
  • Upload the image to your container registry that is hosted on Amazon Elastic Container Registry (Amazon ECR).

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

46

47 of 78

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

48 of 78

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

  1. Pull the image from Amazon ECR
  2. Optimize the image
  3. Deploy the image to Lambda

CreateFunction

Container image

Status: PENDING

Lambda

49 of 78

Versioning

  • Immutable copies of Lambda function code �and configuration
  • Create: $LATEST version

  • Publish: Snapshot copy of $LATEST
  • Each version has its own Amazon Resource Name (ARN) with a new sequential version number

© 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

50 of 78

Aliases

  • Mutable pointers to versions
  • Each alias has its own ARN

© 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

51 of 78

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)

52 of 78

Custom runtimes

  • With custom runtimes you can use other languages in Lambda.
  • Lambda provides a runtime interface for getting events and sending responses.
  • The bootstrap file is the runtime's entry point.
  • You can deploy a custom runtime next to your function code or in a layer.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

52

53 of 78

Lambda layers

  • Reduce the size of deployment packages
  • Speed up deployments
  • Limits:
    • Up to five layers
    • 250 MB

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

53

Centrally manage code and data that are shared across multiple functions

54 of 78

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

55 of 78

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

56 of 78

Section 7 key takeaways

  • Lambda has built-in versioning so that you can create immutable versions of your code.
  • You can use aliases to point at different versions of your Lambda function.
  • Lambda provides popular runtimes, but you can create custom runtimes.
  • Lambda layers are libraries of code that you create and which other Lambda functions can call.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

56

57 of 78

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.

58 of 78

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

59 of 78

Amazon CloudWatch

CloudWatch collects monitoring and operational data in the form of logs, metrics, and events.

  • Get a unified view of AWS resources, applications, and services
  • Review logs as a flow of events ordered by time
  • Query log data interactively with CloudWatch Logs Insights
  • Use default operational metrics from AWS services
  • Alarm based on metric thresholds and initiate automated actions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

59

Amazon CloudWatch

60 of 78

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

61 of 78

AWS X-Ray

X-Ray traces requests that travel through your application and shows a map of your application’s underlying component.

  • One-click enablement for Lambda functions and integration with other AWS services
  • X-Ray SDK to capture metadata for API calls that are made to AWS services with the AWS SDK
  • Visual detection of latency distribution and quick isolation of outliers and trends
  • Easier debugging of application code
  • Filtering and grouping of requests by error type

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

61

AWS X-Ray

62 of 78

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:

  • Resource name
  • Details about the request and the work that is done
  • Subsegments

Subsegments

Breakdown of segment data into greater detail, including:

  • More granular timing
  • Details about downstream calls
  • Inferred segments for downstream services
  • Annotations and metadata

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

63 of 78

Example X-Ray trace

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

63

Segments�

Subsegments�

Annotations�

64 of 78

Demonstration: Using X-Ray with Lambda

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

64

65 of 78

Section 8 key takeaways

  • Modern applications require more than traditional operations monitoring.
  • CloudWatch provides built-in logging and metrics to monitor your Lambda functions.
  • With X-Ray, you can trace requests across your application to find trouble spots quickly.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

65

66 of 78

Lab 7.1: Creating Lambda Functions Using the AWS SDK for Python��

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

66

67 of 78

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

68 of 78

Lab: Tasks

  1. Preparing the development environment
  2. Creating the get_all_products Lambda function
  3. Configuring the REST API GET method to invoke the Lambda function
  4. Creating the create_report Lambda function
  5. Configuring the REST API POST method to invoke the Lambda function
  6. Testing the integration by using the café website

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

68

69 of 78

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

70 of 78

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

71 of 78

Lab debrief: �Key takeaways

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

71

72 of 78

Module wrap-up

Module 7: Developing Event-Driven Serverless Solutions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

73 of 78

Module summary

In summary, in this module, you learned how to:

  • Explain serverless computing
  • Describe how Lambda works
  • Recognize Lambda invocation models
  • Identify how to use IAM to grant Lambda permissions
  • Indicate the steps to author and configure a Lambda function
  • Explain how to deploy Lambda functions
  • Identify why X-Ray is a critical developer tool 
  • Create Lambda functions

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

73

74 of 78

Complete the knowledge check

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

74

75 of 78

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?

  1. Use the Lambda console editor to update the code and include the missing dependencies.
  2. Create an additional .zip file with the missing dependencies, and include the file in the original Lambda deployment package.
  3. Add references to the missing dependencies in the Lambda function’s environment variables.
  4. Create a layer that contains the missing dependencies, and attach it to the Lambda function.

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

75

76 of 78

Additional resources

© 2021, Amazon Web Services, Inc. or its affiliates. All rights reserved.

76

77 of 78

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.

78 of 78

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