SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
© 2015, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Guy Davies, Sophos Ltd.
October 2015
CMP407
Lambda as Cron
Scheduling Invocations in AWS Lambda
About me
• Guy Davies, Senior Systems Engineer, Sophos Ltd
Sophos use AWS extensively in our operations to support our anti-
malware, anti-spam, and threat-detection software and hardware
devices.
Also provide security products for AWS customers to complement their
cloud security profiles:
• UTM [ free trial available! ]
• Secure Server for Linux [ AMI available in Marketplace ]
www.sophos.com/aws
What to expect from the session
• How to schedule tasks in AWS Lambda
• Overview of the various options available
• Building up a pure Lambda scheduling infrastructure
• Resources and templates to implement this yourself
Events? Scheduling?
Why would I want to schedule Lambda?
• Lambda designed as event-driven computing
• Event-driven computing is awesome
• Most of the time you want to trigger because something
happens…
HOWEVER
Why would I want to schedule Lambda?
Sometimes you just plain need to do something on a
schedule.
Examples:
• Log cleanup
• Batching up statistics
• Alarm clock
• Infrastructure automation
Scheduling options on traditional infrastructure
Unix
• cron: recurring tasks
*/2 * * * * do_something
• at: run a task at a specific time
at 1615 oct 7 <<< “mail –s’AWS talk!’ guy.davies@sophos.com”
Windows
• Scheduled tasks
• AT
Options for scheduling Lambda functions (1)
1. Spin up an Amazon EC2 instance, and use crontab to
invoke Lambda
• Why bother running Lambda at all?
• Many folks want a pure-Lambda deployment
• Running an instance means more to manage
• Not hugely financially efficient
Options for scheduling Lambda functions (2)
2. Unreliable Town Clock (townclock.io)
• Awesome public Amazon SNS topic
• Chimes every fifteen minutes
• Community supported
• Has a 15 minute granularity
Options for scheduling Lambda functions (3)
3. Others…
• Trigger from Amazon SWF
• Trigger from an instance in AWS Data Pipeline
• Trigger from an AWS CloudTrail upload into an Amazon S3
bucket
All of these could be your solution! But what if we want a
“pure” Lambda implementation that’s managed by AWS?
A pure Lambda scheduler
How do we generate a timing signal in AWS?
0
0.2
0.4
0.6
0.8
1
Photo: ‘Signetics NE5555N, …’ by Stefan506 is
licenced by CC BY-SA 3.0. Source:
https://en.wikipedia.org/wiki/555_timer_IC
Amazon
CloudWatch
CloudWatch as a time signal
1. Set an alarm on a CloudWatch metric
2. Alarm goes into ALARM state:
• Triggers Amazon SNS which triggers Lambda
• Lambda inverts the state of the metric
3. Alarm goes into OK state:
• Triggers SNS which triggers Lambda
• Lambda inverts the state of the metric
Configuring the CloudWatch alarm
Configuring the CloudWatch alarm
Once the metric is
inverted, the alarm will
trigger at the top of the
next minute:
1-minute resolution
Configuring the CloudWatch alarm
All three states trigger the
same SNS notification. The
Lambda function figures
which was the trigger and
sets the CloudWatch
metric to the opposite state
Putting it together
Lambda
cron
function
CloudWatch
metric
CloudWatch alarm
triggers
SNS topic10
Invoke further Lambda
functions (if scheduled)
The Lambda function
Lambda function
1. The “event” is the SNS notification that is sent by
CloudWatch.
2. Invert the value of the CloudWatch metric.
3. Jobs and schedule are managed as a separate JSON
file in the bundle.
4. Invoke any Lambda functions in the schedule that are
scheduled to be run this minute.
5. Done.
Main Lambda function
exports.handler = function(event, context) {
async.waterfall([
function (callback) { flip_cloudwatch(event,callback); },
read_crontab,
execute_lambdas
], function (err) {
if (err) context.fail(err);
else context.succeed(); });
};
Flipping CloudWatch
The event is an SNS message from CloudWatch:
var snsmessage = JSON.parse(event.Records[0].Sns.Message);
If it’s just gone into alarm, we want to reset to zero. Likewise if it’s just gone into
OK, reset to 1.
if (snsmessage.NewStateValue == 'ALARM') { value = 0.0 }
else if (snsmessage.NewStateValue == 'OK' || snsmessage.NewStateValue ==
'INSUFFICIENT_DATA') { value = 1.0 };
Push the new value to CloudWatch:
var params = { MetricData: [ { MetricName: 'LambdaCron', Timestamp: new Date,
Unit: 'None', Value: value } ], Namespace: 'LambdaCron' };
cloudwatch.putMetricData(params, function(err, data) { . . . });
Crontab-like Lambda configuration
{
"jobs": [ {
"schedule": "*/3 * * * *",
"function": "testfunction",
"args": {
"key1": "test1",
"key3": "test3",
"key2": "test2"
}
} ]
}
Checking the schedule (1)
Use the fantastic cron-parser library (https://github.com/harrisiirak/cron-parser/
MIT licenced)
var parser = require('cron-parser');
Create a Date object which refers to the top of the current minute to compare
the schedule to.
var d = new Date();
d.setSeconds(0);
d.setMilliseconds(0);
Parse the crontab to find the ‘next’ runtime for the job (= now if it needs to run)
var interval =
parser.parseExpression(job["schedule"],{currentDate: d});
var runtime = interval.next();
Run each job that needs running
if (datestring == runtimestring) {
var lambda = new AWS.Lambda();
var params = {
FunctionName: job["function"],
InvocationType: "Event",
Payload: JSON.stringify(job["args"])
};
lambda.invoke(params, function(err,data) {
if (err) iteratorcallback(err);
else iteratorcallback(null);
});
}
}
Demo
Use cases
Trialling this for intelligent scaling on a schedule
• AWS scheduled scaling has limitations:
• Absolute number of desired instances
• Limit of 120 tasks per month
• Lambda function triggered by lambda-cron could do for
example:
• Every morning at 08:00 UTC, add 20% of capacity unless we
have > 30 instances already running
Reliability and monitoring
Empirically pretty reliable.
Running since April without (much!) intervention.
Even comes back after outages!
Reliability and monitoring
Monitoring: CloudWatch!
• Lambda invocation metrics will tell you that it’s running
• Application-level monitoring on the jobs you are
triggering
60 invocations / hr
Summary
1. Use CloudWatch alarms as two states to provide a
timing signal to Lambda.
2. Trigger off all three states to enhance reliability.
3. Allows us to schedule tasks purely within Lambda.
4. The cron function invokes once a minute.
Resources
Github:
github.com/g-a-d/lambda-cron
Email:
guy.davies@sophos.com
AWS
CloudFormation
stack
Lambda
function
Resources
Libraries used:
• async: https://github.com/caolan/async
• avoid nested-callback-hell (great for folks more used to
procedural programming)
• MIT license
• cron-parser: https://github.com/harrisiirak/cron-parser
• parse crontabs
• MIT license
Resources
Remember to check www.sophos.com/aws
• UTM for AWS (free trial available)
• Secure server for AWS
• Free trials, free home use AV
Remember to complete
your evaluations!
Thank you!

