16 - Serverless Overviews

AWS Lambda

awslambdaserverlesssaa-c03

Overview

AWS Lambda runs virtual functions with no servers to manage. You provision only the code and the functions run.

Amazon EC2 AWS Lambda
Servers Virtual servers you provision, limited by the memory and CPU you pick No servers to manage
Running time Run continuously, whether or not anything happens on the instance (can be optimized by starting and stopping) Short executions, up to 15 minutes
Billing While running Only while the function runs, on demand (not running when not invoked)
Scaling Auto Scaling groups, but you must add and remove servers Automated. AWS provisions more function occurrences and concurrency

Benefits

  • Simple pricing: pay for the number of requests (invocations) and compute time.
  • Generous free tier: 1 million Lambda requests and 400,000 GB-seconds of compute time.
  • Integrated with many AWS services.
  • Many programming languages.
  • Easy monitoring through CloudWatch.
  • Up to 10 GB of RAM per function.
RAM, CPU and network

Increasing the RAM of a function also improves its CPU and network quality and performance. You need to know this.


Languages and Containers

  • Natively: Node.js (JavaScript), Python, Java, C# (.NET Core), PowerShell, Ruby.
  • Other languages through the Custom Runtime API, for example Rust or Golang.
  • Lambda container images are supported, but the image must implement the Lambda Runtime API.

You do not need to memorize all languages. The most important are Node.js and Python.

Docker on the exam

To run Docker images, the exam prefers ECS or Fargate over Lambda, even though Lambda can run some customized container images.


Integrations

Service How it uses Lambda
API Gateway Create a REST API that invokes Lambda functions
Kinesis Transform data on the fly
DynamoDB Triggers: a function runs when something happens in the database
S3 Function triggered when, for example, a file is created
CloudFront Lambda@Edge (see 06-Lambda-Edge-and-CloudFront-Functions)
CloudWatch Events / EventBridge React to infrastructure events, e.g. a CodePipeline state change, to automate things
CloudWatch Logs Stream logs wherever you want
SNS React to notifications on SNS topics
SQS Process messages from SQS queues
Cognito React when, for example, a user logs in

These are only the main ones. There are many more Lambda integrations. (The transcript says "to your database" for the Cognito login example, likely a slip.)


Example Architectures

Serverless thumbnail creation

  1. A new image is uploaded to Amazon S3.
  2. An S3 event notification triggers a Lambda function.
  3. The function generates a thumbnail and uploads it to another S3 bucket or the same one.
  4. The function may also insert metadata (image name, size, creation date, etc.) into DynamoDB.

Result: a reactive, automated architecture for new images.

Serverless CRON job

  • CRON on an EC2 instance wastes instance time when it is not doing anything.
  • Instead, create a CloudWatch Events / EventBridge rule triggered, for example, every hour, integrated with a Lambda function that performs the task.
  • Both CloudWatch Events and Lambda are serverless, so this is a serverless CRON.

Pricing

Check the AWS pricing page if figures are outdated.

Item Price
Requests First 1 million free, then $0.20 per extra 1 million requests
Duration Billed in increments of 1 millisecond
Compute free tier First 400,000 GB-seconds per month free
After free tier $1 for 600,000 GB-seconds

GB-seconds explained: 400,000 GB-seconds equals 400,000 seconds of execution for a function with 1 GB of RAM. A function with 128 MB of RAM gets 8 times more seconds. Running code on Lambda is usually very cheap.


Hands-On Walkthrough

Explore the intro page

  1. In the Lambda console, replace /discover with /begin in the URL to get an educational page.
  2. Lambda supports .NET Core, Go, Java, Node.js, Python, Ruby, or a custom runtime (e.g. the Lambda Rust Runtime).
  3. Click Run on the sample Python handler (prints the event, returns "Hello from Lambda").
  4. Lambda can also respond to events from sources such as streaming analytics, a mobile IoT backend, or a photo uploaded to S3. As the load grows, the number of concurrent invocations scales too.
  5. Cost stays zero in the free tier. Past 1 million invocations charges begin. In the demo, almost 2 million invocations cost only about 14 cents.

Create a function

  1. Click Create function and choose Use a blueprint -> hello world -> Python (3.10 in the demo, any Python works).
  2. Function name demo-lambda. Create a new role with basic Lambda permissions (the function's IAM execution role).
  3. The code has a lambda handler that handles the invocation event. It prints values and returns key1.
  4. Click Create function. The code appears in the editor as lambda_function.py.

Test

  1. Click Test and create a new test event named DemoEvent (hello world template with key1: value1, key2: value2, key3: value3 as JSON).
  2. Click Test. The response is value1, and the function log shows the three print statements.
  3. First run: duration 2.32 ms, billed 3 ms. The result also shows memory size provisioned, memory used and init duration (first use).
  4. Second run: duration 1.33 ms with no init, since the function was ready.

Configuration

  • General configuration -> Memory: 128 MB to 10,240 MB. More memory costs more.
  • Timeout: from a few seconds (the transcript says "three seconds or five seconds", unclear) up to 15 minutes. Set it only as long as needed.
  • Execution role: the one Lambda created.
  • Runtime settings: Python in the demo (the transcript says 3.7 here and 3.10 earlier, unclear). The handler is lambda_function.lambda_handler, meaning file lambda_function.py and function lambda_handler.

Monitoring and logs

  1. Monitoring tab shows invocations, duration, errors and successes, with CloudWatch metrics and CloudWatch Logs integration.
  2. Refresh recent invocations to see a log stream. Click it to open CloudWatch Logs.
  3. Log group is /aws/lambda/demo-lambda (named after the function, in your region), with one log stream per run.

Force an error

  1. Comment one line and uncomment the line that raises an exception.
  2. Click Deploy, then Test. The result is an error of type Exception.
  3. A second log stream in CloudWatch Logs holds the exception, so you can find the root cause.
  4. Revert the change, deploy, and test again to make it work.

Permissions

  • In Configuration -> Permissions the role demo lambda role was created by the console.
  • Its policy allows writing to CloudWatch Logs. The resource summary shows 3 actions and 2 resources: create log group, create log stream, and send logs to CloudWatch Logs.
Exam scope

The instructor says this is enough for the SAA exam. The Certified Developer course goes deeper on Lambda.


Questions & Answers

Q1: What is the maximum execution time of a Lambda function?

Answer:

15 minutes (900 seconds). See 03-Lambda-Limits.

Q2: How is Lambda billed?

Answer:

By number of requests and duration (1 ms increments). Free tier: 1 million requests and 400,000 GB-seconds per month.

Q3: How do you give a Lambda function more CPU?

Answer:

Increase its RAM (up to 10 GB). CPU and network improve with it.

Q4: Lambda or ECS/Fargate for Docker images?

Answer:

ECS or Fargate is preferred on the exam.

Q5: How do you build a serverless CRON job?

Answer:

A CloudWatch Events / EventBridge rule on a schedule that triggers a Lambda function.

Q6: Why can the demo function write to CloudWatch Logs?

Answer:

Its execution role (created with basic Lambda permissions) allows creating log groups and streams and sending logs.

Check yourself

Quiz

Flashcards

Click the card (or focus it), then use ← → to move and Space to flip.