Serverless Course Slide 012022
Serverless Course Slide 012022
● You own the kitchen ● You do NOT own kitchen ● You do NOT own kitchen
● You spend money buying ● You get food from a takeout place ● You get food from a takeout place who
every appliance who delivers instantly delivers instantly
● You pay for the electricity ● However, takeout place only ● However, this takeout place accepts
used in the kitchen delivers food exactly for 5 people at order for any number of people
● You make food for 20 a time ● You simply put order for the exact
people everyday ● If 3 people show up, you waste food number of people showed up
● Lot of wasted food of 2 people ● Best cost optimized solution
● If 7 people show up, you place 2
orders, each for 5 people, still some
waste
● Better than Traditional Datacenter
but still little wasteful
● You own the datacenter ● You do NOT own the datacenter ● You do NOT own the datacenter
building ● You provision EC2 ● You utilize Serverless Services
● You spend money buying ● However, each EC2 comes with ● If more traffic hits, it auto scales
every server fixed processing power and automatically
● You pay for the cost of memory ● You pay for the number of executions
datacenter i.e. electricity, ● Sometimes traffic would be less rather than idle resources
AC etc. than EC2 capacity ● Best cost optimized solution
● You buy enough servers to ● If EC2 reaches capacity, add
accommodate for huge another EC2 via Auto Scaling
traffic Group, but with fixed predetermined
● Lot of wasted $$$ capacity
● Better than Traditional Datacenter
but still little wasteful
Traffic
CPU
Traffic
CPU
Traffic
CPU CPU
Auto Scaling
Amazon EC2 Amazon EC2
Utilization 30%
Cost 100%
Traffic
AWS Lambda
Traffic
Traffic
No AMI Rehydration
Aurora Serverless
AWS Lambda Amazon API Amazon SQS AWS Step
Gateway Functions
DynamoDB
Amazon S3
And More...
Copyright © Rajdeep Saha - All Rights Reserved
Crown Jewel of Serverless
● With Lambda, you can run code for virtually any type of
application or backend service - all with zero administration
S3 Bucket
Object Put
Aurora
Message in SQS
https://s3.amazonaws.com/lambda-tools/pricing-calculator.html
Ways To Create
Lambda
Ways To Create Serverless
AWS Console
CloudFormation/SAM/CDK
AWS CLI
AWS Console
CloudFormation/SAM/CDK
AWS CLI
AWS Console
CloudFormation/SAM/CDK
AWS CLI
RDS Dynamo
S3
Other 100s of
Services
EC2
Comprehend
QLDB MQ
IAM Roles
aws s3 ls
Ap
plic
a
EC2 Ap
Dy tion
na rea S3
plic mo ds
Role attached to EC2 a ti
Dy on w
na rite
mo s
Policy to access S3 to
Developer
Project Team A Project Team B
EC2 EC2
Dynamo S3 RDS
Is This Service
Serverless
Serverless
Amazon SQS
Not
Serverless
Amazon Kinesis
Not
Serverless
Amazon EC2
RESTAURANT
KITCHEN
RESTAURANT
KITCHEN
Response
YOU
Real life example of APIs
I hope it is
payday!
Get Balance
API
Time to lookup
that fancy
restaurant
Get Balance
API
Time to lookup
that fancy
restaurant
Book Taxi
Look Up Flight Deals
Browse Items in Online Store
RESTAURANT
KITCHEN
Reques
t Desser
t
Dessert
Another hungry patron API
Station
Method Integration
Request Request
Lambda backend
Client
Method Integration
Response Response
Usage Plan - A usage plan provides selected API clients with access to one or more deployed
APIs. You can use a usage plan to configure throttling and quota limits, which are enforced on
individual client API keys
API Developer - Your AWS account that owns an API Gateway deployment (for example, a service
provider that also supports programmatic access.)
App Developer - An app creator who may or may not have an AWS account and interacts with the
API that you, the API developer, have deployed. App developers are your customers. An app
developer is typically identified by an API key.
Methods (GET, POST etc.) - Each method along with resources, are deployed to stages,
with invoke url for each method under each resource in each stage
Lambda Version and
Alias
Version 1 $LATEST
50%
Version 2 $LATEST
API Alias
Gateway oldestNewest
Version 3 $LATEST
50%
Version 4 $LATEST
API Gateway Canary Deployment
100%
Lambda 1
0%
50% Base Version
100%
50%
Lambda 1 modified
Canary Version
Base Version
API Gateway API
Endpoint Types
API Gateway
What is CORS?
● Browser security feature that restricts cross-origin HTTP requests
1 Can I do a GET?
Application Lambda
Copyright © Rajdeep Saha - All Rights Reserved
Multi Origin CORS Flow
1 OPTIONS
Access-Control-Request-Method: GET
Access-Control-Request-Headers: Content-Type,
Authorization,x-api-key
Web Browser
(www.example.com) 2 Allowed values Returned
Access-Control-Request-Method: GET, POST CORS Lambda
Access-Control-Request-Headers: Content-Type,
(Sets Header based
Authorization,x-api-key
Web Browser Access-Control-Allow-Origin: www.example.com on incoming origin)
(www.demo.com) OR
Access-Control-Allow-Origin: www.demo.com
HTTP API
Copyright © Rajdeep Saha - All Rights Reserved
HTTP APIs - What and Why?
Source: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
Copyright © Rajdeep Saha - All Rights Reserved
HTTP API Vs Rest API - Integration
Source: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
Copyright © Rajdeep Saha - All Rights Reserved
HTTP API Vs Rest API - Security
Source: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
Copyright © Rajdeep Saha - All Rights Reserved
HTTP API Vs Rest API - Authorizers
Source: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
Copyright © Rajdeep Saha - All Rights Reserved
HTTP API Vs Rest API - API Management
Source: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
Copyright © Rajdeep Saha - All Rights Reserved
HTTP API Vs Rest API - Monitoring
Source: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
Copyright © Rajdeep Saha - All Rights Reserved
HTTP API Vs Rest API - Development
Source: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vs-rest.html
Copyright © Rajdeep Saha - All Rights Reserved
Custom Domain API Gateway
Using API Gateway Url
Invoke API
Amazon API Gateway
Invoke
URL: https://p6xpfsiz5m.execute-api.us-west-2.amazonaws.com/default/myfirstlambda
Using API Gateway Url
Invoke API
Amazon API Gateway
Invoke API
Amazon API Gateway
Amazon EC2
https://lambda-api.com
Amazon EC2
https://lambda-api.com
...
• Container comes up
Cold Start
• Loads your code
• Run Code
● Limit of Scaling
● Rate of Scaling
Lambda Code Execution Under The Hood
Lambda
Lambda
Invoke
Invoke
...
...
Provisioned Concurrency
Lambda Environment
json boto3
Lambda Code
import json ✅
import boto3 ✅
import requests ✅❌
• Demo
• Best practices
• AWS provides underlying container, your
code/dependencies gets loaded
• Package and deploy Lambda function as container
images
• This does NOT run Lambda code on EKS/ECS
(NOT Knative/CloudRun equivalent)
• Container image can be up to 10 GB in size
(Compared to 50 MB for Zip deployment )
Dockerize app
Amazon Elastic Container
Registry
Lambda Container Image Support
Dockerize app
Amazon Elastic Container
Registry
Dockerize app
Amazon Elastic Container
Registry
getAccountBalance
createAccountLambda
updateAccountBalance
Lambda Layers re:Invent 2018 Update
● Layers simplify sharing, versioning, and deploying common code.
● 250 MB total size limit unchanged (total layers, unzipped).
● Up to 5 layers per function.
Put shared code into discrete layers Don’t put unnecessary stuff into the layer,
don’t treat it as dumpstar! It will increase
Version layers and use to deploy across code loading time.
accounts
+ =
Copyright © Rajdeep Saha - All Rights Reserved
Lambda EFS Integration
Amazon EC2
+ =
https://aws.amazon.com/blogs/aws/new-a-shared-file-system-for-your-lambda-functions/
W !
N E
RDS Proxy
Regular Lambda Database Design
• Priced per vCPU per hour for each enabled database instance
RDS Proxy – Demo
• NOT FREE - Priced per vCPU per hour for each enabled database instance
RDS Proxy – Demo
• IAM Prerequisites
• IAM Role for RDS proxy
• IAM Role for Lambda
● Stop EC2
AWS Lambda
Event
(event-based)
High Level Design
AWS Lambda
Amazon Simple
Notification Service
SubscriberA
SystemA
Publishes a
Topic
message SubscriberB
SubscriberC
AWS Lambda
Copyright © Rajdeep Saha - All Rights Reserved
Advantages of SNS
● Automatically scale
SystemA
Puts a
Queue
message AWS Lambda
● Standard Queue
● FIFO Queue
Copyright © Rajdeep Saha - All Rights Reserved
Standard Vs FIFO
Standard FIFO
● Order is not guaranteed ● Order is strictly preserved
● Scales automatically
Your Lambda
SQS Queue Function
Your Lambda
SQS Queue Function
Batch Size = 6 (Limit 10)
5 =< Polling limit <= Lambda
concurrency limit
SQS Queue
Copyright © Rajdeep Saha - All Rights Reserved
Sunny Day Scenario
SQS Queue
Your Lambda Function
Batch Size = 6 (Limit 10)
5 =< Polling limit <= Lambda
concurrency limit
Your Lambda Function
Copyright © Rajdeep Saha - All Rights Reserved
Rainy Day Scenario
SQS Queue
Your Lambda Function
Batch Size = 6 (Limit 10)
5 =< Polling limit <= Lambda
concurrency limit
Your Lambda Function
Copyright © Rajdeep Saha - All Rights Reserved
Rainy Day Scenario
SQS Queue
Your Lambda Function
Batch Size = 6 (Limit 10)
5 =< Polling limit <= Lambda
concurrency limit
Your Lambda Function
Copyright © Rajdeep Saha - All Rights Reserved
Rainy Day Scenario
SQS Queue
Your Lambda Function
Batch Size = 6 (Limit 10)
5 =< Polling limit <= Lambda
concurrency limit
Your Lambda Function
Copyright © Rajdeep Saha - All Rights Reserved
Solving Message Re-Processing
SQS Queue
Your Lambda Function
Batch Size = 6 (Limit 10)
5 =< Polling limit <= Lambda
concurrency limit
Your Lambda Function
Copyright © Rajdeep Saha - All Rights Reserved
Sync to Async: High Volume Traffic
System A calls a Lambda.Traffic volume very high.
AWS Lambda
SystemA
SystemA
SystemA
Very High
Volume Traffic
Amazon Simple Storage AWS Lambda AWS Lambda
Amazon Simple Queue
Service (S3) (Triggered from S3) (Processing)
Service
Topic
Lambda
(HomeLoan)
Amazon
All kinds of Loans SNS
SMS
(All Loans)
SNS MESSAGE FILTERING
Lambda (HomeLoan)
SNS
All kinds
of Loans Topic for Loans
Email (CarLoan)
SNS Service automatically scales, use Lambda per function concurrency setting to control
downstream consumption.
SQS Service automatically scales, use Lambda trigger Batch size setting and Per Function
Concurrency setting to control downstream consumption.
EventBridge Service automatically scales automatically up with default soft quotas of 400 PutEvents
and 750 target invocations requests per second (can be increased). Use Lambda per
function concurrency setting to control downstream consumption.
Conditional Message Processing
Service Conditional message processing
SQS SQS can’t decide consumer based on message. Use SNS message filtering
with SQS to achieve this
EventBridge Event filtering can route messages to targets based on message. Can
transform events before sending to target. Contains schema registry.
SNS Message Filtering
Amazon EventBridge Schema
Messag Schem
e a
Amazon EventBridge Schema Registry
Event bus
Rule2
(Pattern
Matching)
EventBridge Integration Partners
SQS SQS stores all messages within a single, highly-available AWS region with
multiple redundant Availability Zones (AZs)
EventBridge EventBridge stores all messages within a single, highly-available AWS region
with multiple redundant Availability Zones (AZs)
Pricing
Service Model Cost Per Mil Factor
EventBridge Per request $1.00 – SaaS, custom, and Each request can be up to 256
cross-account events KB in size
SNS No formal persistence model beyond delivery retry logic that extends up
through potentially 23 days.
SQS By default messages are stored for 4 days. This can be modified to as
little as 60 seconds up to 14 days by configuring a queue’s
MessageRetentionPeriod attribute
EventBridge No formal persistence model beyond delivery retry logic that extends up
through potentially 24 hours
Consumption
Service Invocation model Guidance
SNS Consumer – Lambda, SQS, email, mobile Use Message Filtering to control which
push, SMS, HTTP messages go to which subscribers. Use
Async to Lambda. SNS can ”fanout” to Message delivery status to track failures
multiple subscribing Lambda functions the
same message
SQS Consumer – Lambda, any service that can Can call message delete from within your
run AWS SDK (EC2, EKS etc.) code or let the service handle it via
Lambda service polls messages from queue successful Lambda function execution
and invokes Lambda on your behalf. Scales
polling based on inflight messages.
EventBridge Consumer – Lambda, EC2, Step Functions, Use event patterns set on rules to control
API Gateway etc. which events are subscribed to by different
Async to Lambda. EventBridge can “fanout” rules.
to have up to 5 targets per rule and multiple
rules on the same event source. 300 rules
per event bus.
Retry/Failure handling
Service Retry/failure capabilities
SNS If Lambda is not available, SNS will retry 2 times at 1 seconds apart, then 10 times
exponentially backing off from 1 seconds to 20 minutes and finally 38 times every 20
minutes for a total 50 attempts over more than 23 days before the message is
discarded. Use with SQS for DLQ.
SQS Messages remain in the queue until deleted. They are prevented by being accessed
by other consumers during the “visibility timeout”. Successful Lambda invocations will
cause deletions of messages automatically. If an invocation fails or doesn’t delete a
message during the visibility timeout, it becomes available for other consumers. DLQ
can be used.
EventBridge If Lambda or other target service is not available, EventBridge will automatically retry
delivery with backoff up to 24 hours before message is discarded from EventBridge.
As soon as successful message delivery to target occurs, message is discarded. Use
with SQS for DLQ(New)
Which one should you choose?
2 3 4
Loop 10 times with 5
● Step Function takes care of
second interval all the coordination and flow
Error control
● Create/Change flow in
Visual Console
● Lambdas become cleaner
5
Key Components of AWS Step Function
"HelloWorld": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:HelloFunction",
"Next": "AfterHelloWorldState",
"Comment": "Run the HelloWorld Lambda function"
}
States
States are elements in your state machine.
Tasks
All work in your state machine is done by tasks. A task can be an activity or a Lambda function.
Transitions
Tells the State what to do Next or where to Begin.
Step Function Workflow Types
● Standard And Express Workflows
Amazon EventBridge
Common Workflow
Start Start
Start
End
End End
Nested Workflows Tricky Note
● Keep in mind Request Response vs Sync
Step Function 1
Common Workflow
Start
Start
More States
End
End
Lambda Example
Service Integration
Start
Advantage
Start
Lambda Submits AWS Batch
Job
Start
Publish to SNS
SNS Publish will happen even if Job
didn’t complete
End
Run a Job (.sync)
● Step Function wait for the processing to complete before proceeding
Start
Publish to SNS
SNS Publish will
happen only after Job completion
End
Wait For Callback (.waitForTaskToken)
● Step Function pass a task token to integrated service
● Workflow paused until task token is returned
○ Can wait upto an year!
Start
End
Wait For Callback (.waitForTaskToken)
● Step Function pass a task token to integrated service
● Workflow paused until task token is returned
○ Can wait upto an year!
Start
SQS Database
Publish to SNS
EKS
End
Wait For Callback (.waitForTaskToken)
● Specify waiting limit using Heartbeat Timeout
Start
End
Activity Workers
Start
SQS Database
Publish to SNS
EKS
End
Activity Workers
● Step Function runs activity with input, and task token
● Some other process (NOT invoked by Step Function) reads,
processes tasks and returns output with task token
Start
On Prem
Publish to SNS
● All the logs can be fed to an analytic system for actionable insights
API Gateway & CloudWatch Logging - Beyond the Basic
Execution Logging
● Logs related to execution of the API
● Includes Logs for
○ Request and Response payloads
○ API Keys
○ Usage Plans
○ Data used by Lambda authorizers (custom authorizers)
● Log group would be created automatically, named
API-gateway-Execution-Logs_{rest-api-id}/{stage_name} format
Access Logging
● Logs related to access of the API
● Includes Logs for
○ Who accessed your API
○ How the caller accessed the API
● Create a new Log Group or send to existing one
● Logs can be generated in CLF, JSON, XML, CSV formats for ease of consumption by log analysis
system/process if applicable
S3
Cloudwatch Log Insights
Announced at re:Invent 2018
Reference: https://aws.amazon.com/xray/
Demo of AWS X-Ray with API Gateway
The AWS Command Line Interface (CLI) is a unified tool to manage your AWS services. With just one tool to download and
configure, you can control multiple AWS services from the command line and automate them through scripts.
SSH
Install AWS CLI
AWS CLI
The AWS Command Line Interface (CLI) is a unified tool to manage your AWS services. With just one tool to download and
configure, you can control multiple AWS services from the command line and automate them through scripts.
Run command to
create/update lambda
(aws lambda create-function ..)
SSH
Install AWS CLI
AWS Cloud9 - What and Why?
Home Desktop Office Laptop That machine is still here?
● Cloud-based IDE that write, run, debug your code with just a browser
● Runs in underlying EC2, granting you massive processing power
● Code, Addons and Customizations are saved in cloud
● Consistent experience, no matter which machine you log in from
● And yes, your favorite color scheme is saved as well!
AWS Cloud9 - Features
Deployment Stage
Deployment Stage
API API API
Usage Plan
(Throttling, Bursting and Quota)
API Key
Controlling Access
IAM Creds
Access key
Secret Access Key Amazon API Gateway AWS Lambda
Cognito User Pool and API Gateway Flow
User Pool
Created 1
3 (Pool ID)
User Sign up to the pool App Client
(using pool ID and Client ID) Created
2
(Client ID
generated)
User exchange creds, Assign user pool as 4
receives Token ID Authorizer for API Gateway
Validates
5 Token Method
Backend Lambda
Calls API called
Method with 6 8
Token
API Key Vs Cognito D
D E
EN
API Key Cognito M
COM
Pros Pros R E
● Easy to implement ● More secure than API key because:
● Most popular way of API security ○ Tokens automatically rotate periodically
● Less moving parts ○ Dual checkpoint - during obtaining token,
then again during token validation by API
Cons gateway
● If keys are compromised, API can be invoked ● Similar to OAUTH2, which is becoming the new
by anyone standard
● By default, keys are non expiring. Custom
process required to rotate keys periodically Cons
● Overhead of additional Authentication server
setup
● Could introduce delay to the overall response
time
Demo - Cognito User Pool & API Gateway
I User Pool
CL
S Created 1 ✅
AW
3 ✅ (Pool ID)
User Sign up to the pool App Client
(using pool ID and Client ID) Created
2 ✅
(Client ID
generated)
User exchange creds, Assign user pool as 4 ✅
receives Token ID Authorizer for API Gateway
Validates
✅ 5 I Token Method
CL
S
AW 7 ✅
Backend Lambda
Calls API called
n
ma Method with 8 ✅
st 6 ✅
Po Token
Cognito Federated Identities
AWS_IAM
Securing API With IAM
IAM Creds
Access key
Secret Access Key Amazon API Gateway AWS Lambda
Securing API With IAM
IAM Creds
IAM Creds
User Pool
Created 1
3 (Pool ID)
User Sign up to the pool App Client
(using pool ID and Client ID) Created
2
(Client ID
generated)
User exchange creds,
Assign user pool as 4
receives Token ID (JWT)
Validates Authorizer for API Gateway
5 Token Method
Backend Lambda
Calls API called
Method with 6 8
Token
Understanding Cognito Identity Pool
Assign an IAM
Sends 2 Role for
1 Identity token (JWT) Authenticated
User logs in To Cognito ipool 3
User
IAM Role
Cognito Identity Pool
User
Pool
Assign an IAM
1 Sends 2 Role for
Identity token to Authenticated
User logs in 3
Cognito User
IAM Role1
Cognito Identity Pool
User
Pool
Assign an IAM
1 Sends 2 Role for
Identity token to Authenticated
User logs in 3
Cognito User
IAM Role3
Cognito Identity Pool
User
Pool
Importing Creds
AWS Secrets Manager
Co
Co m
m pr
pr om
X
om Lambda-1 ise Lambda-1
API Gateway ise API Gateway d
in
d vo
APIApplication-1 in APIApplication-1
vok ke
e
Lambda-2 Lambda-2
API Gateway Output contains API Gateway Resource Policy allows which
APIApplication-2 sensitive info APIApplication-2 API/Resource/Method can invoke
this lambda
Lambda-3 Lambda-3
API Gateway API Gateway
APIApplication-3 APIApplication-3
Lambda Resource Policy Continued
Default Behaviour
● By default, if you invoke lambda from API in same AWS account, resource policy of Lambda is
automatically updated to allow the invocation
● For real-world projects, console access beyond development should be prohibited and should
be deployed through CI/CD toolchain with resource policy defined in Cloudformation
○ CI/CD ensures userid (who is deploying) belongs to application ID
● By default, if you invoke lambda from API Gateway from different AWS account, resource
policy of Lambda needs to be updated explicitly
● At this point (Sept, 2018), Lambda resource policy can’t be updated through console
○ Can be updated from AWS CLI and Cloudformation
Demo
Lambda Resource Policy
Demo - Lambda Resource Policy
Compromised invoke
verySensitiveFunction
API Gateway Output contains API Gateway
ProperAPI sensitive info HackerAPI
(Different Application than ProperAPI)
Create
OAUTH 1
3 Account
Auth0
User exchange creds, Assign Lambda 4
receives Token ID Authorizer for API Gateway
Lambda Authorizer Method
5 validates Token
Return IAM Policy
7
Backend Lambda
Calls API called
Method with 6 8
Token
When To Use What?
Mechanism Use Case
API Key Test app, Internal APIs, some times Prod
APIs with key rotation
Co
m
pr
om
X
ise Lambda-1
IP: 20.10.20.30 API Gateway d
X
in
APIApplication-1 vo
ke
IP: 10.50.60.30
Lambda-2
API Gateway Resource Policy allows which
APIApplication-2 API/Resource/Method can invoke
this lambda
Lambda-3
API Gateway
APIApplication-3
Security using API Gateway Resource Policy
IP: 20.10.20.30
X
IP: 10.50.60.30
API Gateway
APIApplication-2
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "arn:aws:execute-api:region:account-id:api-id/",
"Condition": {
"IpAddress": {
"aws:SourceIp": ["10.50.60.30" ]
}}}]}
Storage For Serverless
SQL Vs NoSQL Database
SQL Database (RDBMS) NoSQL Database
Good fit for joins and complex queries Generally, not good fit for complex multi table
queries
Example - Oracle, DB2, MS-SQL, AWS RDS Example - AWS DynamoDB, MongoDB,
Cassandra
Important: With the advent of technology, segregation of use cases for SQL and NoSQL are NOT
as black and white as it used to be, multiple factors need to be considered
Issue with Lambda and Traditional Database
Massive Concurrency Limit
Fixed Read Write Limit
Traffic to Lambda R/W to Database (Pay for max limit)
25% RW
Table:
What is Primary Key: The primary key uniquely identifies each item in the table, so that no
two items can have the same key.
● Partition key - A simple primary key, composed of one attribute known as the partition key.
● Partition key and sort key - Referred to as a composite primary key, this type of key is
composed of two attributes. The first attribute is the partition key, and the second attribute is
the sort key. No two items can have same combo of these two attributes.
Partition key is also referred as hash attribute, sort key also referred as range attribute
DynamoDB Items and Attributes
● The primary key for Music consists of two attributes (Artist and
SongTitle). Each item in the table must have these two attributes.
The combination of Artist and SongTitle distinguishes each item
in the table from all of the others.
● Other than the primary key, the Music table is schemaless, which
means that neither the attributes nor their data types need to
be defined beforehand. Each item can have its own distinct
attributes.
● One of the items has a nested attribute (PromotionInfo), which
contains other nested attributes.
DEMO
Creating DynamoDB table from Console
DynamoDB Primary Key
What is Primary Key: The primary key uniquely identifies each item in the table, so that no
two items can have the same key.
● Partition key - A simple primary key, composed of one attribute known as the partition key.
● Partition key and sort key - Referred to as a composite primary key, this type of key is
composed of two attributes. The first attribute is the partition key, and the second attribute is
the sort key. No two items can have same combo of these two attributes.
Example - The Music table has composite primary key (Artist and SongTitle). You can access
any item in the Music table directly, if you provide the Artist and SongTitle values for that item.
Partition key is also referred as hash attribute, sort key also referred as range attribute
DEMO
How to write items into DynamoDB from
Lambda
DEMO
How to delete DynamoDB items using Lambda
DynamoDB Secondary Indexes
Why Secondary Indexes: A secondary index lets you query the data in the table using an
alternate key, in addition to queries against the primary key.
● Global secondary index - An index with a partition key and sort key that can be different
from those on the table.
● Local secondary index – An index that has the same partition key as the table, but a
different sort key.
Note: Table design should be done in such a way that, you can achieve maximum efficiency with
minimum number of indexes. Index updates can be expensive!
DynamoDB Secondary Indexes
Customer
us-west-1 Replication slows down Customer
us-east-1
DynamoDB Global Tables
Customer
us-west-1 Customer
us-east-1
Math Time!
Q - If you create a table with 10 read and 10 write capacity units, assuming 4 KB item size for read and 1
KB item size for write, what would be the throughput (KB/Second) for strongly consistent read and write?
Pricing
● $ 1.25 per million write requests, $ 0.25 per million read requests
DynamoDB Streams
What is DynamoDB Streams: An optional feature that captures data modification events in
DynamoDB tables. The data about these events appear in the stream in near real time, and in
the order that the events occurred.
New item
inserted
Lambda Real Life Project
4
Get top news stories
1
Fetch news based
on sentiment
News API
3 6
Save news and sentiment
Lambda Real Life Project
4
Get top news stories
1
Fetch news based
on sentiment
News API
3 6
Save news and sentiment
Lambda Real Life Project - Part 1 Recap
● Cloud9
● External Dependencies
● AWS Role
Get top news stories
1 ● DynamoDB
● Lambda Write/Delete into DynamoDB
● Cloudwatch Rules
News API
● AWS Comprehend
Determine sentiment of news - ● Homework - AWS Secrets Manager
2 positive, negative, neutral
3
Lambda Real Life Project - Final Words
● Easy Integration
● Secure
● Focus on Service, not Servers!
○ Automatic AutoScaling
○ No AMI to maintain
○ No patching
○ Economical
Developer
Monitor Operate Deploy
Operations
I just
wanna
code cool
stuff
What is DevOps?
● Word “DevOps” coined in 2009 by Patrick Debois
● Combination of cultural philosophies, practices, and tools
● Development and Operations teams are no longer “siloed”
Why DevOps?
How long would it take your organization to deploy a
change that involves a single line of code?
Continuous Integration
Continuous Delivery
Continuous Deployment
Why DevOps on AWS?
● Fully Managed
● Built for Scale
● Inherent Integration with other AWS Services
● Apply Existing Knowledge of AWS SDK
● Secure
● Pay As You Go + Free Tier
● DevOps on AWS job is on high demand
DevOps On AWS - A Glimpse
Source Build Test Prod
AWS CodePipeline
What is AWS CodeCommit
● Code Repository
○ Think of GitHub, GitHub Enterprise, BitBucket
on Steroids! (More on this on next slide)
● Store Anything
○ Source Code to binaries
● Based on Git
○ Works seamlessly with existing Git tools
AWS CodeCommit Benefits
● Fully Managed
○ Eliminates need to host, maintain, backup,
scale your own source control servers
○ Scales automatically
● Secure
○ Automatic encryption at rest & in transit
○ IAM integration
● High Availability
● Collaboration
● Inherent integration with AWS Services
Diving Deeper
Code Repo
AWS CodeCommit
Continuous Integration
Branch Visualizer
What’s Different in Real World?
● Create a repository from Console
● Clone the repo to Cloud9
Bob
Source Destination
branch branch
(Master)
Bob creates pull
request
Code Repo
AWS CodeBuild
Continuous Integration
Elephant in the Room - Jenkins
Jenkins CodeBuild
GitHub
AWS CodeCommit
Many Ways to Skin a Cat!
● DevOps is deploying a change on a repeatable, reliable and
automated way
GitHub
AWS CodeCommit
GitHub
AWS CodeCommit
GitHub
AWS CodeCommit
AWS CodePipeline
CI/CD Flow-2 for Lambda
Code Repo
GitHub
AWS CodeCommit
AWS CodePipeline
Power of this Pipeline
Code Repo
GitHub
AWS CodeCommit
AWS CodePipeline
In This Lecture
● Deployment Lambda
● End to End Flow
In this CodeBuild Demo
Code Repo
GitHub
AWS CodeCommit
Deployment Lambda
Lambda Package Triggered Package
(Zip) by S3 from S3
Code Repo
AWS
CodeDeploy
AWS CodeDeploy Benefits
● Automatically Scales
○ Deploy to one or thousands instances
● Minimize Downtime
○ Rolling updates
○ Blue Green Deployments
● Stop And Roll Back
● Integrate with third party tools
● Concurrent Deployments
CodeDeploy For Lambda
● CodeDeploy can NOT deploy Lambda code currently
(As of 08/2019)
● CodeDeploy can switch Lambda traffic from one
version to another
○ All at once
○ Canary
● CodePipeline CAN deploy Lambda code
○ CodeDeploy can switch traffic after deploy
○ Both are covered in the course :)
AppSpec
● AppSpec file tells CodeDeploy what
tasks to do in what order
● Deployment Groups
● Deployment Type
● Deployment Configurations
Deployment Groups
Set of Individual Instances
EC2 Instances
Deployment Group
Code deployed to App Servers only
Deployment Groups
Deployment Group
WebTier AutoScaling Group AppTier AutoScaling Group
Image: https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-steps.html#deployment-steps-server
Putting It All Together
Deployment Components on AWS Lambda
Image: https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-steps.html#deployment-steps-server
DEMO TIME!
● Deployment Group
● Deployment Type
● Deployment Configurations
DEMO TIME!
● CodeDeploy for Lambda
○ Switch traffic to versions
○ Appspec file
Code Repo
AWS CodePipeline
AWS CodePipeline Big Picture
Code Repo
AWS CodePipeline
AWS CodePipeline Big Picture
Code Repo
AWS CodePipeline
AWS CodePipeline Benefits
● Rapid Delivery
● Configurable Workflow
● Fully Managed
● Easy Integration
○ With AWS Services
○ Third Party Tools
DEMO TIME!
● Overall Look & Feel in Console
DEMO TIME!
● Create a Simple Pipeline
GitHub
AWS CodeCommit
AWS CodePipeline
Power of this Pipeline
Code Repo
GitHub
AWS CodeCommit
AWS CodePipeline
CodeStar - What and Why
Primary Purpose Quickly develop. Build and deploy apps on AWS. Includes multiple
Serverless patterns
CI/CD
CodePipeline created. Each step is visualized.
Access to Code base Code be opened in IDE with one click. Natively integrated
with Cloud9.
Track Sprints and Issues Integrated with Jira and Github Issues. Can be tracked from
CodeStar
Manage Project Team Assign team member and roles from the service
AWS SAM
(Serverles
Application Model)
What is SAM
● Shorthand syntax to create Lambda, API,
Database, Event Source Mappings, Layers
○ Can write in plain CloudFormation but will
be much simpler in SAM
○ Converted into CloudFormation during
deployment
What is SAM
Creates
● Lambda
● API in API Gateway
● Put the Lambda as backend for /GET
Serverless
Framework
AWS SAM
AWS Chalice
Considerations for 3rd Party Frameworks
CONTAINER
Let’s Start from Beginning
What is Serverless What is Container
No servers to provision or manage
Standard unit of software that packages up code and all its
dependencies
Automatically scales with usage
Highly available
Serverless Services
Container Orchestrators
Serverless Container
Underlying infrastructure managed by Cloud Provider Users control underlying infrastructure - VM Size,
➢ Scales automatically OS, AMI etc.
➢ No Patching headache ➢ Requires management and orchestration
➢ Need to make master node HA, handle VM
failover, AMI rehydration etc.
Can’t install software (e.g. Webserver, Appserver) Install almost any software
in underlying environment ➢ Prepackaged images with different
➢ Code libraries can be installed softwares available
Serverless Container
Shines at event driven architectures Faster migration to cloud with other softwares
➢ Native integration with other services ➢ Webserver, Appserver
➢ Example - Triggered by S3, Kinesis ➢ App requires third party software
Microservices Microservices!
➢ API Gateway integration
➢ Code is modular without software ➢ Easy to move API with dependencies,
dependencies, e.g - python APIs e.g. Spring Boot with Discovery layer
➢ Easier to migrate Cloud native, green fields ➢ Consider cost and complexity for green
apps field
➢ Consider VPC Cold Start Latency
Kryptonite - For brown field monoliths to Lambda, Kryptonite - Steep learning curve with multitudes
major refactoring needed of choices along with significant Day 2 operational
overhead
Scaling of Lambda Vs Container
Serverless Container
Traffic
Amazon EKS
Traffic to Lambda
Traffic
Basically bunch of
Traffic K8 Master EC2s
Traffic to Lambda
Traffic to Lambda
C C C C C C
Traffic to Lambda
C C C C C C
Serverless Container
Amazon EKS
3 million/month, 512 MB Memory, 300 ms execution time, 3 million/month, 512 MB Memory, 300 ms execution time
unpredictable traffic
➢ $144/month (Control Plane) + $14.4 (t3.small worker
➢ $8/month node) = $160/month
➢ Cost will increase during higher spike coz of scaling
90 million/month, 512 MB memory, 250 ms execution time, 90 million/month, 512 MB memory, 300 ms execution time,
predictable traffic predictable traffic
➢ $206/month ➢ $144/month (Control Plane) + $28.8 (t3.medium worker
node) = $173/month
➢ Predictable traffic makes it possible to select proper
VM, higher CPU utilization
One is NOT cheaper or pricier than the other, it all depends on the use case
Parting Words
SERVERLESS
CONTAINER
“We don’t believe in one tool to rule the world. We want you to use the right tool for
the right job.”— Andy Jassy, CEO of AWS
Fargate - What & Why
● Both ECS and EKS requires managing Cluster and/or some infrastructure
● One size does NOT fit ALL - Can be cheaper or pricier than ECS/EKS based on usage
What is Docker/Container?
● Docker packages software into standardized units called containers that have
everything your software needs to run including libraries, code and runtime
● Lets you quickly deploy and scale applications into any environment
What is Container Orchestrator?
How Does Docker Work?
EC2s are like hyenas, if you see one, other ones are nearby.
● Deployment of Containers
● Redundancy and availability of Containers
● Scaling up or down of Containers
● Load Balancing
● Health Monitoring of Containers and Hosts
● Service Discovery
● And More...
Container Orchestrator
Say Hello to Container Orchestrators
● Docker Swarm
● Apache Mesos
● Kubernetes
○ EKS (Elastic Container Service for Kubernetes)
● AWS Fargate
Battle of Orchestrators
So it begins...
Control Plane - ECS & Kubernetes
Control Plane - Main entry point of Orchestrator. Interface to launch an application, query the
state or shut down
ECS
● Fully managed, highly available, highly scalable Control Plane
● You do NOT pay for Control Plane
Kubernetes
● Fully Open-Source, created by Google, run on any cloud or on-prem
● Run your own Control Plane on Host (such as EC2)
● You need to take care of selecting EC2 and scaling etc.
● AWS can manage Kubernetes Control Plane for you - EKS
● Pay for the Control Plane - either for underlying EC2 or AWS Managed EKS Control
Plane
Why Fargate?
● Both ECS and EKS requires managing Cluster and/or some infrastructure
● One size does NOT fit ALL - Can be cheaper or pricier than ECS/EKS based on usage
Fargate - What & Why
● Both ECS and EKS requires managing Cluster and/or some infrastructure
● One size does NOT fit ALL - Can be cheaper or pricier than ECS/EKS based on usage
Money Matters
1 task cost per ECS EKS Fargate
month
Control Plane Costs Zero, pay for Control Plane Costs 144$ (Dec Only pay for tasks based on CPU
worker nodes 2018), pay for worker nodes and Memory
Deeper integration with other AWS actively working on the Fargate currently runs on ECS,
AWS Services such as IAM, ALB integrations early days, more to come
etc.
Good for cloud native container Good for cloud native container Good for workload which runs for
architectures architectures, easier to move a duration, Fargate is expensive
on-prem Kubernetes to AWS if high CPU/Memory tasks runs
EKS all the time
Serverless Architectures &
Advanced Optimization
Techniques
Optimizing Your Lambda
Couple Words Before We Begin
• Your Function
• Actual Code
• Execution Environment
• The execution settings of the Lambda
Optimizing Your Function Code
Lambda Code Execution Under The Hood
Lambda
Lambda
Invoke
Invoke
import json
Libraries can be
lazy loaded too!
Lambda Environment Variables
Image: https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html
Seeing a cold start in AWS X-Ray
Image: https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html
Third Party Tools
Lambda performance already available from:
• Datadog
• Epsagon
• NodeSource
• IOPipe
• Thundra
Lambda Memory and Compute Goes Together
CPU
MEMORY
128 MB 56.13735sec
256 MB 26.43806sec
512 MB 12.68250sec
1024 MB 6.28947sec
Green==Best Red==Worst
https://s3.amazonaws.com/lambda-tools/pricing-calculator.html
Memory Vs Monthly Cost
Stats for Lambda function that calculates all prime numbers <= 30000 &
3000 times a month
AWS Lambda
service
● Operational excellence
● Security
● Reliability
● Performance efficiency
● Cost optimization
Refrence: https://d1.awsstatic.com/whitepapers/architecture/AWS-Serverless-Applications-Lens.pdf
Serverless - General Design Principles
Data Layer
● Persistent storage
● Secure mechanism to store states that your business logic will need
● Provides a mechanism to trigger events in response to data changes
News API
3
Save news and sentiment
Serverless - Design Scenarios
Web Application
Important: Always weigh your options unbiasedly, Lambda is not suppose to be all end all for all
design problems
Lambda VPC ENI Cold Start - No More!
Lambda VPC Networking
Lambda Networking with your VPC
Prior to VPC Improvements