Contenu connexe

Tendances

Tendances (20)

Getting Started with Amazon WorkSpaces
 Getting Started with Amazon WorkSpaces Getting Started with Amazon WorkSpaces
Getting Started with Amazon WorkSpaces
 
Aws Solution Architecture Associate - summary
Aws Solution Architecture Associate - summaryAws Solution Architecture Associate - summary
Aws Solution Architecture Associate - summary
 
Aws vs. Azure: 5 Things You Need To Know
Aws vs. Azure: 5 Things You Need To KnowAws vs. Azure: 5 Things You Need To Know
Aws vs. Azure: 5 Things You Need To Know
 
AWS Security Hub
AWS Security HubAWS Security Hub
AWS Security Hub
 
AWS PPT.pptx
AWS PPT.pptxAWS PPT.pptx
AWS PPT.pptx
 
Amazon Lightsail: Jumpstart Your Cloud Project for a Low, Predictable Price.
Amazon Lightsail: Jumpstart Your Cloud Project for a Low, Predictable Price. Amazon Lightsail: Jumpstart Your Cloud Project for a Low, Predictable Price.
Amazon Lightsail: Jumpstart Your Cloud Project for a Low, Predictable Price.
 
Aws overview
Aws overviewAws overview
Aws overview
 
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
Introduction to AWS Cloud Computing | AWS Public Sector Summit 2016
 
An Introduction to AWS
An Introduction to AWSAn Introduction to AWS
An Introduction to AWS
 
Introduction to AWS VPC, Guidelines, and Best Practices
Introduction to AWS VPC, Guidelines, and Best PracticesIntroduction to AWS VPC, Guidelines, and Best Practices
Introduction to AWS VPC, Guidelines, and Best Practices
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
Cloud Computing and Amazon Web Services
Cloud Computing and Amazon Web ServicesCloud Computing and Amazon Web Services
Cloud Computing and Amazon Web Services
 
Best Practices for Getting Started with AWS
Best Practices for Getting Started with AWSBest Practices for Getting Started with AWS
Best Practices for Getting Started with AWS
 
Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)
Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)
Webinar AWS 201 - Using Amazon Virtual Private Cloud (VPC)
 
Serverless computing
Serverless computingServerless computing
Serverless computing
 
What is AWS?
What is AWS?What is AWS?
What is AWS?
 
Windows Virtual Desktop Powered By Microsoft Azure
Windows Virtual Desktop Powered By Microsoft AzureWindows Virtual Desktop Powered By Microsoft Azure
Windows Virtual Desktop Powered By Microsoft Azure
 
An introduction to Serverless
An introduction to ServerlessAn introduction to Serverless
An introduction to Serverless
 
Azure Active Directory | Microsoft Azure Tutorial for Beginners | Azure 70-53...
Azure Active Directory | Microsoft Azure Tutorial for Beginners | Azure 70-53...Azure Active Directory | Microsoft Azure Tutorial for Beginners | Azure 70-53...
Azure Active Directory | Microsoft Azure Tutorial for Beginners | Azure 70-53...
 

En vedette

Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...
Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...
Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...
ServerlessConf
 

En vedette (20)

AWS October Webinar Series - AWS Lambda Best Practices: Python, Scheduled Job...
AWS October Webinar Series - AWS Lambda Best Practices: Python, Scheduled Job...AWS October Webinar Series - AWS Lambda Best Practices: Python, Scheduled Job...
AWS October Webinar Series - AWS Lambda Best Practices: Python, Scheduled Job...
 
AWS re:Invent 2016: Using AWS Lambda to Build Control Systems for Your AWS In...
AWS re:Invent 2016: Using AWS Lambda to Build Control Systems for Your AWS In...AWS re:Invent 2016: Using AWS Lambda to Build Control Systems for Your AWS In...
AWS re:Invent 2016: Using AWS Lambda to Build Control Systems for Your AWS In...
 
Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...
Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...
Frederic Lavigne and Stephen Fink - Serverless Video Processing with IBM Blue...
 
Ben Kehoe - Serverless Architecture for the Internet of Things
Ben Kehoe - Serverless Architecture for the Internet of ThingsBen Kehoe - Serverless Architecture for the Internet of Things
Ben Kehoe - Serverless Architecture for the Internet of Things
 
AWS re:Invent 2016: What’s New with AWS Lambda (SVR202)
AWS re:Invent 2016: What’s New with AWS Lambda (SVR202)AWS re:Invent 2016: What’s New with AWS Lambda (SVR202)
AWS re:Invent 2016: What’s New with AWS Lambda (SVR202)
 
Real-time Data Processing with Amazon DynamoDB Streams and AWS Lambda
Real-time Data Processing with Amazon DynamoDB Streams and AWS LambdaReal-time Data Processing with Amazon DynamoDB Streams and AWS Lambda
Real-time Data Processing with Amazon DynamoDB Streams and AWS Lambda
 
Extreme Apache Spark: how in 3 months we created a pipeline that can process ...
Extreme Apache Spark: how in 3 months we created a pipeline that can process ...Extreme Apache Spark: how in 3 months we created a pipeline that can process ...
Extreme Apache Spark: how in 3 months we created a pipeline that can process ...
 
AWS Lambda Updates
AWS Lambda UpdatesAWS Lambda Updates
AWS Lambda Updates
 
Amazon Aurora: The New Relational Database Engine from Amazon
Amazon Aurora: The New Relational Database Engine from AmazonAmazon Aurora: The New Relational Database Engine from Amazon
Amazon Aurora: The New Relational Database Engine from Amazon
 
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel AvivSelf Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
Self Service Agile Infrastructure for Product Teams - Pop-up Loft Tel Aviv
 
Deep Dive: Amazon Elastic MapReduce
Deep Dive: Amazon Elastic MapReduceDeep Dive: Amazon Elastic MapReduce
Deep Dive: Amazon Elastic MapReduce
 
El uso de la c
El uso de la cEl uso de la c
El uso de la c
 
OAuth 2.0 refresher Talk
OAuth 2.0 refresher TalkOAuth 2.0 refresher Talk
OAuth 2.0 refresher Talk
 
EC2 Avanzado
EC2 AvanzadoEC2 Avanzado
EC2 Avanzado
 
Beyond Shuffling - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
Beyond Shuffling  - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...Beyond Shuffling  - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
Beyond Shuffling - Effective Tips and Tricks for Scaling Spark (Vancouver Sp...
 
Building a Serverless Pipeline
Building a Serverless PipelineBuilding a Serverless Pipeline
Building a Serverless Pipeline
 
Architecting for Greater Security on AWS
Architecting for Greater Security on AWSArchitecting for Greater Security on AWS
Architecting for Greater Security on AWS
 
Release the Monkeys ! Testing in the Wild at Netflix
Release the Monkeys !  Testing in the Wild at NetflixRelease the Monkeys !  Testing in the Wild at Netflix
Release the Monkeys ! Testing in the Wild at Netflix
 
Py.test
Py.testPy.test
Py.test
 
Survival Analysis of Web Users
Survival Analysis of Web UsersSurvival Analysis of Web Users
Survival Analysis of Web Users
 

Similaire à (CMP407) Lambda as Cron: Scheduling Invocations in AWS Lambda

Similaire à (CMP407) Lambda as Cron: Scheduling Invocations in AWS Lambda (20)

Getting Started with AWS Lambda and the Serverless Cloud
Getting Started with AWS Lambda and the Serverless CloudGetting Started with AWS Lambda and the Serverless Cloud
Getting Started with AWS Lambda and the Serverless Cloud
 
Getting Started with AWS Lambda and the Serverless Cloud
Getting Started with AWS Lambda and the Serverless CloudGetting Started with AWS Lambda and the Serverless Cloud
Getting Started with AWS Lambda and the Serverless Cloud
 
AWS April Webinar Series - AWS Lambda: Event-driven Code for Devices and the ...
AWS April Webinar Series - AWS Lambda: Event-driven Code for Devices and the ...AWS April Webinar Series - AWS Lambda: Event-driven Code for Devices and the ...
AWS April Webinar Series - AWS Lambda: Event-driven Code for Devices and the ...
 
AWS Lambda and Serverless Cloud
AWS Lambda and Serverless CloudAWS Lambda and Serverless Cloud
AWS Lambda and Serverless Cloud
 
SoCal NodeJS Meetup 20170215_aws_lambda
SoCal NodeJS Meetup 20170215_aws_lambdaSoCal NodeJS Meetup 20170215_aws_lambda
SoCal NodeJS Meetup 20170215_aws_lambda
 
Real-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS LambdaReal-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS Lambda
 
Infinite Scaling using Lambda and Aws - Atlogys Tech Talk
Infinite Scaling using Lambda and Aws - Atlogys Tech TalkInfinite Scaling using Lambda and Aws - Atlogys Tech Talk
Infinite Scaling using Lambda and Aws - Atlogys Tech Talk
 
Real-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS LambdaReal-time Data Processing Using AWS Lambda
Real-time Data Processing Using AWS Lambda
 
A Walk in the Cloud with AWS Lambda
A Walk in the Cloud with AWS LambdaA Walk in the Cloud with AWS Lambda
A Walk in the Cloud with AWS Lambda
 
February 2016 Webinar Series - Introducing VPC Support for AWS Lambda
February 2016 Webinar Series - Introducing VPC Support for AWS LambdaFebruary 2016 Webinar Series - Introducing VPC Support for AWS Lambda
February 2016 Webinar Series - Introducing VPC Support for AWS Lambda
 
DevOps, Microservices and Serverless Architecture
DevOps, Microservices and Serverless ArchitectureDevOps, Microservices and Serverless Architecture
DevOps, Microservices and Serverless Architecture
 
AWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless CloudAWS Lambda and the Serverless Cloud
AWS Lambda and the Serverless Cloud
 
AWS Summit Auckland - Getting Started with AWS Lambda and the Serverless Cloud
AWS Summit Auckland - Getting Started with AWS Lambda and the Serverless CloudAWS Summit Auckland - Getting Started with AWS Lambda and the Serverless Cloud
AWS Summit Auckland - Getting Started with AWS Lambda and the Serverless Cloud
 
AWS re:Invent 2016: Monitoring, Hold the Infrastructure: Getting the Most fro...
AWS re:Invent 2016: Monitoring, Hold the Infrastructure: Getting the Most fro...AWS re:Invent 2016: Monitoring, Hold the Infrastructure: Getting the Most fro...
AWS re:Invent 2016: Monitoring, Hold the Infrastructure: Getting the Most fro...
 
Monitoring, Hold the Infrastructure - Getting the Most out of AWS Lambda – Da...
Monitoring, Hold the Infrastructure - Getting the Most out of AWS Lambda – Da...Monitoring, Hold the Infrastructure - Getting the Most out of AWS Lambda – Da...
Monitoring, Hold the Infrastructure - Getting the Most out of AWS Lambda – Da...
 
Getting Started with AWS Lambda & Serverless Cloud
Getting Started with AWS Lambda & Serverless CloudGetting Started with AWS Lambda & Serverless Cloud
Getting Started with AWS Lambda & Serverless Cloud
 
Serverless computing with AWS Lambda
Serverless computing with AWS Lambda Serverless computing with AWS Lambda
Serverless computing with AWS Lambda
 
(CMP403) AWS Lambda: Simplifying Big Data Workloads
(CMP403) AWS Lambda: Simplifying Big Data Workloads(CMP403) AWS Lambda: Simplifying Big Data Workloads
(CMP403) AWS Lambda: Simplifying Big Data Workloads
 
Intro to AWS Lambda
Intro to AWS LambdaIntro to AWS Lambda
Intro to AWS Lambda
 
AWS Lambda
AWS LambdaAWS Lambda
AWS Lambda
 

Plus de Amazon Web Services

Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
Amazon Web Services
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
Amazon Web Services
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
Amazon Web Services
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
Amazon Web Services
 

Plus de Amazon Web Services (20)

Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
Come costruire servizi di Forecasting sfruttando algoritmi di ML e deep learn...
 
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
Big Data per le Startup: come creare applicazioni Big Data in modalità Server...
 
Esegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS FargateEsegui pod serverless con Amazon EKS e AWS Fargate
Esegui pod serverless con Amazon EKS e AWS Fargate
 
Costruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWSCostruire Applicazioni Moderne con AWS
Costruire Applicazioni Moderne con AWS
 
Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot Come spendere fino al 90% in meno con i container e le istanze spot
Come spendere fino al 90% in meno con i container e le istanze spot
 
Open banking as a service
Open banking as a serviceOpen banking as a service
Open banking as a service
 
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
Rendi unica l’offerta della tua startup sul mercato con i servizi Machine Lea...
 
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...OpsWorks Configuration Management: automatizza la gestione e i deployment del...
OpsWorks Configuration Management: automatizza la gestione e i deployment del...
 
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows WorkloadsMicrosoft Active Directory su AWS per supportare i tuoi Windows Workloads
Microsoft Active Directory su AWS per supportare i tuoi Windows Workloads
 
Computer Vision con AWS
Computer Vision con AWSComputer Vision con AWS
Computer Vision con AWS
 
Database Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatareDatabase Oracle e VMware Cloud on AWS i miti da sfatare
Database Oracle e VMware Cloud on AWS i miti da sfatare
 
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJSCrea la tua prima serverless ledger-based app con QLDB e NodeJS
Crea la tua prima serverless ledger-based app con QLDB e NodeJS
 
API moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e webAPI moderne real-time per applicazioni mobili e web
API moderne real-time per applicazioni mobili e web
 
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatareDatabase Oracle e VMware Cloud™ on AWS: i miti da sfatare
Database Oracle e VMware Cloud™ on AWS: i miti da sfatare
 
Tools for building your MVP on AWS
Tools for building your MVP on AWSTools for building your MVP on AWS
Tools for building your MVP on AWS
 
How to Build a Winning Pitch Deck
How to Build a Winning Pitch DeckHow to Build a Winning Pitch Deck
How to Build a Winning Pitch Deck
 
Building a web application without servers
Building a web application without serversBuilding a web application without servers
Building a web application without servers
 
Fundraising Essentials
Fundraising EssentialsFundraising Essentials
Fundraising Essentials
 
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
AWS_HK_StartupDay_Building Interactive websites while automating for efficien...
 
Introduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container ServiceIntroduzione a Amazon Elastic Container Service
Introduzione a Amazon Elastic Container Service
 

Dernier

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 

(CMP407) Lambda as Cron: Scheduling Invocations in AWS Lambda

  • 1. © 2015, Amazon Web Services, Inc. or its Affiliates. All rights reserved. Guy Davies, Sophos Ltd. October 2015 CMP407 Lambda as Cron Scheduling Invocations in AWS Lambda
  • 2. About me • Guy Davies, Senior Systems Engineer, Sophos Ltd Sophos use AWS extensively in our operations to support our anti- malware, anti-spam, and threat-detection software and hardware devices. Also provide security products for AWS customers to complement their cloud security profiles: • UTM [ free trial available! ] • Secure Server for Linux [ AMI available in Marketplace ] www.sophos.com/aws
  • 3. What to expect from the session • How to schedule tasks in AWS Lambda • Overview of the various options available • Building up a pure Lambda scheduling infrastructure • Resources and templates to implement this yourself
  • 5. Why would I want to schedule Lambda? • Lambda designed as event-driven computing • Event-driven computing is awesome • Most of the time you want to trigger because something happens… HOWEVER
  • 6. Why would I want to schedule Lambda? Sometimes you just plain need to do something on a schedule. Examples: • Log cleanup • Batching up statistics • Alarm clock • Infrastructure automation
  • 7. Scheduling options on traditional infrastructure Unix • cron: recurring tasks */2 * * * * do_something • at: run a task at a specific time at 1615 oct 7 <<< “mail –s’AWS talk!’ guy.davies@sophos.com” Windows • Scheduled tasks • AT
  • 8. Options for scheduling Lambda functions (1) 1. Spin up an Amazon EC2 instance, and use crontab to invoke Lambda • Why bother running Lambda at all? • Many folks want a pure-Lambda deployment • Running an instance means more to manage • Not hugely financially efficient
  • 9. Options for scheduling Lambda functions (2) 2. Unreliable Town Clock (townclock.io) • Awesome public Amazon SNS topic • Chimes every fifteen minutes • Community supported • Has a 15 minute granularity
  • 10. Options for scheduling Lambda functions (3) 3. Others… • Trigger from Amazon SWF • Trigger from an instance in AWS Data Pipeline • Trigger from an AWS CloudTrail upload into an Amazon S3 bucket All of these could be your solution! But what if we want a “pure” Lambda implementation that’s managed by AWS?
  • 11. A pure Lambda scheduler
  • 12. How do we generate a timing signal in AWS? 0 0.2 0.4 0.6 0.8 1 Photo: ‘Signetics NE5555N, …’ by Stefan506 is licenced by CC BY-SA 3.0. Source: https://en.wikipedia.org/wiki/555_timer_IC Amazon CloudWatch
  • 13. CloudWatch as a time signal 1. Set an alarm on a CloudWatch metric 2. Alarm goes into ALARM state: • Triggers Amazon SNS which triggers Lambda • Lambda inverts the state of the metric 3. Alarm goes into OK state: • Triggers SNS which triggers Lambda • Lambda inverts the state of the metric
  • 15. Configuring the CloudWatch alarm Once the metric is inverted, the alarm will trigger at the top of the next minute: 1-minute resolution
  • 16. Configuring the CloudWatch alarm All three states trigger the same SNS notification. The Lambda function figures which was the trigger and sets the CloudWatch metric to the opposite state
  • 17. Putting it together Lambda cron function CloudWatch metric CloudWatch alarm triggers SNS topic10 Invoke further Lambda functions (if scheduled)
  • 19. Lambda function 1. The “event” is the SNS notification that is sent by CloudWatch. 2. Invert the value of the CloudWatch metric. 3. Jobs and schedule are managed as a separate JSON file in the bundle. 4. Invoke any Lambda functions in the schedule that are scheduled to be run this minute. 5. Done.
  • 20. Main Lambda function exports.handler = function(event, context) { async.waterfall([ function (callback) { flip_cloudwatch(event,callback); }, read_crontab, execute_lambdas ], function (err) { if (err) context.fail(err); else context.succeed(); }); };
  • 21. Flipping CloudWatch The event is an SNS message from CloudWatch: var snsmessage = JSON.parse(event.Records[0].Sns.Message); If it’s just gone into alarm, we want to reset to zero. Likewise if it’s just gone into OK, reset to 1. if (snsmessage.NewStateValue == 'ALARM') { value = 0.0 } else if (snsmessage.NewStateValue == 'OK' || snsmessage.NewStateValue == 'INSUFFICIENT_DATA') { value = 1.0 }; Push the new value to CloudWatch: var params = { MetricData: [ { MetricName: 'LambdaCron', Timestamp: new Date, Unit: 'None', Value: value } ], Namespace: 'LambdaCron' }; cloudwatch.putMetricData(params, function(err, data) { . . . });
  • 22. Crontab-like Lambda configuration { "jobs": [ { "schedule": "*/3 * * * *", "function": "testfunction", "args": { "key1": "test1", "key3": "test3", "key2": "test2" } } ] }
  • 23. Checking the schedule (1) Use the fantastic cron-parser library (https://github.com/harrisiirak/cron-parser/ MIT licenced) var parser = require('cron-parser'); Create a Date object which refers to the top of the current minute to compare the schedule to. var d = new Date(); d.setSeconds(0); d.setMilliseconds(0); Parse the crontab to find the ‘next’ runtime for the job (= now if it needs to run) var interval = parser.parseExpression(job["schedule"],{currentDate: d}); var runtime = interval.next();
  • 24. Run each job that needs running if (datestring == runtimestring) { var lambda = new AWS.Lambda(); var params = { FunctionName: job["function"], InvocationType: "Event", Payload: JSON.stringify(job["args"]) }; lambda.invoke(params, function(err,data) { if (err) iteratorcallback(err); else iteratorcallback(null); }); } }
  • 25. Demo
  • 26. Use cases Trialling this for intelligent scaling on a schedule • AWS scheduled scaling has limitations: • Absolute number of desired instances • Limit of 120 tasks per month • Lambda function triggered by lambda-cron could do for example: • Every morning at 08:00 UTC, add 20% of capacity unless we have > 30 instances already running
  • 27. Reliability and monitoring Empirically pretty reliable. Running since April without (much!) intervention. Even comes back after outages!
  • 28. Reliability and monitoring Monitoring: CloudWatch! • Lambda invocation metrics will tell you that it’s running • Application-level monitoring on the jobs you are triggering 60 invocations / hr
  • 29. Summary 1. Use CloudWatch alarms as two states to provide a timing signal to Lambda. 2. Trigger off all three states to enhance reliability. 3. Allows us to schedule tasks purely within Lambda. 4. The cron function invokes once a minute.
  • 31. Resources Libraries used: • async: https://github.com/caolan/async • avoid nested-callback-hell (great for folks more used to procedural programming) • MIT license • cron-parser: https://github.com/harrisiirak/cron-parser • parse crontabs • MIT license
  • 32. Resources Remember to check www.sophos.com/aws • UTM for AWS (free trial available) • Secure server for AWS • Free trials, free home use AV